repo
string
commit
string
message
string
diff
string
nateware/dotfiles
ec6190b9d38e9e7e4bfb4315c0f885f2dd726c47
added mongodb
diff --git a/.bash_profile b/.bash_profile index 5ecf4f3..00f2ffa 100644 --- a/.bash_profile +++ b/.bash_profile @@ -1,7 +1,7 @@ [ -f $HOME/.bashrc ] && . $HOME/.bashrc -use_ruby=ruby-1.9.2 +use_ruby=ruby-1.9.2-p180 echo "Setting rvm ruby to: $use_ruby" rvm $use_ruby type ruby diff --git a/.bashrc b/.bashrc index caf223f..9cf8b5e 100644 --- a/.bashrc +++ b/.bashrc @@ -1,76 +1,79 @@ # ~/.bashrc export PS1='[\u@\h:\W]\$ ' alias ls='\ls -Gh' alias ll='ls -al' alias wget='curl -LO' alias ldd='otool -L' alias rsync='\rsync --exclude=.svn --exclude=.git --exclude=RCS' # Don't want local rubydocs - TOO SLOW! alias gi='gem install --no-ri --no-rdoc' # For Jeweler export JEWELER_OPTS='--bacon --create-repo --gemcutter' # ImageMagick export PATH="/usr/local/ImageMagick/bin:$PATH" export DYLD_LIBRARY_PATH="/usr/local/ImageMagick/lib" # MySQL export PATH="/usr/local/mysql/bin:$PATH" export DYLD_LIBRARY_PATH="/usr/local/mysql/lib" +# MongoDB +export PATH="$PATH:/usr/local/mongodb/bin" + # For Amazon EC2 export EC2_PRIVATE_KEY="$HOME/.ec2/pk-UO255XUYVOVVBXUWADA57YCL7XZZKQDE.pem" export EC2_CERT="$HOME/.ec2/cert-UO255XUYVOVVBXUWADA57YCL7XZZKQDE.pem" ec2_user=`cat $HOME/.ec2/ec2_user.txt` alias ess="ssh -i $HOME/.ec2/id_rsa-$ec2_user-keypair -o StrictHostKeyChecking=no -l root" alias esync="rsync -av -e 'ssh -i $HOME/.ec2/id_rsa-$ec2_user-keypair -o StrictHostKeyChecking=no -l root'" alias pss="ssh -i $HOME/.ec2/id_rsa-$ec2_user-user -o StrictHostKeyChecking=no -l $ec2_user" alias psync="rsync -av -e 'ssh -i $HOME/.ec2/id_rsa-$ec2_user-user -o StrictHostKeyChecking=no -l $ec2_user'" # For amazon-ec2 gem export AMAZON_ACCESS_KEY_ID=`cat $HOME/.ec2/access_key_id.txt` export AMAZON_SECRET_ACCESS_KEY=`cat $HOME/.ec2/secret_access_key.txt` export PLAYCO_ROOT=$HOME/Workspace/playerconnect if [ -d $PLAYCO_ROOT ]; then for file in $PLAYCO_ROOT/util/sh/*.sh do . $file done fi # Tools for EC2 export EC2_HOME=/usr/local/ec2-api-tools-current export PATH="$PATH:$EC2_HOME/bin" export JAVA_HOME=/Library/Java/Home # Put our ~/bin *first* export PATH="$HOME/bin:$HOME/sbin:/usr/local/bin:/usr/local/mysql/bin:/usr/local/git/bin:/usr/local/pgsql/bin:$PATH:/opt/local/bin:/opt/local/sbin" # For ruby version manager [ -s $HOME/.rvm/scripts/rvm ] && . $HOME/.rvm/scripts/rvm # Still needed for old games export ORACLE_HOME="/usr/local/oracle/10.2.0.4/client" export DYLD_LIBRARY_PATH="$DYLD_LIBRARY_PATH:$ORACLE_HOME/lib" export TNS_ADMIN="$HOME/Workspace/playerconnect/base/webservices/trunk/config" export NLS_LANG=".AL32UTF8" PATH="$PATH:$ORACLE_HOME/bin" function g { local current_link="$HOME/Workspace/current" if [ ! -d "$current_link" ]; then echo "No valid current project symlink: $current_link" >&2 return else local project=`readlink $current_link` [[ "$project" = /* ]] || project="$HOME/Workspace/$project" echo cd $project cd $project fi }
nateware/dotfiles
f8b5dde06805b3949d1645374fb3a5da048ae71a
basics
diff --git a/.bash_profile b/.bash_profile new file mode 100644 index 0000000..2bf37b9 --- /dev/null +++ b/.bash_profile @@ -0,0 +1,7 @@ +[ -f $HOME/.bashrc ] && . $HOME/.bashrc + +use_ruby=ruby-1.9.2-head +echo "Setting rvm ruby to: $use_ruby" +rvm $use_ruby +type ruby + diff --git a/.bashrc b/.bashrc new file mode 100644 index 0000000..0ccc8b2 --- /dev/null +++ b/.bashrc @@ -0,0 +1,68 @@ + +# ~/.bashrc +export PS1='[\u@\h:\W]\$ ' + +alias ls='\ls -Gh' +alias ll='ls -al' +alias wget='curl -LO' +alias ldd='otool -L' +alias rsync='\rsync --exclude=.svn --exclude=.git --exclude=RCS' + +# Don't want local rubydocs - TOO SLOW! +alias gi='gem install --no-ri --no-rdoc' + +# For Jeweler +export JEWELER_OPTS='--bacon --create-repo --gemcutter' + +# For Amazon EC2 +export EC2_PRIVATE_KEY="$HOME/.ec2/pk-UO255XUYVOVVBXUWADA57YCL7XZZKQDE.pem" +export EC2_CERT="$HOME/.ec2/cert-UO255XUYVOVVBXUWADA57YCL7XZZKQDE.pem" +ec2_user=`cat $HOME/.ec2/ec2_user.txt` +alias ess="ssh -i $HOME/.ec2/id_rsa-$ec2_user-keypair -o StrictHostKeyChecking=no -l root" +alias esync="rsync -av -e 'ssh -i $HOME/.ec2/id_rsa-$ec2_user-keypair -o StrictHostKeyChecking=no -l root'" +alias pss="ssh -i $HOME/.ec2/id_rsa-$ec2_user-user -o StrictHostKeyChecking=no -l $ec2_user" +alias psync="rsync -av -e 'ssh -i $HOME/.ec2/id_rsa-$ec2_user-user -o StrictHostKeyChecking=no -l $ec2_user'" + +# For amazon-ec2 gem +export AMAZON_ACCESS_KEY_ID=`cat $HOME/.ec2/access_key_id.txt` +export AMAZON_SECRET_ACCESS_KEY=`cat $HOME/.ec2/secret_access_key.txt` + +export PLAYCO_ROOT=$HOME/Workspace/playerconnect +if [ -d $PLAYCO_ROOT ]; then + for file in $PLAYCO_ROOT/util/sh/*.sh + do + . $file + done +fi + +# Tools for EC2 +export EC2_HOME=/usr/local/ec2-api-tools-current +export PATH="$PATH:$EC2_HOME/bin" +export JAVA_HOME=/Library/Java/Home + +# Put our ~/bin *first* +export PATH="$HOME/bin:$HOME/sbin:/usr/local/bin:/usr/local/mysql/bin:/usr/local/git/bin:/usr/local/pgsql/bin:$PATH:/opt/local/bin:/opt/local/sbin" + +# For ruby version manager +[ -s $HOME/.rvm/scripts/rvm ] && . $HOME/.rvm/scripts/rvm + +# Still needed for old games +export ORACLE_HOME="/usr/local/oracle/10.2.0.4/client" +export DYLD_LIBRARY_PATH="$ORACLE_HOME/lib" +export TNS_ADMIN="$HOME/Workspace/playerconnect/base/webservices/trunk/config" +export NLS_LANG=".AL32UTF8" +PATH="$PATH:$ORACLE_HOME/bin" + +function g { + local current_link="$HOME/Workspace/current" + if [ ! -d "$current_link" ]; then + echo "No valid current project symlink: $current_link" >&2 + return + else + local project=`readlink $current_link` + [[ "$project" = /* ]] || project="$HOME/Workspace/$project" + echo cd $project + cd $project + fi +} +
froydnj/chipz
75dfbc660a5a28161c57f115adf74c8a926bfc4d
ECL support
diff --git a/chipz.asd b/chipz.asd index 09f665e..b29747c 100644 --- a/chipz.asd +++ b/chipz.asd @@ -1,48 +1,48 @@ ; -*- mode: lisp -*- (cl:defpackage :chipz-system (:use :cl :asdf) (:export #:gray-streams)) (cl:in-package :chipz-system) (defclass txt-file (doc-file) ((type :initform "txt"))) (defclass css-file (doc-file) ((type :initform "css"))) (eval-when (:compile-toplevel :load-toplevel :execute) - #+(or sbcl lispworks openmcl cmu allegro clisp) + #+(or sbcl lispworks openmcl cmu allegro clisp ecl) (pushnew 'chipz-system:gray-streams cl:*features*)) (asdf:defsystem :chipz :version "0.8" :author "Nathan Froyd <froydnj@gmail.com>" :maintainer "Nathan Froyd <froydnj@gmail.com>" :description "A library for decompressing deflate, zlib, and gzip data" :license "BSD style" :components ((:static-file "NEWS") (:static-file "LICENSE") (:static-file "TODO") (:file "package") (:module "doc" :components ((:html-file "index") (:txt-file "chipz-doc") (:css-file "style"))) (:file "constants" :depends-on ("package")) (:file "types-and-tables" :depends-on ("constants")) (:file "crc32" :depends-on ("types-and-tables")) (:file "adler32" :depends-on ("types-and-tables")) (:file "conditions" :depends-on ("package")) (:file "dstate" :depends-on ("package")) (:file "inflate-state" :depends-on ("dstate" "crc32" "adler32")) (:file "gzip" :depends-on ("inflate-state" "conditions")) (:file "zlib" :depends-on ("inflate-state" "conditions")) (:file "inflate" :depends-on ("inflate-state" "gzip" "zlib" "conditions")) (:file "bzip2" :depends-on ("dstate" "constants")) (:file "decompress" :depends-on ("inflate-state" "inflate" "bzip2")) #+chipz-system:gray-streams (:file "stream" :depends-on ("inflate-state" "inflate")) #-chipz-system:gray-streams (:file "stream-fallback" :depends-on ("package")))) diff --git a/stream.lisp b/stream.lisp index 41d0018..85fd779 100644 --- a/stream.lisp +++ b/stream.lisp @@ -1,199 +1,206 @@ ;;;; stream.lisp -- gray stream wrappers for INFLATE (in-package :chipz) (eval-when (:compile-toplevel :load-toplevel) #-chipz-system:gray-streams (error "gray streams are not supported in this lisp implementation")) ;;; portability definitions +#+ecl +(eval-when (:compile-toplevel :load-toplevel :execute) + (gray::redefine-cl-functions)) + #+cmu (eval-when (:compile-toplevel :load-toplevel :execute) (require :gray-streams)) ;;; TRIVIAL-GRAY-STREAMS has it, we might as well, too... #+allegro (eval-when (:compile-toplevel :load-toplevel :execute) (unless (fboundp 'excl:stream-write-string) (require "streamc.fasl"))) (eval-when (:compile-toplevel :load-toplevel :execute) (defvar *binary-input-stream-class* #+lispworks 'stream:fundamental-binary-input-stream #+sbcl 'sb-gray:fundamental-binary-input-stream #+openmcl 'gray:fundamental-binary-input-stream #+cmu 'ext:fundamental-binary-input-stream #+allegro 'excl:fundamental-binary-input-stream - #+clisp 'gray:fundamental-binary-input-stream) + #+clisp 'gray:fundamental-binary-input-stream + #+ecl 'gray:fundamental-binary-input-stream) (defvar *stream-read-byte-function* #+lispworks 'stream:stream-read-byte #+sbcl 'sb-gray:stream-read-byte #+openmcl 'gray:stream-read-byte #+cmu 'ext:stream-read-byte #+allegro 'excl:stream-read-byte - #+clisp 'gray:stream-read-byte) + #+clisp 'gray:stream-read-byte + #+ecl 'gray:stream-read-byte) (defvar *stream-read-sequence-function* #+lispworks 'stream:stream-read-sequence #+sbcl 'sb-gray:stream-read-sequence #+openmcl 'ccl:stream-read-vector #+cmu 'ext:stream-read-sequence #+allegro 'excl:stream-read-sequence - #+clisp 'gray:stream-read-byte-sequence) + #+clisp 'gray:stream-read-byte-sequence + #+ecl 'gray:stream-read-sequence) ) ; EVAL-WHEN ;;; READ-SEQUENCE (defmacro define-stream-read-sequence (specializer &body body) (let ((definition `(cond ((not (typep seq 'simple-octet-vector)) (call-next-method)) (t (let ((end (or end (length seq)))) ,@body))))) - #+(or cmu sbcl allegro) + #+(or cmu sbcl allegro ecl) `(defmethod #.*stream-read-sequence-function* ((stream ,specializer) seq &optional (start 0) end) ,definition) #+(or lispworks openmcl) `(defmethod #.*stream-read-sequence-function* ((stream ,specializer) seq start end) ,definition) #+clisp `(defmethod #.*stream-read-sequence-function* ((stream ,specializer) seq &optional (start 0) end ,(gensym "no-hang") ,(gensym "interactive")) ,definition))) ;;; class definition (defclass decompressing-stream (#.*binary-input-stream-class*) ((wrapped-stream :initarg :stream :reader wrapped-stream) (dstate :initarg :dstate :reader dstate) (dfun :initarg :dfun :reader dfun) (input-buffer :initform (make-array 4096 :element-type '(unsigned-byte 8)) :reader input-buffer) (input-buffer-index :initform 0 :accessor input-buffer-index) (input-buffer-n-bytes :initform 0 :accessor input-buffer-n-bytes) (output-buffer :initform (make-array 4096 :element-type '(unsigned-byte 8)) :reader output-buffer) (output-buffer-index :initform 0 :accessor output-buffer-index) (output-buffer-n-bytes :initform 0 :accessor output-buffer-n-bytes))) ;;; constructors (defun make-decompressing-stream (format stream) (multiple-value-bind (state dfun) (ecase format ((:deflate :zlib :gzip deflate zlib gzip) (values (make-inflate-state format) #'%inflate)) ((:bzip2 bzip2) (values (make-bzip2-state) #'%bzip2-decompress))) (make-instance 'decompressing-stream :stream stream :dstate state :dfun dfun))) ;;; stream management (defun output-available-p (stream) (/= (output-buffer-index stream) (output-buffer-n-bytes stream))) (defun input-available-p (stream) (/= (input-buffer-index stream) (input-buffer-n-bytes stream))) (defun refill-stream-input-buffer (stream) (with-slots (input-buffer wrapped-stream input-buffer-index input-buffer-n-bytes) stream (let ((n-bytes-read (read-sequence input-buffer wrapped-stream))) (setf input-buffer-index 0 input-buffer-n-bytes n-bytes-read) #+nil (format *trace-output* "index: ~D | n-bytes ~D~%" input-buffer-index input-buffer-n-bytes) (values)))) (defun refill-stream-output-buffer (stream) (unless (input-available-p stream) (refill-stream-input-buffer stream)) (multiple-value-bind (bytes-read bytes-output) (funcall (the function (dfun stream)) (dstate stream) (input-buffer stream) (output-buffer stream) :input-start (input-buffer-index stream) :input-end (input-buffer-n-bytes stream)) (setf (output-buffer-index stream) 0 (output-buffer-n-bytes stream) bytes-output (input-buffer-index stream) (+ (input-buffer-index stream) bytes-read)) (assert (<= (input-buffer-index stream) (input-buffer-n-bytes stream))))) ;;; methods (defun read-and-decompress-byte (stream) (flet ((maybe-done () (when (output-available-p stream) (return-from read-and-decompress-byte (aref (output-buffer stream) (prog1 (output-buffer-index stream) (incf (output-buffer-index stream)))))))) ;; several input buffers may be used up before output is available ;; => read-byte should refill "something" while at all possible, ;; like read-sequence already does. (loop initially (maybe-done) do (refill-stream-output-buffer stream) (maybe-done) (unless (input-available-p stream) (refill-stream-input-buffer stream)) ;; If we didn't refill, then we must be all done. (unless (input-available-p stream) (finish-dstate (dstate stream)) (return :eof))))) (defun copy-existing-output (stream seq start end) (declare (type simple-octet-vector seq)) (let ((amount (min (- end start) (- (output-buffer-n-bytes stream) (output-buffer-index stream))))) (replace seq (output-buffer stream) :start1 start :end1 end :start2 (output-buffer-index stream) :end2 (output-buffer-n-bytes stream)) (incf (output-buffer-index stream) amount) (+ start amount))) (define-stream-read-sequence decompressing-stream (unless (typep seq 'simple-octet-vector) (return-from #.*stream-read-sequence-function* (call-next-method))) (loop initially (when (output-available-p stream) (setf start (copy-existing-output stream seq start end))) while (< start end) do (unless (input-available-p stream) (refill-stream-input-buffer stream)) ;; If we didn't refill, then we must be all done. (unless (input-available-p stream) (finish-dstate (dstate stream)) (loop-finish)) ;; Decompress directly into the user-provided buffer. (multiple-value-bind (bytes-read bytes-output) (funcall (the function (dfun stream)) (dstate stream) (input-buffer stream) seq :input-start (input-buffer-index stream) :input-end (input-buffer-n-bytes stream) :output-start start :output-end end) (incf (input-buffer-index stream) bytes-read) (incf start bytes-output)) finally (return start))) (defmethod #.*stream-read-byte-function* ((stream decompressing-stream)) (read-and-decompress-byte stream)) diff --git a/tests.lisp b/tests.lisp index c3888e3..a49e81e 100644 --- a/tests.lisp +++ b/tests.lisp @@ -1,215 +1,218 @@ ;; running the tests requires ;; - ASDF ;; - the salza2 library (http://www.xach.com/lisp/salza2) ;; - "bzip2" program (in PATH) ;; how to run the tests: ;; - load this file, tests.lisp, into your lisp environment ;; - create an empty directory, known hereafter as <test-files-dir> ;; - put some files into the directory, their extension shall be "uncompressed" ;; - compress the test files by running (chipz-tests:compress-test-files <test-files-dir>) ;; you only need to do this once ;; - execute (chipz-tests:run-all-tests <test-files-dir>) (asdf:oos 'asdf:load-op "chipz") (asdf:oos 'asdf:load-op "salza2") (defpackage :chipz-tests (:use :cl :chipz) (:export #:run-all-tests #:compress-test-files)) (in-package :chipz-tests) (defun test/whole-file (format compressed-pathname original-pathname) (with-open-file (compressed-stream compressed-pathname :direction :input :element-type '(unsigned-byte 8)) (with-open-file (stream original-pathname :direction :input :element-type '(unsigned-byte 8)) (let ((compressed-input (make-array (file-length compressed-stream) :element-type '(unsigned-byte 8))) (output (make-array (file-length stream) :element-type '(unsigned-byte 8))) (original (make-array (file-length stream) :element-type '(unsigned-byte 8))) (zstream (make-dstate format))) (let ((compressed-bytes (read-sequence compressed-input compressed-stream))) (read-sequence original stream) (multiple-value-bind (bytes-read bytes-output) (decompress output zstream compressed-input :input-end compressed-bytes) (and (= bytes-read compressed-bytes) (= bytes-output (length original)) (not (mismatch output original :end1 bytes-output :end2 bytes-output))))))))) (defun test/whole-file-cons (format compressed-pathname original-pathname) (with-open-file (compressed-stream compressed-pathname :direction :input :element-type '(unsigned-byte 8)) (with-open-file (stream original-pathname :direction :input :element-type '(unsigned-byte 8)) (let ((compressed-input (make-array (file-length compressed-stream) :element-type '(unsigned-byte 8))) (original (make-array (file-length stream) :element-type '(unsigned-byte 8)))) (read-sequence compressed-input compressed-stream) (let ((output (decompress nil format compressed-input))) (read-sequence original stream) (and (= (length original) (length output)) (not (mismatch output original)))))))) (defun test/incremental-file (format compressed-pathname original-pathname) (with-open-file (compressed-stream compressed-pathname :direction :input :element-type '(unsigned-byte 8)) (with-open-file (stream original-pathname :direction :input :element-type '(unsigned-byte 8)) (let ((compressed-input (make-array (file-length compressed-stream) :element-type '(unsigned-byte 8))) (output (make-array (file-length stream) :element-type '(unsigned-byte 8))) (original (make-array (file-length stream) :element-type '(unsigned-byte 8))) (zstream (make-dstate format))) (read-sequence original stream) (let ((compressed-bytes (read-sequence compressed-input compressed-stream)) (input-index 0) (output-index 0)) (loop (multiple-value-bind (bytes-read bytes-output) (decompress output zstream compressed-input :input-start input-index :input-end compressed-bytes :output-start output-index :output-end (1+ output-index)) (when (zerop bytes-output) (return)) (let ((ouch (mismatch original output :start1 output-index :start2 output-index :end1 (1+ output-index) :end2 (1+ output-index)))) (when ouch (return nil))) (incf input-index bytes-read) (incf output-index))) (and (= input-index compressed-bytes)) (= output-index (length original)) (not (mismatch output original :end1 output-index :end2 output-index))))))) #+chipz-system:gray-streams (defun test/gray-stream-read-sequence (format compressed-pathname original-pathname) (with-open-file (compressed-stream compressed-pathname :direction :input :element-type '(unsigned-byte 8)) (with-open-file (stream original-pathname :direction :input :element-type '(unsigned-byte 8)) (let ((zstream (make-decompressing-stream format compressed-stream)) (output (make-array (file-length stream) :element-type '(unsigned-byte 8))) (original (make-array (file-length stream) :element-type '(unsigned-byte 8)))) (read-sequence output zstream) (read-sequence original stream) (not (mismatch output original)))))) #+chipz-system:gray-streams (defun test/gray-stream-read-byte (format compressed-pathname original-pathname) (with-open-file (compressed-stream compressed-pathname :direction :input :element-type '(unsigned-byte 8)) (with-open-file (stream original-pathname :direction :input :element-type '(unsigned-byte 8)) (let ((zstream (make-decompressing-stream format compressed-stream)) (output (make-array (file-length stream) :element-type '(unsigned-byte 8))) (original (make-array (file-length stream) :element-type '(unsigned-byte 8)))) (loop for i from 0 below (file-length stream) do (progn (setf (aref output i) (read-byte zstream)) (setf (aref original i) (read-byte stream)))) (not (mismatch output original)))))) (defparameter *default-test-files-dir* (make-pathname :directory (append (pathname-directory *LOAD-TRUENAME*) '("test-files")) :device (pathname-device *LOAD-TRUENAME*) :host (pathname-host *LOAD-TRUENAME*))) (defparameter *test-functions* (list 'test/whole-file 'test/whole-file-cons 'test/incremental-file #+chipz-system:gray-streams 'test/gray-stream-read-sequence #+chipz-system:gray-streams 'test/gray-stream-read-byte)) (defparameter *formats* '(gzip zlib deflate bzip2)) (defmacro dolist/every ((var list-form) &body body) (let ((all-ok (gensym))) `(reduce (lambda (,all-ok ,var) (and (progn ,@body) ,all-ok)) ,list-form :initial-value t))) (defun run-all-tests (&optional (test-files-dir *default-test-files-dir*)) (labels ((run-test (testfun format uncompressed-file) (let ((compressed (make-pathname :type (symbol-name format) :defaults uncompressed-file))) (format t "; ~A ~A~%" (symbol-name testfun) compressed) (with-simple-restart (skip-test "skip ~A ~A" (symbol-name testfun) compressed) (assert (probe-file compressed)) (let* ((begin (get-internal-run-time)) (result (funcall testfun format compressed uncompressed-file)) (end (get-internal-run-time)) (secs (/ (- end begin) internal-time-units-per-second))) (if result (format t "; PASSED (~4$ seconds)~%" secs) (format t "; FAILED (~4$ seconds) ~A~%" secs result)) result))))) (let* ((uncompressed (make-pathname :name :wild :type "uncompressed" :defaults test-files-dir))) (dolist/every (testfun *test-functions*) (dolist/every (format *formats*) (dolist/every (file (directory uncompressed)) (run-test testfun format file))))))) (defun run-salza2 (compressor-class input-file output-file) (with-open-file (in-stream input-file :element-type '(unsigned-byte 8)) (with-open-file (out-stream output-file :element-type '(unsigned-byte 8) :direction :output :if-exists :supersede) (let ((buffer (make-array 100000 :element-type '(unsigned-byte 8))) (callback (salza2:make-stream-output-callback out-stream))) (salza2:with-compressor (comp compressor-class :callback callback) (loop (let ((bytes-read (read-sequence buffer in-stream))) (if (zerop bytes-read) (return) (salza2:compress-octet-vector buffer comp :end bytes-read))))))))) (defun run-external (output-file executable &rest args) #+lispworks (system:run-shell-command ;; cmd argv[0] argv[1..] (map 'vector #'identity (list* executable executable args)) :output output-file :if-output-exists :supersede) #+sbcl (sb-ext:run-program executable args :search t :output output-file :if-output-exists :supersede) #+openmcl (ccl:run-program executable args :output output-file :if-output-exists :supersede) #+cmu (extensions:run-program executable args :output output-file :if-output-exists :supersede) #+clisp (ext:run-program - executable :arguments args :output output-file :if-output-exists :overwrite) - #-(or lispworks sbcl openmcl cmu clisp) + executable :arguments args :output output-file :if-output-exists :overwrite) + #+ecl + (ext:run-program + executable args :output output-file :if-output-exists :supersede) + #-(or lispworks sbcl openmcl cmu clisp ecl) (error "run-external is not supported for this lisp implementation")) (defun compress-test-files (&optional (test-files-dir *default-test-files-dir*)) (let ((uncompressed (make-pathname :name :wild :type "uncompressed" :defaults test-files-dir))) (dolist (input (directory uncompressed)) (format t "; compressing ~A~%" input) (dolist (format *formats*) (let ((output (make-pathname :type (symbol-name format) :defaults input))) (ecase format (deflate (run-salza2 'salza2:deflate-compressor input output)) (zlib (run-salza2 'salza2:zlib-compressor input output)) (gzip (run-salza2 'salza2:gzip-compressor input output)) (bzip2 (run-external output "bzip2" "-c" (namestring input)))))))))
froydnj/chipz
c440d671e1fe8e25781de161b86baa26b5bb9f01
accommodate lists in DECOMPRESS
diff --git a/decompress.lisp b/decompress.lisp index c6f7249..e48aab8 100644 --- a/decompress.lisp +++ b/decompress.lisp @@ -1,216 +1,221 @@ (in-package :chipz) ;;; We provide several convenience functions for decompression: ;;; ;;; * decompress a buffer to a newly-consed buffer; ;;; * decompress a stream to a newly-consed buffer; ;;; * decompress a pathname to a newly-consed buffer; ;;; * decompress a buffer to a user-specified buffer; ;;; * decompress a buffer to a stream; ;;; * decompress a stream to a stream. ;;; * decompress a pathname to another pathname; ;;; * decompress a pathname to a stream; ;;; ;;; We do not provide stream->buffer decompression, as we have no way of ;;; knowing how much to read from the stream to fill the buffer, no way ;;; of determining what to do with possible state left in the ;;; INFLATE-STATE that we used, etc. Application-specific logic will ;;; have to handle those bits. (defgeneric decompress (output state input &key &allow-other-keys) (:method (output format input &rest keys) - (%decompress output format input keys))) + (%decompress output format input keys)) + ;; Accommodate people who want to use lists as input, possibly for + ;; experimenting with the API. + (:method (output format (input list) &rest keys) + (let ((vector (coerce input '(simple-array (unsigned-byte 8) (*))))) + (%decompress output format vector keys)))) (defun %decompress (output format input keys) (let ((state (make-dstate format))) (multiple-value-prog1 (apply #'decompress output state input keys) (finish-dstate state)))) ;;; SUBSEQ is specified to always make a copy. But we don't want an ;;; exact copy of a freshly-consed vector; that'd be wasteful. (defun maybe-subseq (v end) (if (= end (length v)) v (subseq v 0 end))) (defun decompress-fun-for-state (state) (typecase state (inflate-state #'%inflate) (bzip2-state #'%bzip2-decompress))) ;; For convenience. (defun %decompress-from-pathname (output state pathname buffer-size) (with-open-file (stream pathname :element-type '(unsigned-byte 8) :direction :input) (decompress output state stream :buffer-size (if (eq buffer-size :file-length) (file-length stream) buffer-size)))) (defmethod decompress ((output null) (state decompression-state) (input pathname) &key) (%decompress-from-pathname output state input :file-length)) (defmethod decompress ((output pathname) (state decompression-state) (input pathname) &key buffer-size) (check-type buffer-size (or null integer)) (with-open-file (stream output :element-type '(unsigned-byte 8) :direction :output) (%decompress-from-pathname stream state input buffer-size))) (defmethod decompress ((output stream) (state decompression-state) (input pathname) &key buffer-size) (check-type buffer-size (or null integer)) (%decompress-from-pathname output state input buffer-size)) (defun %decompress/null-vector (state input fun input-start input-end buffer-size) (declare (type function fun)) (loop with output = (make-array buffer-size :element-type '(unsigned-byte 8)) with output-start = 0 do (cond ((= output-start (length output)) ;; Reallocate the output buffer. (let ((new (make-array (* 2 (length output)) :element-type '(unsigned-byte 8)))) (setf output (replace new output)))) (t (multiple-value-bind (consumed produced) (funcall fun state input output :input-start input-start :input-end input-end :output-start output-start :output-end (length output)) (incf input-start consumed) (incf output-start produced) (when (or (dstate-done state) (and (or (>= input-start input-end) (zerop consumed)) (zerop produced))) (return-from %decompress/null-vector (maybe-subseq output output-start)))))))) (defmethod decompress ((output null) (state decompression-state) (input vector) &key (input-start 0) input-end buffer-size) (%decompress/null-vector state input (decompress-fun-for-state state) input-start (or input-end (length input)) (or buffer-size +default-buffer-size+))) (defun %decompress/null-stream (state input fun buffer-size) (declare (type function fun)) (let ((input-buffer (make-array 8192 :element-type '(unsigned-byte 8)))) (declare (dynamic-extent input-buffer)) (loop with input-start = 0 with input-end = 0 with output = (make-array buffer-size :element-type '(unsigned-byte 8)) with output-start = 0 initially (setf input-end (read-sequence input-buffer input)) do (cond ((= output-start (length output)) ;; Reallocate the output buffer. (let ((new (make-array (* 2 (length output)) :element-type '(unsigned-byte 8)))) (setf output (replace new output)))) (t (multiple-value-bind (consumed produced) (funcall fun state input-buffer output :input-start input-start :input-end input-end :output-start output-start) (incf input-start consumed) (incf output-start produced) (let ((input-consumed-p (>= input-start input-end))) ;; Get more input if possible. (when input-consumed-p (setf input-start 0 input-end (read-sequence input-buffer input))) (when (or (dstate-done state) (and (or (and input-consumed-p (zerop input-end)) (zerop consumed)) (zerop produced))) (return-from %decompress/null-stream (maybe-subseq output output-start)))))))))) (defmethod decompress ((output null) (state decompression-state) (input stream) &key buffer-size) (%decompress/null-stream state input (decompress-fun-for-state state) (or buffer-size +default-buffer-size+))) (defun %decompress/vector-vector (output state input fun input-start input-end output-start output-end) (declare (type simple-octet-vector input output)) (declare (type function fun)) (loop with n-bytes-consumed = 0 and n-bytes-produced = 0 do (multiple-value-bind (consumed produced) (funcall fun state input output :input-start input-start :input-end input-end :output-start output-start :output-end output-end) (incf input-start consumed) (incf output-start produced) (incf n-bytes-consumed consumed) (incf n-bytes-produced produced) (when (and (or (>= input-start input-end) (zerop consumed)) (or (>= output-start output-end) (zerop produced))) (return-from %decompress/vector-vector (values n-bytes-consumed n-bytes-produced)))))) (defmethod decompress ((output vector) (state decompression-state) (input vector) &key (input-start 0) input-end (output-start 0) output-end) (%decompress/vector-vector output state input (decompress-fun-for-state state) input-start (or input-end (length input)) output-start (or output-end (length output)))) (defun %decompress/stream-vector (output state input fun input-start input-end) (declare (type function fun)) (let ((buffer (make-array 8192 :element-type '(unsigned-byte 8)))) (declare (dynamic-extent buffer)) (loop (multiple-value-bind (consumed produced) (funcall fun state input buffer :input-start input-start :input-end input-end) (incf input-start consumed) (write-sequence buffer output :end produced) (when (or (dstate-done state) (and (or (>= input-start input-end) (zerop consumed)) (zerop produced))) (return-from %decompress/stream-vector output)))))) (defmethod decompress ((output stream) (state decompression-state) (input vector) &key (input-start 0) input-end) (%decompress/stream-vector output state input (decompress-fun-for-state state) input-start (or input-end (length input)))) (defun %decompress/stream-stream (output state input fun) (declare (type function fun)) (let ((input-buffer (make-array 8192 :element-type '(unsigned-byte 8))) (output-buffer (make-array 8192 :element-type '(unsigned-byte 8)))) (declare (dynamic-extent input-buffer output-buffer)) (loop with input-start = 0 with input-end = 0 initially (setf input-end (read-sequence input-buffer input)) do (multiple-value-bind (consumed produced) (funcall fun state input-buffer output-buffer :input-start input-start :input-end input-end) (incf input-start consumed) (write-sequence output-buffer output :end produced) (let ((input-consumed-p (>= input-start input-end))) (when input-consumed-p (setf input-start 0 input-end (read-sequence input-buffer input))) (when (or (dstate-done state) (and (or (and input-consumed-p (zerop input-end)) (zerop consumed)) (zerop produced))) (return-from %decompress/stream-stream output))))))) (defmethod decompress ((output stream) (state decompression-state) (input stream) &key) (%decompress/stream-stream output state input (decompress-fun-for-state state)))
froydnj/chipz
3cff04d1a3fdc400a7f37bb0239341cb30885952
fix typo in decompress.lisp
diff --git a/decompress.lisp b/decompress.lisp index ef50948..c6f7249 100644 --- a/decompress.lisp +++ b/decompress.lisp @@ -1,216 +1,216 @@ (in-package :chipz) ;;; We provide several convenience functions for decompression: ;;; ;;; * decompress a buffer to a newly-consed buffer; ;;; * decompress a stream to a newly-consed buffer; -;;; * decompress a pathane to a newly-consed buffer; +;;; * decompress a pathname to a newly-consed buffer; ;;; * decompress a buffer to a user-specified buffer; ;;; * decompress a buffer to a stream; ;;; * decompress a stream to a stream. ;;; * decompress a pathname to another pathname; ;;; * decompress a pathname to a stream; ;;; ;;; We do not provide stream->buffer decompression, as we have no way of ;;; knowing how much to read from the stream to fill the buffer, no way ;;; of determining what to do with possible state left in the ;;; INFLATE-STATE that we used, etc. Application-specific logic will ;;; have to handle those bits. (defgeneric decompress (output state input &key &allow-other-keys) (:method (output format input &rest keys) (%decompress output format input keys))) (defun %decompress (output format input keys) (let ((state (make-dstate format))) (multiple-value-prog1 (apply #'decompress output state input keys) (finish-dstate state)))) ;;; SUBSEQ is specified to always make a copy. But we don't want an ;;; exact copy of a freshly-consed vector; that'd be wasteful. (defun maybe-subseq (v end) (if (= end (length v)) v (subseq v 0 end))) (defun decompress-fun-for-state (state) (typecase state (inflate-state #'%inflate) (bzip2-state #'%bzip2-decompress))) ;; For convenience. (defun %decompress-from-pathname (output state pathname buffer-size) (with-open-file (stream pathname :element-type '(unsigned-byte 8) :direction :input) (decompress output state stream :buffer-size (if (eq buffer-size :file-length) (file-length stream) buffer-size)))) (defmethod decompress ((output null) (state decompression-state) (input pathname) &key) (%decompress-from-pathname output state input :file-length)) (defmethod decompress ((output pathname) (state decompression-state) (input pathname) &key buffer-size) (check-type buffer-size (or null integer)) (with-open-file (stream output :element-type '(unsigned-byte 8) :direction :output) (%decompress-from-pathname stream state input buffer-size))) (defmethod decompress ((output stream) (state decompression-state) (input pathname) &key buffer-size) (check-type buffer-size (or null integer)) (%decompress-from-pathname output state input buffer-size)) (defun %decompress/null-vector (state input fun input-start input-end buffer-size) (declare (type function fun)) (loop with output = (make-array buffer-size :element-type '(unsigned-byte 8)) with output-start = 0 do (cond ((= output-start (length output)) ;; Reallocate the output buffer. (let ((new (make-array (* 2 (length output)) :element-type '(unsigned-byte 8)))) (setf output (replace new output)))) (t (multiple-value-bind (consumed produced) (funcall fun state input output :input-start input-start :input-end input-end :output-start output-start :output-end (length output)) (incf input-start consumed) (incf output-start produced) (when (or (dstate-done state) (and (or (>= input-start input-end) (zerop consumed)) (zerop produced))) (return-from %decompress/null-vector (maybe-subseq output output-start)))))))) (defmethod decompress ((output null) (state decompression-state) (input vector) &key (input-start 0) input-end buffer-size) (%decompress/null-vector state input (decompress-fun-for-state state) input-start (or input-end (length input)) (or buffer-size +default-buffer-size+))) (defun %decompress/null-stream (state input fun buffer-size) (declare (type function fun)) (let ((input-buffer (make-array 8192 :element-type '(unsigned-byte 8)))) (declare (dynamic-extent input-buffer)) (loop with input-start = 0 with input-end = 0 with output = (make-array buffer-size :element-type '(unsigned-byte 8)) with output-start = 0 initially (setf input-end (read-sequence input-buffer input)) do (cond ((= output-start (length output)) ;; Reallocate the output buffer. (let ((new (make-array (* 2 (length output)) :element-type '(unsigned-byte 8)))) (setf output (replace new output)))) (t (multiple-value-bind (consumed produced) (funcall fun state input-buffer output :input-start input-start :input-end input-end :output-start output-start) (incf input-start consumed) (incf output-start produced) (let ((input-consumed-p (>= input-start input-end))) ;; Get more input if possible. (when input-consumed-p (setf input-start 0 input-end (read-sequence input-buffer input))) (when (or (dstate-done state) (and (or (and input-consumed-p (zerop input-end)) (zerop consumed)) (zerop produced))) (return-from %decompress/null-stream (maybe-subseq output output-start)))))))))) (defmethod decompress ((output null) (state decompression-state) (input stream) &key buffer-size) (%decompress/null-stream state input (decompress-fun-for-state state) (or buffer-size +default-buffer-size+))) (defun %decompress/vector-vector (output state input fun input-start input-end output-start output-end) (declare (type simple-octet-vector input output)) (declare (type function fun)) (loop with n-bytes-consumed = 0 and n-bytes-produced = 0 do (multiple-value-bind (consumed produced) (funcall fun state input output :input-start input-start :input-end input-end :output-start output-start :output-end output-end) (incf input-start consumed) (incf output-start produced) (incf n-bytes-consumed consumed) (incf n-bytes-produced produced) (when (and (or (>= input-start input-end) (zerop consumed)) (or (>= output-start output-end) (zerop produced))) (return-from %decompress/vector-vector (values n-bytes-consumed n-bytes-produced)))))) (defmethod decompress ((output vector) (state decompression-state) (input vector) &key (input-start 0) input-end (output-start 0) output-end) (%decompress/vector-vector output state input (decompress-fun-for-state state) input-start (or input-end (length input)) output-start (or output-end (length output)))) (defun %decompress/stream-vector (output state input fun input-start input-end) (declare (type function fun)) (let ((buffer (make-array 8192 :element-type '(unsigned-byte 8)))) (declare (dynamic-extent buffer)) (loop (multiple-value-bind (consumed produced) (funcall fun state input buffer :input-start input-start :input-end input-end) (incf input-start consumed) (write-sequence buffer output :end produced) (when (or (dstate-done state) (and (or (>= input-start input-end) (zerop consumed)) (zerop produced))) (return-from %decompress/stream-vector output)))))) (defmethod decompress ((output stream) (state decompression-state) (input vector) &key (input-start 0) input-end) (%decompress/stream-vector output state input (decompress-fun-for-state state) input-start (or input-end (length input)))) (defun %decompress/stream-stream (output state input fun) (declare (type function fun)) (let ((input-buffer (make-array 8192 :element-type '(unsigned-byte 8))) (output-buffer (make-array 8192 :element-type '(unsigned-byte 8)))) (declare (dynamic-extent input-buffer output-buffer)) (loop with input-start = 0 with input-end = 0 initially (setf input-end (read-sequence input-buffer input)) do (multiple-value-bind (consumed produced) (funcall fun state input-buffer output-buffer :input-start input-start :input-end input-end) (incf input-start consumed) (write-sequence output-buffer output :end produced) (let ((input-consumed-p (>= input-start input-end))) (when input-consumed-p (setf input-start 0 input-end (read-sequence input-buffer input))) (when (or (dstate-done state) (and (or (and input-consumed-p (zerop input-end)) (zerop consumed)) (zerop produced))) (return-from %decompress/stream-stream output))))))) (defmethod decompress ((output stream) (state decompression-state) (input stream) &key) (%decompress/stream-stream output state input (decompress-fun-for-state state)))
froydnj/chipz
3402c94df1d0af7742df08d3ffa23fd5c04c9bf2
release 0.8
diff --git a/NEWS b/NEWS index c4fba3b..3e96b13 100644 --- a/NEWS +++ b/NEWS @@ -1,111 +1,125 @@ hey emacs, show me an -*- mode: outline -*- -* Version +* Version 0.8, released 2013-01-14 ** bug fixes Stack overflow problems on several implementations have been fixed. (Thanks to Zach Beane for pointing this out.) +Anton Kovalenko contributed several fixes to the bzip2 code. + +Several bugs have been fixed with the Gray streams support. (Thanks to +Anton Kovalenko and Felix Lange for the fixes and zort on Github for a +bug report.) + +Gray streams support works with recent versions of Allegro Common Lisp. +(Thanks to Dave Cooper.) + ** improvements -consing when computing the CRC32 checksum for gzip has been reduced. +Consing when computing the CRC32 checksum for gzip has been reduced. (Thanks to Zach Beane for permission to pull his code from Salza.) +MAKE-DECOMPRESSING-STREAM now singals an error if Gray streams are not +supported. (Thanks to Felix Lange.) + ** new features A new method on DECOMPRESS has been added for decompressing files into memory. +CLISP now supports decompressing streams. (Thanks to Felix Lange.) + * Version 0.7.4, released 2009-10-26 ** bug fixes CRC32 checksums are now calculated properly. (Thanks to Sven Van Caekenberghe.) ** improvements READ-SEQUENCE is now supported on Gray streams, which may result in a significant performance boost. * Version 0.7.3, released 2009-05-09 ** bug fixes Checksum errors now throw the correct error, rather than complaining about an unknown checksum-mismatch error. (Thanks to _3b on #lisp.) Fixed an error when decompressing raw deflate data. (Thanks to _3b on #lisp.) Fixed an error in rare cases when reading checksums. (Thanks to _3b on #lisp.) * Version 0.7.2, released 2008-12-20 ** bug fixes Gray streams now work correctly. (Thanks to Austin Haas.) * Version 0.7.1, released 2008-12-17 ** bug fixes Fixed some errors related to confusion between keywords and CHIPZ symbols. (Thanks to Austin Haas and Tomas Zellerin.) * Version 0.7.0, released 2008-10-24 ** new features bzip2 decompression is now included. Please see the documentation for more details. ** improvements DECOMPRESS now supports the keyword argument :BUFFER-SIZE. Please see the documentation for more details. Checksum verification is now performed for gzip and zlib data. * Version 0.6.1, released 2008-10-03 ** bug fixes Various fixes have been applied to increase Chipz's portability. (Thanks to Zach Beane.) * Version 0.6.0, released 2008-09-27 ** new features Gray streams are now supported on Lispworks, CMUCL, Allegro, and OpenMCL. There has been a significant amount of optimization work done on the library and decompression shows better than order-of-magnitude speedups on SBCL. * Version 0.5.1, released 2008-02-09 ** bug fixes DECOMPRESS now handles :INPUT-END properly in all cases. (Thanks to Jeremy English.) * Version 0.5, released 2008-01-02 Completely redid the structure of the library. The API is now modeled after that of `zlib', with convenience functions added. Gray streams interfaces added. * Version 0.1.1, released 2006-01-27 Fixed PROCESS-NO-COMPRESS-BLOCK to read from the underlying stream, rather than the bitstream. (Thanks to Eric Marsden.) * Version 0.1, released 2006-01-27 Initial release. diff --git a/chipz.asd b/chipz.asd index 668cd32..09f665e 100644 --- a/chipz.asd +++ b/chipz.asd @@ -1,48 +1,48 @@ ; -*- mode: lisp -*- (cl:defpackage :chipz-system (:use :cl :asdf) (:export #:gray-streams)) (cl:in-package :chipz-system) (defclass txt-file (doc-file) ((type :initform "txt"))) (defclass css-file (doc-file) ((type :initform "css"))) (eval-when (:compile-toplevel :load-toplevel :execute) #+(or sbcl lispworks openmcl cmu allegro clisp) (pushnew 'chipz-system:gray-streams cl:*features*)) (asdf:defsystem :chipz - :version "0.7.4" + :version "0.8" :author "Nathan Froyd <froydnj@gmail.com>" :maintainer "Nathan Froyd <froydnj@gmail.com>" :description "A library for decompressing deflate, zlib, and gzip data" :license "BSD style" :components ((:static-file "NEWS") (:static-file "LICENSE") (:static-file "TODO") (:file "package") (:module "doc" :components ((:html-file "index") (:txt-file "chipz-doc") (:css-file "style"))) (:file "constants" :depends-on ("package")) (:file "types-and-tables" :depends-on ("constants")) (:file "crc32" :depends-on ("types-and-tables")) (:file "adler32" :depends-on ("types-and-tables")) (:file "conditions" :depends-on ("package")) (:file "dstate" :depends-on ("package")) (:file "inflate-state" :depends-on ("dstate" "crc32" "adler32")) (:file "gzip" :depends-on ("inflate-state" "conditions")) (:file "zlib" :depends-on ("inflate-state" "conditions")) (:file "inflate" :depends-on ("inflate-state" "gzip" "zlib" "conditions")) (:file "bzip2" :depends-on ("dstate" "constants")) (:file "decompress" :depends-on ("inflate-state" "inflate" "bzip2")) #+chipz-system:gray-streams (:file "stream" :depends-on ("inflate-state" "inflate")) #-chipz-system:gray-streams (:file "stream-fallback" :depends-on ("package")))) diff --git a/doc/index.html b/doc/index.html index 5e0ed91..6f4ebcb 100644 --- a/doc/index.html +++ b/doc/index.html @@ -1,86 +1,86 @@ <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <HTML><HEAD><TITLE>Chipz</TITLE><LINK TYPE="text/css" TITLE="default" REL="stylesheet" MEDIA="screen" HREF="style.css" /></HEAD><BODY><H1>Chipz</H1><P>Chipz is a library for decompressing DEFLATE and BZIP2 data. DEFLATE data, defined in <A HREF="http://www.ietf.org/rfc/rfc1951.txt">RFC1951</A>, forms the core of popular compression formats such as zlib (<A HREF="http://www.ietf.org/rfc/rfc1950.txt">RFC 1950</A>) and gzip (<A HREF="http://www.ietf.org/rfc/rfc1952.txt">RFC 1952</A>). As such, Chipz also provides for decompressing data in those formats as well. BZIP2 is the format used by the popular compression -tool <A HREF="http://www.bzip.org/">bzip2</A>.</P><P>Chipz is the reading complement to <A HREF="http://www.xach.com/salza2/">Salza</A>.</P><H2>Installation</H2><P>Chipz can be downloaded at <A HREF="http://www.method-combination.net/lisp/files/chipz.tar.gz">http://www.method-combination.net/lisp/files/chipz.tar.gz</A>. The latest version is 0.7.4.</P><P>It comes with an ASDF system definition, so <TT>(ASDF:OOS +tool <A HREF="http://www.bzip.org/">bzip2</A>.</P><P>Chipz is the reading complement to <A HREF="http://www.xach.com/salza2/">Salza</A>.</P><H2>Installation</H2><P>Chipz can be downloaded at <A HREF="http://www.method-combination.net/lisp/files/chipz.tar.gz">http://www.method-combination.net/lisp/files/chipz.tar.gz</A>. The latest version is 0.8.</P><P>It comes with an ASDF system definition, so <TT>(ASDF:OOS 'ASDF:LOAD-OP :CHIPZ)</TT> should be all that you need to get started.</P><H2>License</H2><P>Chipz is released under a MIT-like license; you can do pretty much anything you want to with the code except claim that you wrote it.</P><H2>Using the library</H2><P>The main function of the library is <TT>decompress</TT>:</P><DIV CLASS="lisp-symbol"><A NAME="decompress"></A><TT><STRONG>decompress</STRONG> <EM>output</EM> <EM>state</EM> <EM>input</EM> <EM><TT>&key</TT></EM> <EM><TT>&allow-other-keys</TT></EM> =&gt; <EM>output</EM></TT><BR /></DIV><P>Five distinct use cases are covered by this single function:</P><UL><LI>Decompressing from an octet vector to a fresh octet vector;</LI><LI>Decompressing from a stream to a fresh octet vector;</LI><LI>Decompressing from an octet vector to a user-specified octet vector;</LI><LI>Decompressing from an octet vector to a stream;</LI><LI>Decompressing from a stream to a stream;</LI></UL><TABLE CLASS="note"><TR><TD CLASS="title">Note</TD><TD CLASS="content">Chipz does not provide for decompressing data from a stream to a user-specified buffer, as the buffer management involved cannot be done automatically by the library--the application must be involved in this case.</TD></TR></TABLE><H3><A NAME="one-shot"></A>One-shot decompression</H3><P>The first and second use cases above are intended to be convenient "one-shot" decompression methods. Therefore, although the description of the following methods attached to this generic function have an <TT>decompression-state</TT> parameter, as returned by <A HREF="#make-dstate" STYLE="symbol">make-dstate</A>, respectively, the usual way to use them will be to provide a <TT>format</TT> argument. This <TT>format</TT> argument should be one of:</P><UL><LI><TT>chipz:bzip2</TT> for decompressing data in the bzip2 format;</LI><LI><TT>chipz:gzip</TT> for decompressing data in the gzip format;</LI><LI><TT>chipz:zlib</TT> for decompressing data in the zlib format;</LI><LI><TT>chipz:deflate</TT> for decompressing data in the deflate format.</LI></UL><P>The <TT>format</TT> argument can also be a keyword, such as <TT>:gzip</TT>, for backwards compatibility. Using symbols in the <TT>CHIPZ</TT> package is preferred, however.</P><P>Most applications will use <TT>chipz:gzip</TT> or <TT>chipz:bzip2</TT>, a -few applications will use <TT>chipz:zlib</TT>, and uses of <TT>chipz:deflate</TT> will probably be few and far between.</P><P>All the method signatures described below also accept a <TT>format</TT> argument in lieu of an <TT>decompression-state</TT> argument.</P><P>The signatures of the first two methods are as follows.</P><DIV CLASS="lisp-symbol"><A NAME="decompress"></A><TT><STRONG>decompress</STRONG> <EM>(output null)</EM> <EM>(state decompression-state)</EM> <EM>(input vector)</EM> <EM><TT>&key</TT></EM> <EM>(input-start 0)</EM> <EM>input-end</EM> <EM>buffer-size</EM> <EM><TT>&allow-other-keys</TT></EM> =&gt; <EM>output</EM></TT><BR /></DIV><DIV CLASS="lisp-symbol"><A NAME="decompress"></A><TT><STRONG>decompress</STRONG> <EM>(output null)</EM> <EM>(state decompression-state)</EM> <EM>(input stream)</EM> <EM><TT>&key</TT></EM> <EM>buffer-size</EM> <EM><TT>&allow-other-keys</TT></EM> =&gt; <EM>output</EM></TT><BR /></DIV><P>A simple function to retrieve the contents of a gzip-compressed +few applications will use <TT>chipz:zlib</TT>, and uses of <TT>chipz:deflate</TT> will probably be few and far between.</P><P>All the method signatures described below also accept a <TT>format</TT> argument in lieu of an <TT>decompression-state</TT> argument.</P><P>The signatures of the first two methods are as follows.</P><DIV CLASS="lisp-symbol"><A NAME="decompress"></A><TT><STRONG>decompress</STRONG> <EM>(output null)</EM> <EM>(state decompression-state)</EM> <EM>(input vector)</EM> <EM><TT>&key</TT></EM> <EM>(input-start 0)</EM> <EM>input-end</EM> <EM>buffer-size</EM> =&gt; <EM>output</EM></TT><BR /></DIV><DIV CLASS="lisp-symbol"><A NAME="decompress"></A><TT><STRONG>decompress</STRONG> <EM>(output null)</EM> <EM>(state decompression-state)</EM> <EM>(input stream)</EM> <EM><TT>&key</TT></EM> <EM>buffer-size</EM> =&gt; <EM>output</EM></TT><BR /></DIV><P>A simple function to retrieve the contents of a gzip-compressed file, then, might be:</P><PRE>(defun gzip-contents (pathname) (with-open-file (stream pathname :direction :input :element-type '(unsigned-byte 8)) (chipz:decompress nil 'chipz:gzip stream)))</PRE><P>These one-shot methods also support a <TT>:buffer-size</TT> argument as a hint of the size of decompressed data. The library uses this to pre-allocate the output buffer to the hinted size. Therefore, if you know the size of the decompressed data or have a good estimate, fewer allocations will be done, leading to slightly better performance. If <TT>:buffer-size</TT> is not provided or proves to be too small, the library will of course grow the output buffer as necessary.</P><H3>Decompressing to a vector</H3><P>An alternate way to deal with compressed data is to read in a buffer's worth of data, decompress the buffer, and then deal with any remaining input and the produced output, looping to read and process more data as appropriate. This scheme is the third use case described above and is handled in zlib with the <TT>inflate</TT> -function. In Chipz, it is just another method of <TT>decompress</TT>.</P><DIV CLASS="lisp-symbol"><A NAME="decompress"></A><TT><STRONG>decompress</STRONG> <EM>(output vector)</EM> <EM>(state decompression-state)</EM> <EM>(input vector)</EM> <EM><TT>&key</TT></EM> <EM>(input-start 0)</EM> <EM>input-end</EM> <EM>(output-start 0)</EM> <EM>output-end</EM> <EM><TT>&allow-other-keys</TT></EM> =&gt; <EM>n-bytes-consumed</EM>, <EM>n-bytes-produced</EM></TT><BR /></DIV><P>This method decompresses the data from <EM>input</EM> between <EM>input-start</EM> and <EM>input-end</EM> and place the uncompressed data in <EM>output</EM>, limited by <EM>output-start</EM> and <EM>output-end</EM>. Please +function. In Chipz, it is just another method of <TT>decompress</TT>.</P><DIV CLASS="lisp-symbol"><A NAME="decompress"></A><TT><STRONG>decompress</STRONG> <EM>(output vector)</EM> <EM>(state decompression-state)</EM> <EM>(input vector)</EM> <EM><TT>&key</TT></EM> <EM>(input-start 0)</EM> <EM>input-end</EM> <EM>(output-start 0)</EM> <EM>output-end</EM> =&gt; <EM>n-bytes-consumed</EM>, <EM>n-bytes-produced</EM></TT><BR /></DIV><P>This method decompresses the data from <EM>input</EM> between <EM>input-start</EM> and <EM>input-end</EM> and place the uncompressed data in <EM>output</EM>, limited by <EM>output-start</EM> and <EM>output-end</EM>. Please note that it is possible to consume some or all of the input without producing any output and to produce some or all of the output without consuming any input.</P><P>As above, you can use a <TT>format</TT> argument instead of an <TT>decompression-state</TT>. You will usually not want to do this unless you know exactly how large the decompressed data is going to be; otherwise, you will only decompress a portion of the data and any intermediate state required to decompress the remainder of the data will be thrown away.</P><H3>Decompressing to a stream</H3><P>Finally, <TT>decompress</TT> can also be used to write the decompressed data directly to a stream, enabling a poor man's gunzip function:</P><PRE>(defun gunzip (gzip-filename output-filename) (with-open-file (gzstream gzip-filename :direction :input :element-type '(unsigned-byte 8)) (with-open-file (stream output-filename :direction :output :element-type '(unsigned-byte 8) :if-exists :supersede) (chipz:decompress stream 'chipz:gzip gzstream) - output-filename)))</PRE><P>The relevant methods in this case are:</P><DIV CLASS="lisp-symbol"><A NAME="decompress"></A><TT><STRONG>decompress</STRONG> <EM>(output stream)</EM> <EM>(state decompression-state)</EM> <EM>(input vector)</EM> <EM><TT>&key</TT></EM> <EM>(input-start 0)</EM> <EM>input-end</EM> <EM><TT>&allow-other-keys</TT></EM> =&gt; <EM>stream</EM></TT><BR /></DIV><DIV CLASS="lisp-symbol"><A NAME="decompress"></A><TT><STRONG>decompress</STRONG> <EM>(output stream)</EM> <EM>(state decompression-state)</EM> <EM>(input stream)</EM> <EM><TT>&allow-other-keys</TT></EM> =&gt; <EM>stream</EM></TT><BR /></DIV><P>Both return the output stream.</P><H3>Creating <TT>decompression-state</TT> objects</H3><P>The core data structure of Chipz is a <TT>decompression-state</TT>, which stores the internal state of an ongoing + output-filename)))</PRE><P>The relevant methods in this case are:</P><DIV CLASS="lisp-symbol"><A NAME="decompress"></A><TT><STRONG>decompress</STRONG> <EM>(output stream)</EM> <EM>(state decompression-state)</EM> <EM>(input vector)</EM> <EM><TT>&key</TT></EM> <EM>(input-start 0)</EM> <EM>input-end</EM> =&gt; <EM>stream</EM></TT><BR /></DIV><DIV CLASS="lisp-symbol"><A NAME="decompress"></A><TT><STRONG>decompress</STRONG> <EM>(output stream)</EM> <EM>(state decompression-state)</EM> <EM>(input stream)</EM> =&gt; <EM>stream</EM></TT><BR /></DIV><P>Both return the output stream.</P><H3>Creating <TT>decompression-state</TT> objects</H3><P>The core data structure of Chipz is a <TT>decompression-state</TT>, which stores the internal state of an ongoing decompression process. You create a <TT>decompression-state</TT> with <A HREF="#make-dstate" STYLE="symbol">make-dstate</A>.</P><DIV CLASS="lisp-symbol"><A NAME="make-dstate"></A><TT><STRONG>make-dstate</STRONG> <EM>format</EM> =&gt; <EM>dstate</EM></TT><BR /></DIV><P>Return an <TT>decompression-state</TT> object suitable for uncompressing data in <EM>data-format</EM>. <EM>data-format</EM> should be:</P><UL><LI><TT>chipz:bzip2</TT> for decompressing data in the bzip2 format;</LI><LI><TT>chipz:gzip</TT> for decompressing data in the gzip format;</LI><LI><TT>chipz:zlib</TT> for decompressing data in the zlib format;</LI><LI><TT>chipz:deflate</TT> for decompressing data in the deflate format.</LI></UL><P>As with <A HREF="#decompress" STYLE="symbol">decompress</A>, you can use keywords instead, but doing so is deprecated.</P><P>Prior to adding bzip2 support, Chipz supported only deflate-based formats. <A HREF="#make-inflate-state" STYLE="symbol">make-inflate-state</A> was the primary interface then; it is now deprecated, but kept around for backwards compatibility.</P><DIV CLASS="lisp-symbol"><A NAME="make-inflate-state"></A><TT><STRONG>make-inflate-state</STRONG> <EM>format</EM> =&gt; <EM>inflate-state</EM></TT><BR /></DIV><P><A HREF="#make-inflate-state" STYLE="symbol">make-inflate-state</A> supports the same <EM>data-format</EM> arguments as <A HREF="#make-dstate" STYLE="symbol">make-dstate</A> does, with the obvious exception of <EM>chipz:bzip2</EM>. The <TT>inflate-state</TT> object returned is a <TT>decompression-state</TT>, so it can be passed to <A HREF="#decompress" STYLE="symbol">decompress</A> and <A HREF="#finish-dstate" STYLE="symbol">finish-dstate</A>.</P><P>Once you are done with a <TT>decompression-state</TT> object, you must call <A HREF="#finish-dstate" STYLE="symbol">finish-dstate</A> on it. <A HREF="#finish-dstate" STYLE="symbol">finish-dstate</A> checks that the given <EM>state</EM> decompressed all the data in a given stream. It does not dispose of any resources associated with <EM>state</EM>; it is meant purely as an error-checking construct. Therefore, it is inappropriate to call from, say, the cleanup forms of <TT>UNWIND-PROTECT</TT>. The cleanup forms may be run when an error is thrown during decompression and of course the stream will only be partially decompressed at that point.</P><DIV CLASS="lisp-symbol"><A NAME="finish-dstate"></A><TT><STRONG>finish-dstate</STRONG> <EM>state</EM> =&gt; <EM>t</EM></TT><BR /></DIV><P><A HREF="#finish-inflate-state" STYLE="symbol">finish-inflate-state</A> does the same thing, but only for <TT>inflate-state</TT>. Its use, like that of <A HREF="#make-inflate-state" STYLE="symbol">make-inflate-state</A> is deprecated.</P><DIV CLASS="lisp-symbol"><A NAME="finish-inflate-state"></A><TT><STRONG>finish-inflate-state</STRONG> <EM>state</EM> =&gt; <EM>t</EM></TT><BR /></DIV><H2>Gray streams</H2><P>Chipz includes support for creating Gray streams to wrap streams containing compressed data and read the uncompressed data from those streams. SBCL, Allegro, Lispworks, CMUCL, and OpenMCL are supported at this time.</P><DIV CLASS="lisp-symbol"><A NAME="make-decompressing-stream"></A><TT><STRONG>make-decompressing-stream</STRONG> <EM>format</EM> <EM>stream</EM> =&gt; <EM>decompressing-stream</EM></TT><BR /></DIV><P>Return a stream that provides transparent decompression of the data from <EM>stream</EM> in <EM>format</EM>. That is, <TT>read-byte</TT> and <TT>read-sequence</TT> will decompress the data read from <EM>stream</EM> and return portions of the decompressed data as requested. <EM>format</EM> is as in the <A HREF="#one-shot">one-shot decompression methods</A>.</P><H2>Conditions</H2><DIV CLASS="lisp-symbol"><A NAME="chipz-error"></A><TT><STRONG>chipz-error</STRONG></TT><BR /></DIV><P>All errors signaled by Chipz are of this type.</P><DIV CLASS="lisp-symbol"><A NAME="invalid-format-error"></A><TT><STRONG>invalid-format-error</STRONG></TT><BR /></DIV><P>This error is signaled when the <EM>format</EM> argument to <A HREF="#decompress" STYLE="symbol">decompress</A> or <A HREF="#make-dstate" STYLE="symbol">make-dstate</A> is not one of the symbols specified for <A HREF="#make-dstate" STYLE="symbol">make-dstate</A>. This error is also signaled in <A HREF="#make-inflate-state" STYLE="symbol">make-inflate-state</A> if the <EM>format</EM> argument is not valid for that function.</P><DIV CLASS="lisp-symbol"><A NAME="decompression-error"></A><TT><STRONG>decompression-error</STRONG></TT><BR /></DIV><P>All errors signaled during decompression are of this type.</P><DIV CLASS="lisp-symbol"><A NAME="invalid-checksum-error"></A><TT><STRONG>invalid-checksum-error</STRONG></TT><BR /></DIV><P>The zlib, gzip, and bzip2 formats all contain checksums to verify the integrity of the uncompressed data; this error is signaled when the stored checksum is found to be inconsistent with the checksum computed by Chipz. It indicates that the compressed data has probably been corrupted in some fashion (or there is an error in Chipz).</P><DIV CLASS="lisp-symbol"><A NAME="premature-end-of-stream"></A><TT><STRONG>premature-end-of-stream</STRONG></TT><BR /></DIV><P>This error is signaled when <A HREF="#finish-dstate" STYLE="symbol">finish-dstate</A> is called on an <TT>decompression-state</TT> that has not finished processing an entire decompressed data stream.</P><DIV CLASS="lisp-symbol"><A NAME="inflate-error"></A><TT><STRONG>inflate-error</STRONG></TT><BR /></DIV><P>All errors signaled while decompressing deflate-based formats are of this type.</P><DIV CLASS="lisp-symbol"><A NAME="invalid-zlib-header-error"></A><TT><STRONG>invalid-zlib-header-error</STRONG></TT><BR /></DIV><P>This error is signaled when an invalid zlib header is read.</P><DIV CLASS="lisp-symbol"><A NAME="invalid-gzip-header-error"></A><TT><STRONG>invalid-gzip-header-error</STRONG></TT><BR /></DIV><P>This error is signaled when an invalid gzip header is read.</P><DIV CLASS="lisp-symbol"><A NAME="reserved-block-type-error"></A><TT><STRONG>reserved-block-type-error</STRONG></TT><BR /></DIV><P>This error is signaled when a deflate block is read whose type is 3. This type is reserved for future expansion and should not be found in the wild.</P><DIV CLASS="lisp-symbol"><A NAME="invalid-stored-block-length-error"></A><TT><STRONG>invalid-stored-block-length-error</STRONG></TT><BR /></DIV><P>This error is signaled when the length of a deflate stored block is found to be invalid.</P><DIV CLASS="lisp-symbol"><A NAME="bzip2-error"></A><TT><STRONG>bzip2-error</STRONG></TT><BR /></DIV><P>All errors signaled while decompressing bzip2-based formats are of this type.</P><DIV CLASS="lisp-symbol"><A NAME="invalid-bzip2-data"></A><TT><STRONG>invalid-bzip2-data</STRONG></TT><BR /></DIV><P>This error is signaled when the compressed bzip2 data is found to be corrupt in some way that prevents further decompression.</P></BODY></HTML> \ No newline at end of file
froydnj/chipz
40cb950db9ba26d8f28ca1b03c19ef06e8006d67
fix Allegro Gray streams support, fixes #6
diff --git a/stream.lisp b/stream.lisp index 3d47e0a..41d0018 100644 --- a/stream.lisp +++ b/stream.lisp @@ -1,199 +1,199 @@ ;;;; stream.lisp -- gray stream wrappers for INFLATE (in-package :chipz) (eval-when (:compile-toplevel :load-toplevel) #-chipz-system:gray-streams (error "gray streams are not supported in this lisp implementation")) ;;; portability definitions #+cmu (eval-when (:compile-toplevel :load-toplevel :execute) (require :gray-streams)) ;;; TRIVIAL-GRAY-STREAMS has it, we might as well, too... #+allegro (eval-when (:compile-toplevel :load-toplevel :execute) - (unless (fboundp 'stream:stream-write-string) + (unless (fboundp 'excl:stream-write-string) (require "streamc.fasl"))) (eval-when (:compile-toplevel :load-toplevel :execute) (defvar *binary-input-stream-class* #+lispworks 'stream:fundamental-binary-input-stream #+sbcl 'sb-gray:fundamental-binary-input-stream #+openmcl 'gray:fundamental-binary-input-stream #+cmu 'ext:fundamental-binary-input-stream #+allegro 'excl:fundamental-binary-input-stream #+clisp 'gray:fundamental-binary-input-stream) (defvar *stream-read-byte-function* #+lispworks 'stream:stream-read-byte #+sbcl 'sb-gray:stream-read-byte #+openmcl 'gray:stream-read-byte #+cmu 'ext:stream-read-byte #+allegro 'excl:stream-read-byte #+clisp 'gray:stream-read-byte) (defvar *stream-read-sequence-function* #+lispworks 'stream:stream-read-sequence #+sbcl 'sb-gray:stream-read-sequence #+openmcl 'ccl:stream-read-vector #+cmu 'ext:stream-read-sequence #+allegro 'excl:stream-read-sequence #+clisp 'gray:stream-read-byte-sequence) ) ; EVAL-WHEN ;;; READ-SEQUENCE (defmacro define-stream-read-sequence (specializer &body body) (let ((definition `(cond ((not (typep seq 'simple-octet-vector)) (call-next-method)) (t (let ((end (or end (length seq)))) ,@body))))) #+(or cmu sbcl allegro) `(defmethod #.*stream-read-sequence-function* ((stream ,specializer) seq &optional (start 0) end) ,definition) #+(or lispworks openmcl) `(defmethod #.*stream-read-sequence-function* ((stream ,specializer) seq start end) ,definition) #+clisp `(defmethod #.*stream-read-sequence-function* ((stream ,specializer) seq &optional (start 0) end ,(gensym "no-hang") ,(gensym "interactive")) ,definition))) ;;; class definition (defclass decompressing-stream (#.*binary-input-stream-class*) ((wrapped-stream :initarg :stream :reader wrapped-stream) (dstate :initarg :dstate :reader dstate) (dfun :initarg :dfun :reader dfun) (input-buffer :initform (make-array 4096 :element-type '(unsigned-byte 8)) :reader input-buffer) (input-buffer-index :initform 0 :accessor input-buffer-index) (input-buffer-n-bytes :initform 0 :accessor input-buffer-n-bytes) (output-buffer :initform (make-array 4096 :element-type '(unsigned-byte 8)) :reader output-buffer) (output-buffer-index :initform 0 :accessor output-buffer-index) (output-buffer-n-bytes :initform 0 :accessor output-buffer-n-bytes))) ;;; constructors (defun make-decompressing-stream (format stream) (multiple-value-bind (state dfun) (ecase format ((:deflate :zlib :gzip deflate zlib gzip) (values (make-inflate-state format) #'%inflate)) ((:bzip2 bzip2) (values (make-bzip2-state) #'%bzip2-decompress))) (make-instance 'decompressing-stream :stream stream :dstate state :dfun dfun))) ;;; stream management (defun output-available-p (stream) (/= (output-buffer-index stream) (output-buffer-n-bytes stream))) (defun input-available-p (stream) (/= (input-buffer-index stream) (input-buffer-n-bytes stream))) (defun refill-stream-input-buffer (stream) (with-slots (input-buffer wrapped-stream input-buffer-index input-buffer-n-bytes) stream (let ((n-bytes-read (read-sequence input-buffer wrapped-stream))) (setf input-buffer-index 0 input-buffer-n-bytes n-bytes-read) #+nil (format *trace-output* "index: ~D | n-bytes ~D~%" input-buffer-index input-buffer-n-bytes) (values)))) (defun refill-stream-output-buffer (stream) (unless (input-available-p stream) (refill-stream-input-buffer stream)) (multiple-value-bind (bytes-read bytes-output) (funcall (the function (dfun stream)) (dstate stream) (input-buffer stream) (output-buffer stream) :input-start (input-buffer-index stream) :input-end (input-buffer-n-bytes stream)) (setf (output-buffer-index stream) 0 (output-buffer-n-bytes stream) bytes-output (input-buffer-index stream) (+ (input-buffer-index stream) bytes-read)) (assert (<= (input-buffer-index stream) (input-buffer-n-bytes stream))))) ;;; methods (defun read-and-decompress-byte (stream) (flet ((maybe-done () (when (output-available-p stream) (return-from read-and-decompress-byte (aref (output-buffer stream) (prog1 (output-buffer-index stream) (incf (output-buffer-index stream)))))))) ;; several input buffers may be used up before output is available ;; => read-byte should refill "something" while at all possible, ;; like read-sequence already does. (loop initially (maybe-done) do (refill-stream-output-buffer stream) (maybe-done) (unless (input-available-p stream) (refill-stream-input-buffer stream)) ;; If we didn't refill, then we must be all done. (unless (input-available-p stream) (finish-dstate (dstate stream)) (return :eof))))) (defun copy-existing-output (stream seq start end) (declare (type simple-octet-vector seq)) (let ((amount (min (- end start) (- (output-buffer-n-bytes stream) (output-buffer-index stream))))) (replace seq (output-buffer stream) :start1 start :end1 end :start2 (output-buffer-index stream) :end2 (output-buffer-n-bytes stream)) (incf (output-buffer-index stream) amount) (+ start amount))) (define-stream-read-sequence decompressing-stream (unless (typep seq 'simple-octet-vector) (return-from #.*stream-read-sequence-function* (call-next-method))) (loop initially (when (output-available-p stream) (setf start (copy-existing-output stream seq start end))) while (< start end) do (unless (input-available-p stream) (refill-stream-input-buffer stream)) ;; If we didn't refill, then we must be all done. (unless (input-available-p stream) (finish-dstate (dstate stream)) (loop-finish)) ;; Decompress directly into the user-provided buffer. (multiple-value-bind (bytes-read bytes-output) (funcall (the function (dfun stream)) (dstate stream) (input-buffer stream) seq :input-start (input-buffer-index stream) :input-end (input-buffer-n-bytes stream) :output-start start :output-end end) (incf (input-buffer-index stream) bytes-read) (incf start bytes-output)) finally (return start))) (defmethod #.*stream-read-byte-function* ((stream decompressing-stream)) (read-and-decompress-byte stream))
froydnj/chipz
a82dc649fbcfd754abde657f79e87a28ea5a724a
Cleanup the .asd file for ASDF 2.27.
diff --git a/chipz.asd b/chipz.asd index 5e2a6ba..668cd32 100644 --- a/chipz.asd +++ b/chipz.asd @@ -1,52 +1,48 @@ ; -*- mode: lisp -*- (cl:defpackage :chipz-system (:use :cl :asdf) (:export #:gray-streams)) (cl:in-package :chipz-system) -(defclass txt-file (doc-file) ()) -(defclass css-file (doc-file) ()) - -(defmethod source-file-type ((c txt-file) (s module)) "txt") -(defmethod source-file-type ((c css-file) (s module)) "css") +(defclass txt-file (doc-file) ((type :initform "txt"))) +(defclass css-file (doc-file) ((type :initform "css"))) (eval-when (:compile-toplevel :load-toplevel :execute) #+(or sbcl lispworks openmcl cmu allegro clisp) (pushnew 'chipz-system:gray-streams cl:*features*)) (asdf:defsystem :chipz :version "0.7.4" :author "Nathan Froyd <froydnj@gmail.com>" :maintainer "Nathan Froyd <froydnj@gmail.com>" :description "A library for decompressing deflate, zlib, and gzip data" :license "BSD style" :components ((:static-file "NEWS") (:static-file "LICENSE") (:static-file "TODO") (:file "package") (:module "doc" :components - ((:html-file "chipz") - ;; XXX ASDF bogosity + ((:html-file "index") (:txt-file "chipz-doc") (:css-file "style"))) (:file "constants" :depends-on ("package")) (:file "types-and-tables" :depends-on ("constants")) (:file "crc32" :depends-on ("types-and-tables")) (:file "adler32" :depends-on ("types-and-tables")) (:file "conditions" :depends-on ("package")) (:file "dstate" :depends-on ("package")) (:file "inflate-state" :depends-on ("dstate" "crc32" "adler32")) (:file "gzip" :depends-on ("inflate-state" "conditions")) (:file "zlib" :depends-on ("inflate-state" "conditions")) (:file "inflate" :depends-on ("inflate-state" "gzip" "zlib" "conditions")) (:file "bzip2" :depends-on ("dstate" "constants")) (:file "decompress" :depends-on ("inflate-state" "inflate" "bzip2")) #+chipz-system:gray-streams (:file "stream" :depends-on ("inflate-state" "inflate")) #-chipz-system:gray-streams (:file "stream-fallback" :depends-on ("package"))))
froydnj/chipz
329dadf670a0780daf92af743d482e4f4230a1b0
stream: add support for make-decompressing-stream on clisp
diff --git a/chipz.asd b/chipz.asd index 6130e60..5e2a6ba 100644 --- a/chipz.asd +++ b/chipz.asd @@ -1,52 +1,52 @@ ; -*- mode: lisp -*- (cl:defpackage :chipz-system (:use :cl :asdf) (:export #:gray-streams)) (cl:in-package :chipz-system) (defclass txt-file (doc-file) ()) (defclass css-file (doc-file) ()) (defmethod source-file-type ((c txt-file) (s module)) "txt") (defmethod source-file-type ((c css-file) (s module)) "css") (eval-when (:compile-toplevel :load-toplevel :execute) - #+(or sbcl lispworks openmcl cmu allegro) + #+(or sbcl lispworks openmcl cmu allegro clisp) (pushnew 'chipz-system:gray-streams cl:*features*)) (asdf:defsystem :chipz :version "0.7.4" :author "Nathan Froyd <froydnj@gmail.com>" :maintainer "Nathan Froyd <froydnj@gmail.com>" :description "A library for decompressing deflate, zlib, and gzip data" :license "BSD style" :components ((:static-file "NEWS") (:static-file "LICENSE") (:static-file "TODO") (:file "package") (:module "doc" :components ((:html-file "chipz") ;; XXX ASDF bogosity (:txt-file "chipz-doc") (:css-file "style"))) (:file "constants" :depends-on ("package")) (:file "types-and-tables" :depends-on ("constants")) (:file "crc32" :depends-on ("types-and-tables")) (:file "adler32" :depends-on ("types-and-tables")) (:file "conditions" :depends-on ("package")) (:file "dstate" :depends-on ("package")) (:file "inflate-state" :depends-on ("dstate" "crc32" "adler32")) (:file "gzip" :depends-on ("inflate-state" "conditions")) (:file "zlib" :depends-on ("inflate-state" "conditions")) (:file "inflate" :depends-on ("inflate-state" "gzip" "zlib" "conditions")) (:file "bzip2" :depends-on ("dstate" "constants")) (:file "decompress" :depends-on ("inflate-state" "inflate" "bzip2")) #+chipz-system:gray-streams (:file "stream" :depends-on ("inflate-state" "inflate")) #-chipz-system:gray-streams (:file "stream-fallback" :depends-on ("package")))) diff --git a/stream.lisp b/stream.lisp index 21e162e..4f4de79 100644 --- a/stream.lisp +++ b/stream.lisp @@ -1,188 +1,198 @@ ;;;; stream.lisp -- gray stream wrappers for INFLATE (in-package :chipz) (eval-when (:compile-toplevel :load-toplevel) #-chipz-system:gray-streams (error "gray streams are not supported in this lisp implementation")) ;;; portability definitions #+cmu (eval-when (:compile-toplevel :load-toplevel :execute) (require :gray-streams)) ;;; TRIVIAL-GRAY-STREAMS has it, we might as well, too... #+allegro (eval-when (:compile-toplevel :load-toplevel :execute) (unless (fboundp 'stream:stream-write-string) (require "streamc.fasl"))) (eval-when (:compile-toplevel :load-toplevel :execute) (defvar *binary-input-stream-class* #+lispworks 'stream:fundamental-binary-input-stream #+sbcl 'sb-gray:fundamental-binary-input-stream #+openmcl 'gray:fundamental-binary-input-stream #+cmu 'ext:fundamental-binary-input-stream - #+allegro 'excl:fundamental-binary-input-stream) + #+allegro 'excl:fundamental-binary-input-stream + #+clisp 'gray:fundamental-binary-input-stream) (defvar *stream-read-byte-function* #+lispworks 'stream:stream-read-byte #+sbcl 'sb-gray:stream-read-byte #+openmcl 'gray:stream-read-byte #+cmu 'ext:stream-read-byte - #+allegro 'excl:stream-read-byte) + #+allegro 'excl:stream-read-byte + #+clisp 'gray:stream-read-byte) (defvar *stream-read-sequence-function* #+lispworks 'stream:stream-read-sequence #+sbcl 'sb-gray:stream-read-sequence #+openmcl 'ccl:stream-read-vector #+cmu 'ext:stream-read-sequence - #+allegro 'excl:stream-read-sequence) + #+allegro 'excl:stream-read-sequence + #+clisp 'gray:stream-read-byte-sequence) ) ; EVAL-WHEN ;;; READ-SEQUENCE (defmacro define-stream-read-sequence (specializer &body body) (let ((definition `(cond ((not (typep seq 'simple-octet-vector)) (call-next-method)) (t (let ((end (or end (length seq)))) ,@body))))) #+(or cmu sbcl allegro) `(defmethod #.*stream-read-sequence-function* ((stream ,specializer) seq &optional (start 0) end) ,definition) #+(or lispworks openmcl) `(defmethod #.*stream-read-sequence-function* ((stream ,specializer) seq start end) + ,definition) + + #+clisp + `(defmethod #.*stream-read-sequence-function* ((stream ,specializer) seq + &optional (start 0) end + ,(gensym "no-hang") + ,(gensym "interactive")) ,definition))) ;;; class definition (defclass decompressing-stream (#.*binary-input-stream-class*) ((wrapped-stream :initarg :stream :reader wrapped-stream) (dstate :initarg :dstate :reader dstate) (dfun :initarg :dfun :reader dfun) (input-buffer :initform (make-array 4096 :element-type '(unsigned-byte 8)) :reader input-buffer) (input-buffer-index :initform 0 :accessor input-buffer-index) (input-buffer-n-bytes :initform 0 :accessor input-buffer-n-bytes) (output-buffer :initform (make-array 4096 :element-type '(unsigned-byte 8)) :reader output-buffer) (output-buffer-index :initform 0 :accessor output-buffer-index) (output-buffer-n-bytes :initform 0 :accessor output-buffer-n-bytes))) ;;; constructors (defun make-decompressing-stream (format stream) (multiple-value-bind (state dfun) (ecase format ((:deflate :zlib :gzip deflate zlib gzip) (values (make-inflate-state format) #'%inflate)) ((:bzip2 bzip2) (values (make-bzip2-state) #'%bzip2-decompress))) (make-instance 'decompressing-stream :stream stream :dstate state :dfun dfun))) ;;; stream management (defun output-available-p (stream) (/= (output-buffer-index stream) (output-buffer-n-bytes stream))) (defun input-available-p (stream) (/= (input-buffer-index stream) (input-buffer-n-bytes stream))) (defun refill-stream-input-buffer (stream) (with-slots (input-buffer wrapped-stream input-buffer-index input-buffer-n-bytes) stream (let ((n-bytes-read (read-sequence input-buffer wrapped-stream))) (setf input-buffer-index 0 input-buffer-n-bytes n-bytes-read) #+nil (format *trace-output* "index: ~D | n-bytes ~D~%" input-buffer-index input-buffer-n-bytes) (values)))) (defun refill-stream-output-buffer (stream) (unless (input-available-p stream) (refill-stream-input-buffer stream)) (multiple-value-bind (bytes-read bytes-output) (funcall (the function (dfun stream)) (dstate stream) (input-buffer stream) (output-buffer stream) :input-start (input-buffer-index stream) :input-end (input-buffer-n-bytes stream)) (setf (output-buffer-index stream) 0 (output-buffer-n-bytes stream) bytes-output (input-buffer-index stream) (+ (input-buffer-index stream) bytes-read)) (assert (<= (input-buffer-index stream) (input-buffer-n-bytes stream))))) ;;; methods (defun read-and-decompress-byte (stream) (flet ((maybe-done () (when (output-available-p stream) (return-from read-and-decompress-byte (aref (output-buffer stream) (prog1 (output-buffer-index stream) (incf (output-buffer-index stream)))))))) ;; several input buffers may be used up before output is available ;; => read-byte should refill "something" while at all possible, ;; like read-sequence already does. (loop initially (maybe-done) do (refill-stream-output-buffer stream) (maybe-done) (unless (input-available-p stream) (refill-stream-input-buffer stream)) ;; If we didn't refill, then we must be all done. (unless (input-available-p stream) (finish-dstate (dstate stream)) (return :eof))))) (defun copy-existing-output (stream seq start end) (declare (type simple-octet-vector seq)) (let ((amount (min (- end start) (- (output-buffer-n-bytes stream) (output-buffer-index stream))))) (replace seq (output-buffer stream) :start1 start :end1 end :start2 (output-buffer-index stream) :end2 (output-buffer-n-bytes stream)) (+ start amount))) (define-stream-read-sequence decompressing-stream (unless (typep seq 'simple-octet-vector) (return-from #.*stream-read-sequence-function* (call-next-method))) (loop initially (when (output-available-p stream) (setf start (copy-existing-output stream seq start end))) while (< start end) do (unless (input-available-p stream) (refill-stream-input-buffer stream)) ;; If we didn't refill, then we must be all done. (unless (input-available-p stream) (finish-dstate (dstate stream)) (loop-finish)) ;; Decompress directly into the user-provided buffer. (multiple-value-bind (bytes-read bytes-output) (funcall (the function (dfun stream)) (dstate stream) (input-buffer stream) seq :input-start (input-buffer-index stream) :input-end (input-buffer-n-bytes stream) :output-start start :output-end end) (incf (input-buffer-index stream) bytes-read) (incf start bytes-output)) finally (return start))) (defmethod #.*stream-read-byte-function* ((stream decompressing-stream)) (read-and-decompress-byte stream))
froydnj/chipz
b3552b02578219be74a7184ea4b63d9c85403400
fallback implementation for make-decompressing-stream that signals a proper error
diff --git a/chipz.asd b/chipz.asd index 840cad3..6130e60 100644 --- a/chipz.asd +++ b/chipz.asd @@ -1,49 +1,52 @@ ; -*- mode: lisp -*- (cl:defpackage :chipz-system (:use :cl :asdf) (:export #:gray-streams)) (cl:in-package :chipz-system) (defclass txt-file (doc-file) ()) (defclass css-file (doc-file) ()) (defmethod source-file-type ((c txt-file) (s module)) "txt") (defmethod source-file-type ((c css-file) (s module)) "css") (eval-when (:compile-toplevel :load-toplevel :execute) #+(or sbcl lispworks openmcl cmu allegro) (pushnew 'chipz-system:gray-streams cl:*features*)) (asdf:defsystem :chipz :version "0.7.4" :author "Nathan Froyd <froydnj@gmail.com>" :maintainer "Nathan Froyd <froydnj@gmail.com>" :description "A library for decompressing deflate, zlib, and gzip data" :license "BSD style" :components ((:static-file "NEWS") (:static-file "LICENSE") (:static-file "TODO") (:file "package") (:module "doc" :components ((:html-file "chipz") ;; XXX ASDF bogosity (:txt-file "chipz-doc") (:css-file "style"))) (:file "constants" :depends-on ("package")) (:file "types-and-tables" :depends-on ("constants")) (:file "crc32" :depends-on ("types-and-tables")) (:file "adler32" :depends-on ("types-and-tables")) (:file "conditions" :depends-on ("package")) (:file "dstate" :depends-on ("package")) (:file "inflate-state" :depends-on ("dstate" "crc32" "adler32")) (:file "gzip" :depends-on ("inflate-state" "conditions")) (:file "zlib" :depends-on ("inflate-state" "conditions")) (:file "inflate" :depends-on ("inflate-state" "gzip" "zlib" "conditions")) (:file "bzip2" :depends-on ("dstate" "constants")) (:file "decompress" :depends-on ("inflate-state" "inflate" "bzip2")) #+chipz-system:gray-streams - (:file "stream" :depends-on ("inflate-state" "inflate")))) + (:file "stream" :depends-on ("inflate-state" "inflate")) + + #-chipz-system:gray-streams + (:file "stream-fallback" :depends-on ("package")))) diff --git a/stream-fallback.lisp b/stream-fallback.lisp new file mode 100644 index 0000000..60d0107 --- /dev/null +++ b/stream-fallback.lisp @@ -0,0 +1,7 @@ +;;;; stream-fallback.lisp -- loaded when there is no support for gray streams + +(in-package :chipz) + +(defun make-decompressing-stream (format stream) + (declare (ignore format stream)) + (error "make-decompressing-stream is not supported for this lisp implementation")) \ No newline at end of file
froydnj/chipz
24cd0b55d9ae11cbdf11b7bfc41cdf026dfc61b6
push 'chipz-system:gray-streams into *features* on supported implementations
diff --git a/chipz.asd b/chipz.asd index 47e6ee6..840cad3 100644 --- a/chipz.asd +++ b/chipz.asd @@ -1,44 +1,49 @@ ; -*- mode: lisp -*- (cl:defpackage :chipz-system - (:use :cl :asdf)) + (:use :cl :asdf) + (:export #:gray-streams)) (cl:in-package :chipz-system) (defclass txt-file (doc-file) ()) (defclass css-file (doc-file) ()) (defmethod source-file-type ((c txt-file) (s module)) "txt") (defmethod source-file-type ((c css-file) (s module)) "css") +(eval-when (:compile-toplevel :load-toplevel :execute) + #+(or sbcl lispworks openmcl cmu allegro) + (pushnew 'chipz-system:gray-streams cl:*features*)) + (asdf:defsystem :chipz :version "0.7.4" :author "Nathan Froyd <froydnj@gmail.com>" :maintainer "Nathan Froyd <froydnj@gmail.com>" :description "A library for decompressing deflate, zlib, and gzip data" :license "BSD style" :components ((:static-file "NEWS") (:static-file "LICENSE") (:static-file "TODO") (:file "package") (:module "doc" :components ((:html-file "chipz") ;; XXX ASDF bogosity (:txt-file "chipz-doc") (:css-file "style"))) (:file "constants" :depends-on ("package")) (:file "types-and-tables" :depends-on ("constants")) (:file "crc32" :depends-on ("types-and-tables")) (:file "adler32" :depends-on ("types-and-tables")) (:file "conditions" :depends-on ("package")) (:file "dstate" :depends-on ("package")) (:file "inflate-state" :depends-on ("dstate" "crc32" "adler32")) (:file "gzip" :depends-on ("inflate-state" "conditions")) (:file "zlib" :depends-on ("inflate-state" "conditions")) (:file "inflate" :depends-on ("inflate-state" "gzip" "zlib" "conditions")) (:file "bzip2" :depends-on ("dstate" "constants")) (:file "decompress" :depends-on ("inflate-state" "inflate" "bzip2")) - #+(or sbcl lispworks openmcl cmu allegro) + #+chipz-system:gray-streams (:file "stream" :depends-on ("inflate-state" "inflate")))) diff --git a/stream.lisp b/stream.lisp index 8db34d7..21e162e 100644 --- a/stream.lisp +++ b/stream.lisp @@ -1,218 +1,188 @@ ;;;; stream.lisp -- gray stream wrappers for INFLATE (in-package :chipz) +(eval-when (:compile-toplevel :load-toplevel) + #-chipz-system:gray-streams + (error "gray streams are not supported in this lisp implementation")) ;;; portability definitions #+cmu (eval-when (:compile-toplevel :load-toplevel :execute) (require :gray-streams)) ;;; TRIVIAL-GRAY-STREAMS has it, we might as well, too... #+allegro (eval-when (:compile-toplevel :load-toplevel :execute) (unless (fboundp 'stream:stream-write-string) (require "streamc.fasl"))) (eval-when (:compile-toplevel :load-toplevel :execute) -(defvar *binary-input-stream-class* - (quote - #+lispworks stream:fundamental-binary-input-stream - #+sbcl sb-gray:fundamental-binary-input-stream - #+openmcl gray:fundamental-binary-input-stream - #+cmu ext:fundamental-binary-input-stream - #+allegro excl:fundamental-binary-input-stream - #-(or lispworks sbcl openmcl cmu allegro) - (error "octet streams not supported in this implementation"))) - -(defvar *stream-read-byte-function* - (quote - #+lispworks stream:stream-read-byte - #+sbcl sb-gray:stream-read-byte - #+openmcl gray:stream-read-byte - #+cmu ext:stream-read-byte - #+allegro excl:stream-read-byte - #-(or lispworks sbcl openmcl cmu allegro) - (error "octet streams not supported in this implementation"))) - -(defvar *stream-read-sequence-function* - (quote - #+lispworks stream:stream-read-sequence - #+sbcl sb-gray:stream-read-sequence - #+openmcl ccl:stream-read-vector - #+cmu ext:stream-read-sequence - #+allegro excl:stream-read-sequence - #-(or lispworks sbcl openmcl cmu allegro) - (error "octet streams not supported in this implementation"))) + (defvar *binary-input-stream-class* + #+lispworks 'stream:fundamental-binary-input-stream + #+sbcl 'sb-gray:fundamental-binary-input-stream + #+openmcl 'gray:fundamental-binary-input-stream + #+cmu 'ext:fundamental-binary-input-stream + #+allegro 'excl:fundamental-binary-input-stream) + + (defvar *stream-read-byte-function* + #+lispworks 'stream:stream-read-byte + #+sbcl 'sb-gray:stream-read-byte + #+openmcl 'gray:stream-read-byte + #+cmu 'ext:stream-read-byte + #+allegro 'excl:stream-read-byte) + + (defvar *stream-read-sequence-function* + #+lispworks 'stream:stream-read-sequence + #+sbcl 'sb-gray:stream-read-sequence + #+openmcl 'ccl:stream-read-vector + #+cmu 'ext:stream-read-sequence + #+allegro 'excl:stream-read-sequence) ) ; EVAL-WHEN ;;; READ-SEQUENCE (defmacro define-stream-read-sequence (specializer &body body) - #+sbcl - `(defmethod sb-gray:stream-read-sequence ((stream ,specializer) seq &optional (start 0) end) - (cond - ((not (typep seq 'simple-octet-vector)) - (call-next-method)) - (t - (let ((end (or end (length seq)))) - ,@body)))) - #+cmu - `(defmethod ext:stream-read-sequence ((stream ,specializer) seq &optional (start 0) end) - (cond - ((not (typep seq 'simple-octet-vector)) - (call-next-method)) - (t - (let ((end (or end (length seq)))) - ,@body)))) - #+allegro - `(defmethod excl:stream-read-sequence ((stream ,specializer) seq &optional (start 0) end) - (cond - ((not (typep seq 'simple-octet-vector)) - (call-next-method)) - (t - (let ((end (or end (length seq)))) - ,@body)))) - #+openmcl - `(defmethod ccl:stream-read-vector ((stream ,specializer) seq start end) - (cond - ((not (typep seq 'simple-octet-vector)) - (call-next-method)) - (t - ,@body))) - #+lispworks - `(defmethod stream:stream-read-sequence ((stream ,specializer) seq start end) - (cond - ((not (typep seq 'simple-octet-vector)) - (call-next-method)) - (t - ,@body)))) - + (let ((definition + `(cond + ((not (typep seq 'simple-octet-vector)) + (call-next-method)) + (t + (let ((end (or end (length seq)))) + ,@body))))) + + #+(or cmu sbcl allegro) + `(defmethod #.*stream-read-sequence-function* ((stream ,specializer) seq &optional (start 0) end) + ,definition) + + #+(or lispworks openmcl) + `(defmethod #.*stream-read-sequence-function* ((stream ,specializer) seq start end) + ,definition))) ;;; class definition (defclass decompressing-stream (#.*binary-input-stream-class*) ((wrapped-stream :initarg :stream :reader wrapped-stream) (dstate :initarg :dstate :reader dstate) (dfun :initarg :dfun :reader dfun) (input-buffer :initform (make-array 4096 :element-type '(unsigned-byte 8)) :reader input-buffer) (input-buffer-index :initform 0 :accessor input-buffer-index) (input-buffer-n-bytes :initform 0 :accessor input-buffer-n-bytes) (output-buffer :initform (make-array 4096 :element-type '(unsigned-byte 8)) :reader output-buffer) (output-buffer-index :initform 0 :accessor output-buffer-index) (output-buffer-n-bytes :initform 0 :accessor output-buffer-n-bytes))) ;;; constructors (defun make-decompressing-stream (format stream) (multiple-value-bind (state dfun) (ecase format ((:deflate :zlib :gzip deflate zlib gzip) (values (make-inflate-state format) #'%inflate)) ((:bzip2 bzip2) (values (make-bzip2-state) #'%bzip2-decompress))) (make-instance 'decompressing-stream :stream stream :dstate state :dfun dfun))) ;;; stream management (defun output-available-p (stream) (/= (output-buffer-index stream) (output-buffer-n-bytes stream))) (defun input-available-p (stream) (/= (input-buffer-index stream) (input-buffer-n-bytes stream))) (defun refill-stream-input-buffer (stream) (with-slots (input-buffer wrapped-stream input-buffer-index input-buffer-n-bytes) stream (let ((n-bytes-read (read-sequence input-buffer wrapped-stream))) (setf input-buffer-index 0 input-buffer-n-bytes n-bytes-read) #+nil (format *trace-output* "index: ~D | n-bytes ~D~%" input-buffer-index input-buffer-n-bytes) (values)))) (defun refill-stream-output-buffer (stream) (unless (input-available-p stream) (refill-stream-input-buffer stream)) (multiple-value-bind (bytes-read bytes-output) (funcall (the function (dfun stream)) (dstate stream) (input-buffer stream) (output-buffer stream) :input-start (input-buffer-index stream) :input-end (input-buffer-n-bytes stream)) (setf (output-buffer-index stream) 0 (output-buffer-n-bytes stream) bytes-output (input-buffer-index stream) (+ (input-buffer-index stream) bytes-read)) (assert (<= (input-buffer-index stream) (input-buffer-n-bytes stream))))) ;;; methods (defun read-and-decompress-byte (stream) (flet ((maybe-done () (when (output-available-p stream) (return-from read-and-decompress-byte (aref (output-buffer stream) (prog1 (output-buffer-index stream) (incf (output-buffer-index stream)))))))) ;; several input buffers may be used up before output is available ;; => read-byte should refill "something" while at all possible, ;; like read-sequence already does. (loop initially (maybe-done) do (refill-stream-output-buffer stream) (maybe-done) (unless (input-available-p stream) (refill-stream-input-buffer stream)) ;; If we didn't refill, then we must be all done. (unless (input-available-p stream) (finish-dstate (dstate stream)) (return :eof))))) (defun copy-existing-output (stream seq start end) (declare (type simple-octet-vector seq)) (let ((amount (min (- end start) (- (output-buffer-n-bytes stream) (output-buffer-index stream))))) (replace seq (output-buffer stream) :start1 start :end1 end :start2 (output-buffer-index stream) :end2 (output-buffer-n-bytes stream)) (+ start amount))) (define-stream-read-sequence decompressing-stream (unless (typep seq 'simple-octet-vector) (return-from #.*stream-read-sequence-function* (call-next-method))) (loop initially (when (output-available-p stream) (setf start (copy-existing-output stream seq start end))) while (< start end) do (unless (input-available-p stream) (refill-stream-input-buffer stream)) ;; If we didn't refill, then we must be all done. (unless (input-available-p stream) (finish-dstate (dstate stream)) (loop-finish)) ;; Decompress directly into the user-provided buffer. (multiple-value-bind (bytes-read bytes-output) (funcall (the function (dfun stream)) (dstate stream) (input-buffer stream) seq :input-start (input-buffer-index stream) :input-end (input-buffer-n-bytes stream) :output-start start :output-end end) (incf (input-buffer-index stream) bytes-read) (incf start bytes-output)) finally (return start))) (defmethod #.*stream-read-byte-function* ((stream decompressing-stream)) (read-and-decompress-byte stream)) diff --git a/tests.lisp b/tests.lisp index 14d73ae..f09311c 100644 --- a/tests.lisp +++ b/tests.lisp @@ -1,107 +1,107 @@ (in-package :lizard) (defun gzip-test/whole-file (compressed-pathname original-pathname) (with-open-file (compressed-stream compressed-pathname :direction :input :element-type '(unsigned-byte 8)) (with-open-file (stream original-pathname :direction :input :element-type '(unsigned-byte 8)) (let ((compressed-input (make-array (file-length compressed-stream) :element-type '(unsigned-byte 8))) (output (make-array (file-length stream) :element-type '(unsigned-byte 8))) (original (make-array (file-length stream) :element-type '(unsigned-byte 8))) (zstream (make-inflate-state :gzip))) (let ((compressed-bytes (read-sequence compressed-input compressed-stream))) (read-sequence original stream) (multiple-value-bind (bytes-read bytes-output) (read-uncompressed-data zstream compressed-input output :input-end compressed-bytes) (and (= bytes-read compressed-bytes) (= bytes-output (length original)) (not (mismatch output original :end1 bytes-output :end2 bytes-output))))))))) (defun gzip-test/whole-file-cons (compressed-pathname original-pathname) (with-open-file (compressed-stream compressed-pathname :direction :input :element-type '(unsigned-byte 8)) (with-open-file (stream original-pathname :direction :input :element-type '(unsigned-byte 8)) (let ((compressed-input (make-array (file-length compressed-stream) :element-type '(unsigned-byte 8))) (original (make-array (file-length stream) :element-type '(unsigned-byte 8)))) (let ((compressed-bytes (read-sequence compressed-input compressed-stream)) (output (decompress :gzip compressed-input :input-end compressed-bytes))) (read-sequence original stream) (and (= (length original) (length output)) (not (mismatch output original)))))))) (defun gzip-test/incremental-file (compressed-pathname original-pathname) (with-open-file (compressed-stream compressed-pathname :direction :input :element-type '(unsigned-byte 8)) (with-open-file (stream original-pathname :direction :input :element-type '(unsigned-byte 8)) (let ((compressed-input (make-array (file-length compressed-stream) :element-type '(unsigned-byte 8))) (output (make-array (file-length stream) :element-type '(unsigned-byte 8))) (original (make-array (file-length stream) :element-type '(unsigned-byte 8))) (zstream (make-inflate-state :gzip))) (read-sequence original stream) (let ((compressed-bytes (read-sequence compressed-input compressed-stream)) (input-index 0) (output-index 0)) (loop (multiple-value-bind (bytes-read bytes-output) (read-uncompressed-data zstream compressed-input output :input-start input-index :input-end compressed-bytes :output-start output-index :output-end (1+ output-index)) (when (zerop bytes-output) (return)) (let ((ouch (mismatch original output :start1 output-index :start2 output-index :end1 (1+ output-index) :end2 (1+ output-index)))) (when ouch (return nil))) (incf input-index bytes-read) (incf output-index))) (and (= input-index compressed-bytes)) (= output-index (length original)) (not (mismatch output original :end1 output-index :end2 output-index))))))) -#+sbcl +#+chipz-system:gray-streams (defun gzip-test/gray-stream (compressed-pathname original-pathname) (with-open-file (compressed-stream compressed-pathname :direction :input :element-type '(unsigned-byte 8)) (with-open-file (stream original-pathname :direction :input :element-type '(unsigned-byte 8)) (let ((zstream (make-decompressing-stream :gzip compressed-stream)) (output (make-array (file-length stream) :element-type '(unsigned-byte 8))) (original (make-array (file-length stream) :element-type '(unsigned-byte 8)))) (read-sequence output zstream) (read-sequence original stream) (not (mismatch output original)))))) (defun run-all-tests (source-directory) (dolist (testfun (list #'gzip-test/whole-file #'gzip-test/whole-file-cons - #+sbcl #'gzip-test/gray-stream + #+chipz-system:gray-streams #'gzip-test/gray-stream #'gzip-test/incremental-file) t) (let ((directory (merge-pathnames (make-pathname :name :wild :type "lisp" :directory '(:relative "test-files")) source-directory))) (dolist (file (directory directory)) (loop with namestring = (namestring file) for level from 1 to 9 do (let ((gzipped-pathname (make-pathname :name (format nil "~A.~D.gz" namestring level) :type nil))) (when (probe-file gzipped-pathname) (unless (funcall testfun gzipped-pathname file) (return-from run-all-tests nil)))))))))
froydnj/chipz
b5e2a2d18be6421dc0a3b810741bebf01065d776
stream: fix minor read-sequence bug
diff --git a/stream.lisp b/stream.lisp index 324c466..8db34d7 100644 --- a/stream.lisp +++ b/stream.lisp @@ -1,218 +1,218 @@ ;;;; stream.lisp -- gray stream wrappers for INFLATE (in-package :chipz) ;;; portability definitions #+cmu (eval-when (:compile-toplevel :load-toplevel :execute) (require :gray-streams)) ;;; TRIVIAL-GRAY-STREAMS has it, we might as well, too... #+allegro (eval-when (:compile-toplevel :load-toplevel :execute) (unless (fboundp 'stream:stream-write-string) (require "streamc.fasl"))) (eval-when (:compile-toplevel :load-toplevel :execute) (defvar *binary-input-stream-class* (quote #+lispworks stream:fundamental-binary-input-stream #+sbcl sb-gray:fundamental-binary-input-stream #+openmcl gray:fundamental-binary-input-stream #+cmu ext:fundamental-binary-input-stream #+allegro excl:fundamental-binary-input-stream #-(or lispworks sbcl openmcl cmu allegro) (error "octet streams not supported in this implementation"))) (defvar *stream-read-byte-function* (quote #+lispworks stream:stream-read-byte #+sbcl sb-gray:stream-read-byte #+openmcl gray:stream-read-byte #+cmu ext:stream-read-byte #+allegro excl:stream-read-byte #-(or lispworks sbcl openmcl cmu allegro) (error "octet streams not supported in this implementation"))) (defvar *stream-read-sequence-function* (quote #+lispworks stream:stream-read-sequence #+sbcl sb-gray:stream-read-sequence #+openmcl ccl:stream-read-vector #+cmu ext:stream-read-sequence #+allegro excl:stream-read-sequence #-(or lispworks sbcl openmcl cmu allegro) (error "octet streams not supported in this implementation"))) ) ; EVAL-WHEN ;;; READ-SEQUENCE (defmacro define-stream-read-sequence (specializer &body body) #+sbcl `(defmethod sb-gray:stream-read-sequence ((stream ,specializer) seq &optional (start 0) end) (cond ((not (typep seq 'simple-octet-vector)) (call-next-method)) (t (let ((end (or end (length seq)))) ,@body)))) #+cmu `(defmethod ext:stream-read-sequence ((stream ,specializer) seq &optional (start 0) end) (cond ((not (typep seq 'simple-octet-vector)) (call-next-method)) (t (let ((end (or end (length seq)))) ,@body)))) #+allegro `(defmethod excl:stream-read-sequence ((stream ,specializer) seq &optional (start 0) end) (cond ((not (typep seq 'simple-octet-vector)) (call-next-method)) (t (let ((end (or end (length seq)))) ,@body)))) #+openmcl `(defmethod ccl:stream-read-vector ((stream ,specializer) seq start end) (cond ((not (typep seq 'simple-octet-vector)) (call-next-method)) (t ,@body))) #+lispworks `(defmethod stream:stream-read-sequence ((stream ,specializer) seq start end) (cond ((not (typep seq 'simple-octet-vector)) (call-next-method)) (t ,@body)))) ;;; class definition (defclass decompressing-stream (#.*binary-input-stream-class*) ((wrapped-stream :initarg :stream :reader wrapped-stream) (dstate :initarg :dstate :reader dstate) (dfun :initarg :dfun :reader dfun) (input-buffer :initform (make-array 4096 :element-type '(unsigned-byte 8)) :reader input-buffer) (input-buffer-index :initform 0 :accessor input-buffer-index) (input-buffer-n-bytes :initform 0 :accessor input-buffer-n-bytes) (output-buffer :initform (make-array 4096 :element-type '(unsigned-byte 8)) :reader output-buffer) (output-buffer-index :initform 0 :accessor output-buffer-index) (output-buffer-n-bytes :initform 0 :accessor output-buffer-n-bytes))) ;;; constructors (defun make-decompressing-stream (format stream) (multiple-value-bind (state dfun) (ecase format ((:deflate :zlib :gzip deflate zlib gzip) (values (make-inflate-state format) #'%inflate)) ((:bzip2 bzip2) (values (make-bzip2-state) #'%bzip2-decompress))) (make-instance 'decompressing-stream :stream stream :dstate state :dfun dfun))) ;;; stream management (defun output-available-p (stream) (/= (output-buffer-index stream) (output-buffer-n-bytes stream))) (defun input-available-p (stream) (/= (input-buffer-index stream) (input-buffer-n-bytes stream))) (defun refill-stream-input-buffer (stream) (with-slots (input-buffer wrapped-stream input-buffer-index input-buffer-n-bytes) stream (let ((n-bytes-read (read-sequence input-buffer wrapped-stream))) (setf input-buffer-index 0 input-buffer-n-bytes n-bytes-read) #+nil (format *trace-output* "index: ~D | n-bytes ~D~%" input-buffer-index input-buffer-n-bytes) (values)))) (defun refill-stream-output-buffer (stream) (unless (input-available-p stream) (refill-stream-input-buffer stream)) (multiple-value-bind (bytes-read bytes-output) (funcall (the function (dfun stream)) (dstate stream) (input-buffer stream) (output-buffer stream) :input-start (input-buffer-index stream) :input-end (input-buffer-n-bytes stream)) (setf (output-buffer-index stream) 0 (output-buffer-n-bytes stream) bytes-output (input-buffer-index stream) (+ (input-buffer-index stream) bytes-read)) (assert (<= (input-buffer-index stream) (input-buffer-n-bytes stream))))) ;;; methods (defun read-and-decompress-byte (stream) (flet ((maybe-done () (when (output-available-p stream) (return-from read-and-decompress-byte (aref (output-buffer stream) (prog1 (output-buffer-index stream) (incf (output-buffer-index stream)))))))) ;; several input buffers may be used up before output is available ;; => read-byte should refill "something" while at all possible, ;; like read-sequence already does. (loop initially (maybe-done) do (refill-stream-output-buffer stream) (maybe-done) (unless (input-available-p stream) (refill-stream-input-buffer stream)) ;; If we didn't refill, then we must be all done. (unless (input-available-p stream) (finish-dstate (dstate stream)) (return :eof))))) (defun copy-existing-output (stream seq start end) (declare (type simple-octet-vector seq)) - (let ((amount (min (- start end) + (let ((amount (min (- end start) (- (output-buffer-n-bytes stream) (output-buffer-index stream))))) (replace seq (output-buffer stream) :start1 start :end1 end :start2 (output-buffer-index stream) :end2 (output-buffer-n-bytes stream)) (+ start amount))) (define-stream-read-sequence decompressing-stream (unless (typep seq 'simple-octet-vector) (return-from #.*stream-read-sequence-function* (call-next-method))) (loop initially (when (output-available-p stream) (setf start (copy-existing-output stream seq start end))) while (< start end) do (unless (input-available-p stream) (refill-stream-input-buffer stream)) ;; If we didn't refill, then we must be all done. (unless (input-available-p stream) (finish-dstate (dstate stream)) (loop-finish)) ;; Decompress directly into the user-provided buffer. (multiple-value-bind (bytes-read bytes-output) (funcall (the function (dfun stream)) (dstate stream) (input-buffer stream) seq :input-start (input-buffer-index stream) :input-end (input-buffer-n-bytes stream) :output-start start :output-end end) (incf (input-buffer-index stream) bytes-read) (incf start bytes-output)) finally (return start))) (defmethod #.*stream-read-byte-function* ((stream decompressing-stream)) (read-and-decompress-byte stream))
froydnj/chipz
2db490428c2d4be95e9076d05cbe7146beb3bba8
Fixed READ-AND-DECOMPRESS-BYTE: don't give up too early, refill input as many times as possible if output is empty; the logic is similar to STREAM-READ-SEQUENCE.
diff --git a/stream.lisp b/stream.lisp index 3868dbc..324c466 100644 --- a/stream.lisp +++ b/stream.lisp @@ -1,210 +1,218 @@ ;;;; stream.lisp -- gray stream wrappers for INFLATE (in-package :chipz) ;;; portability definitions #+cmu (eval-when (:compile-toplevel :load-toplevel :execute) (require :gray-streams)) ;;; TRIVIAL-GRAY-STREAMS has it, we might as well, too... #+allegro (eval-when (:compile-toplevel :load-toplevel :execute) (unless (fboundp 'stream:stream-write-string) (require "streamc.fasl"))) (eval-when (:compile-toplevel :load-toplevel :execute) (defvar *binary-input-stream-class* (quote #+lispworks stream:fundamental-binary-input-stream #+sbcl sb-gray:fundamental-binary-input-stream #+openmcl gray:fundamental-binary-input-stream #+cmu ext:fundamental-binary-input-stream #+allegro excl:fundamental-binary-input-stream #-(or lispworks sbcl openmcl cmu allegro) (error "octet streams not supported in this implementation"))) (defvar *stream-read-byte-function* (quote #+lispworks stream:stream-read-byte #+sbcl sb-gray:stream-read-byte #+openmcl gray:stream-read-byte #+cmu ext:stream-read-byte #+allegro excl:stream-read-byte #-(or lispworks sbcl openmcl cmu allegro) (error "octet streams not supported in this implementation"))) (defvar *stream-read-sequence-function* (quote #+lispworks stream:stream-read-sequence #+sbcl sb-gray:stream-read-sequence #+openmcl ccl:stream-read-vector #+cmu ext:stream-read-sequence #+allegro excl:stream-read-sequence #-(or lispworks sbcl openmcl cmu allegro) (error "octet streams not supported in this implementation"))) ) ; EVAL-WHEN ;;; READ-SEQUENCE (defmacro define-stream-read-sequence (specializer &body body) #+sbcl `(defmethod sb-gray:stream-read-sequence ((stream ,specializer) seq &optional (start 0) end) (cond ((not (typep seq 'simple-octet-vector)) (call-next-method)) (t (let ((end (or end (length seq)))) ,@body)))) #+cmu `(defmethod ext:stream-read-sequence ((stream ,specializer) seq &optional (start 0) end) (cond ((not (typep seq 'simple-octet-vector)) (call-next-method)) (t (let ((end (or end (length seq)))) ,@body)))) #+allegro `(defmethod excl:stream-read-sequence ((stream ,specializer) seq &optional (start 0) end) (cond ((not (typep seq 'simple-octet-vector)) (call-next-method)) (t (let ((end (or end (length seq)))) ,@body)))) #+openmcl `(defmethod ccl:stream-read-vector ((stream ,specializer) seq start end) (cond ((not (typep seq 'simple-octet-vector)) (call-next-method)) (t ,@body))) #+lispworks `(defmethod stream:stream-read-sequence ((stream ,specializer) seq start end) (cond ((not (typep seq 'simple-octet-vector)) (call-next-method)) (t ,@body)))) ;;; class definition (defclass decompressing-stream (#.*binary-input-stream-class*) ((wrapped-stream :initarg :stream :reader wrapped-stream) (dstate :initarg :dstate :reader dstate) (dfun :initarg :dfun :reader dfun) (input-buffer :initform (make-array 4096 :element-type '(unsigned-byte 8)) :reader input-buffer) (input-buffer-index :initform 0 :accessor input-buffer-index) (input-buffer-n-bytes :initform 0 :accessor input-buffer-n-bytes) (output-buffer :initform (make-array 4096 :element-type '(unsigned-byte 8)) :reader output-buffer) (output-buffer-index :initform 0 :accessor output-buffer-index) (output-buffer-n-bytes :initform 0 :accessor output-buffer-n-bytes))) ;;; constructors (defun make-decompressing-stream (format stream) (multiple-value-bind (state dfun) (ecase format ((:deflate :zlib :gzip deflate zlib gzip) (values (make-inflate-state format) #'%inflate)) ((:bzip2 bzip2) (values (make-bzip2-state) #'%bzip2-decompress))) (make-instance 'decompressing-stream :stream stream :dstate state :dfun dfun))) ;;; stream management (defun output-available-p (stream) (/= (output-buffer-index stream) (output-buffer-n-bytes stream))) (defun input-available-p (stream) (/= (input-buffer-index stream) (input-buffer-n-bytes stream))) (defun refill-stream-input-buffer (stream) (with-slots (input-buffer wrapped-stream input-buffer-index input-buffer-n-bytes) stream (let ((n-bytes-read (read-sequence input-buffer wrapped-stream))) (setf input-buffer-index 0 input-buffer-n-bytes n-bytes-read) #+nil (format *trace-output* "index: ~D | n-bytes ~D~%" input-buffer-index input-buffer-n-bytes) (values)))) (defun refill-stream-output-buffer (stream) (unless (input-available-p stream) (refill-stream-input-buffer stream)) (multiple-value-bind (bytes-read bytes-output) (funcall (the function (dfun stream)) (dstate stream) (input-buffer stream) (output-buffer stream) :input-start (input-buffer-index stream) :input-end (input-buffer-n-bytes stream)) (setf (output-buffer-index stream) 0 (output-buffer-n-bytes stream) bytes-output (input-buffer-index stream) (+ (input-buffer-index stream) bytes-read)) (assert (<= (input-buffer-index stream) (input-buffer-n-bytes stream))))) ;;; methods (defun read-and-decompress-byte (stream) - (unless (output-available-p stream) - (refill-stream-output-buffer stream)) - ;; FIXME: should we cache this, so we don't try to refill all the time? - (cond - ((output-available-p stream) - (prog1 (aref (output-buffer stream) (output-buffer-index stream)) - (incf (output-buffer-index stream)))) - (t - (finish-dstate (dstate stream)) - :eof))) + (flet ((maybe-done () + (when (output-available-p stream) + (return-from read-and-decompress-byte + (aref (output-buffer stream) + (prog1 (output-buffer-index stream) + (incf (output-buffer-index stream)))))))) + ;; several input buffers may be used up before output is available + ;; => read-byte should refill "something" while at all possible, + ;; like read-sequence already does. + (loop initially (maybe-done) + do (refill-stream-output-buffer stream) + (maybe-done) + (unless (input-available-p stream) + (refill-stream-input-buffer stream)) + ;; If we didn't refill, then we must be all done. + (unless (input-available-p stream) + (finish-dstate (dstate stream)) + (return :eof))))) (defun copy-existing-output (stream seq start end) (declare (type simple-octet-vector seq)) (let ((amount (min (- start end) (- (output-buffer-n-bytes stream) (output-buffer-index stream))))) (replace seq (output-buffer stream) :start1 start :end1 end :start2 (output-buffer-index stream) :end2 (output-buffer-n-bytes stream)) (+ start amount))) (define-stream-read-sequence decompressing-stream (unless (typep seq 'simple-octet-vector) (return-from #.*stream-read-sequence-function* (call-next-method))) (loop initially (when (output-available-p stream) (setf start (copy-existing-output stream seq start end))) while (< start end) do (unless (input-available-p stream) (refill-stream-input-buffer stream)) ;; If we didn't refill, then we must be all done. (unless (input-available-p stream) (finish-dstate (dstate stream)) (loop-finish)) ;; Decompress directly into the user-provided buffer. (multiple-value-bind (bytes-read bytes-output) (funcall (the function (dfun stream)) (dstate stream) (input-buffer stream) seq :input-start (input-buffer-index stream) :input-end (input-buffer-n-bytes stream) :output-start start :output-end end) (incf (input-buffer-index stream) bytes-read) (incf start bytes-output)) finally (return start))) (defmethod #.*stream-read-byte-function* ((stream decompressing-stream)) (read-and-decompress-byte stream))
froydnj/chipz
082b437d2188d162f4549138578f1b9e8149853b
Fixed BZIP2-BLOCK-CRC32 in %bzip2-state-machine: don't read 32 bits at once:
diff --git a/bzip2.lisp b/bzip2.lisp index d1c99f4..6a51535 100644 --- a/bzip2.lisp +++ b/bzip2.lisp @@ -1,944 +1,946 @@ (in-package :chipz) ;;; bzip2's decompress.c looks relatively simple, but a great deal of ;;; complexity and cleverness is hidden behind C preprpocessor macro. ;;; The single biggest help in understand what is going on behind the ;;; macros is to read "Coroutines in C" by Simon Tatham: ;;; ;;; http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html ;;; ;;; decompress.c is using the same technique described in the paper, ;;; although with a slightly different implementation. ;;; ;;; Lisp, fortunately/alas, does not admit the same sort of techniques ;;; that C does--at least not expressed exactly the same way. So our ;;; translation naturally differs in some places. For example, to make ;;; it easier to figure out how much state we have to preserve, we ;;; choose to read more in at one time than decompress.c--the magic ;;; number header all at once or the bits for the mapping table in ;;; larger chunks than 1 bit at a time, for instance. ;;; Reading things in larger chunks than bits means that we have to do ;;; bit-reversal of various quantities. (defun reverse-ub4 (x) (let ((table (load-time-value (make-array 16 :element-type 'fixnum :initial-contents '(0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15))))) (aref table x))) (defun reverse-ub8 (x) (logior (ash (reverse-ub4 (ldb (byte 4 0) x)) 4) (reverse-ub4 (ldb (byte 4 4) x)))) (defun reverse-ub16 (x) (logior (ash (reverse-ub8 (ldb (byte 8 0) x)) 8) (reverse-ub8 (ldb (byte 8 8) x)))) (defvar *dummy-vec* (make-array #.+bz-max-alpha-size+ :element-type '(unsigned-byte 32))) (defstruct (bzip2-state (:include decompression-state) (:constructor %make-bzip2-state)) ;; For doing the final run-length decoding. (out-ch 0 :type (unsigned-byte 8)) (out-len 0 :type (integer 0 260)) (block-randomized-p nil) (rntogo 0 :type (unsigned-byte 32)) (rntpos 0 :type (unsigned-byte 32)) (100k-block-size 1 :type (integer 1 9)) (small-decompression-p nil) (current-block-number 0) ;; For undoing the Burrows-Wheeler transform. */ (original-pointer 0) (t-position 0 :type (integer 0 (900000))) (k0 0) (unzftab (make-array 256 :element-type '(unsigned-byte 32)) :type (simple-array (unsigned-byte 32) (256))) (n-blocks-used 0) (cftab (make-array 257 :element-type '(unsigned-byte 32)) :type (simple-array (unsigned-byte 32) (257))) (cftab-copy (make-array 257 :element-type '(unsigned-byte 32)) :type (simple-array (unsigned-byte 32) (257))) ;; For undoing the Burrows-Wheeler transform (FAST). (tt (make-array 0 :element-type '(unsigned-byte 32)) :type (simple-array (unsigned-byte 32) (*))) ;; Stored and calculated CRCs. (stored-block-crc 0 :type (unsigned-byte 32)) (stored-combined-crc 0 :type (unsigned-byte 32)) (calculated-block-crc #xffffffff :type (unsigned-byte 32)) (calculated-combined-crc 0 :type (unsigned-byte 32)) ;; Map of bytes used in block ("mapping table"). (n-in-use 0 :type (integer 0 256)) (in-use (make-array 256 :initial-element nil) :type (simple-array t (256))) ;; This was a byte array; we have chosen to make it a simple integer ;; and index it with LOGBITP. (in-use-16 0 :type (unsigned-byte 16)) (seq-to-unseq (make-array 256 :element-type '(unsigned-byte 8)) :type (simple-array (unsigned-byte 8) (256))) ;; For decoding the MTF values. (mtfa (make-array +mtfa-size+ :element-type '(unsigned-byte 8)) :type (simple-array (unsigned-byte 8) (#.+mtfa-size+))) (mtfbase (make-array (/ 256 +mtfl-size+) :element-type '(unsigned-byte 16)) :type (simple-array (unsigned-byte 16) (#.(/ 256 +mtfl-size+)))) (selector (make-array +bz-max-selectors+ :element-type '(unsigned-byte 8)) :type (simple-array (unsigned-byte 8) (#.+bz-max-selectors+))) (selector-mtf (make-array +bz-max-selectors+ :element-type '(unsigned-byte 8)) :type (simple-array (unsigned-byte 8) (#.+bz-max-selectors+))) (len (make-array '(#.+bz-n-groups+ #.+bz-max-alpha-size+) :element-type '(unsigned-byte 8)) :type (simple-array (unsigned-byte 8) (#.+bz-n-groups+ #.+bz-max-alpha-size+))) (mtf-continuation nil :type (or null function)) (limit #1=(let ((w (make-array +bz-n-groups+))) (dotimes (i +bz-n-groups+ w) (setf (aref w i) (make-array +bz-max-alpha-size+ :element-type '(unsigned-byte 32))))) :type (simple-array t (#.+bz-n-groups+))) (base #1# :type (simple-array t (#.+bz-n-groups+))) (perm #1# :type (simple-array t (#.+bz-n-groups+))) (min-lengths (make-array #.+bz-n-groups+ :element-type '(unsigned-byte 32)) :type (simple-array (unsigned-byte 32) (#.+bz-n-groups+))) ;; Save variables for scalars in the decompression code. (i 0) (j 0) (alpha-size 0 :type (integer 0 258)) (n-groups 0) (n-selectors 0) (EOB 0 :type (integer 0 257)) ;; FIXME: check on the declarations for these three. (group-number 0 :type fixnum) (group-position 0 :type fixnum) (lval 0 :type fixnum) (nblockMAX 0 :type (integer 0 900000)) (nblock 0 :type (integer 0 (900000))) (es 0 :type fixnum) (N 0 :type fixnum) (curr 0 :type (integer 0 20)) (zn 0 :type (integer 0 20)) (zvec 0 :type (integer 0 #.(expt 2 20))) (g-minlen 0 :type (integer 0 23)) (g-limit *dummy-vec* :type (simple-array (unsigned-byte 32) (#.+bz-max-alpha-size+))) (g-base *dummy-vec* :type (simple-array (unsigned-byte 32) (#.+bz-max-alpha-size+))) (g-perm *dummy-vec* :type (simple-array (unsigned-byte 32) (#.+bz-max-alpha-size+)))) (defmethod print-object ((object bzip2-state) stream) (print-unreadable-object (object stream) (format stream "Bzip2 state bits: ~X/~D input: ~D/~D output ~D/~D" (bzip2-state-bits object) (bzip2-state-n-bits object) (bzip2-state-input-index object) (bzip2-state-input-end object) (bzip2-state-output-index object) (bzip2-state-output-end object)))) (defun make-maps (state) (declare (type bzip2-state state)) (loop with n-in-use = 0 with in-use-table = (bzip2-state-in-use state) with seq-to-unseq = (bzip2-state-seq-to-unseq state) for i from 0 below 256 when (aref in-use-table i) do (setf (aref seq-to-unseq n-in-use) i n-in-use (1+ n-in-use)) finally (return (setf (bzip2-state-n-in-use state) n-in-use)))) (defun make-decode-tables (state group min-len max-len alpha-size) (declare (type bzip2-state state)) (let* ((limit (aref (bzip2-state-limit state) group)) (base (aref (bzip2-state-base state) group)) (perm (aref (bzip2-state-perm state) group)) (len (bzip2-state-len state)) (rmi (array-row-major-index len group 0))) (loop with pp = 0 for i from min-len to max-len do (dotimes (j alpha-size) (when (= (row-major-aref len (+ rmi j)) i) (setf (aref perm pp) j) (incf pp)))) (loop for i from 0 below +bz-max-code-len+ do (setf (aref base i) 0 (aref limit i) 0)) (loop for i from 0 below alpha-size do (incf (aref base (1+ (row-major-aref len (+ i rmi)))))) (loop for i from 1 below +bz-max-code-len+ do (incf (aref base i) (aref base (1- i)))) (loop with vec = 0 for i from min-len to max-len do (incf vec (- (aref base (1+ i)) (aref base i))) (setf (aref limit i) (1- vec) vec (ash vec 1))) (loop for i from (+ min-len 1) to max-len do (setf (aref base i) (- (ash (1+ (aref limit (1- i))) 1) (aref base i)))))) (defun undo-rle-obuf-to-output (state) (declare (optimize speed)) (cond ((bzip2-state-block-randomized-p state) (error 'bzip2-randomized-blocks-unimplemented)) (t (let ((calculated-block-crc (bzip2-state-calculated-block-crc state)) (out-ch (bzip2-state-out-ch state)) (out-len (bzip2-state-out-len state)) (n-blocks-used (bzip2-state-n-blocks-used state)) (k0 (bzip2-state-k0 state)) (k1 0) (tt (bzip2-state-tt state)) (t-position (bzip2-state-t-position state)) (nblockpp (1+ (bzip2-state-nblock state))) (output (bzip2-state-output state)) (index (bzip2-state-output-index state)) (end (bzip2-state-output-end state))) (declare (type (unsigned-byte 32) calculated-block-crc)) (declare (type (integer 0 260) out-len)) (declare (type (unsigned-byte 8) k0 k1)) (declare (type (integer 0 900000) n-blocks-used nblockpp)) (declare (type (unsigned-byte 32) t-position)) (macrolet ((get-fast () `(prog2 (setf t-position (aref tt t-position)) (logand t-position #xff) (setf t-position (ash t-position -8))))) (tagbody START ;; "try to finish existing run" (when (zerop out-len) (go GRAB-MORE)) (loop (when (= index end) (go FINISH)) (when (= out-len 1) (go LEN-EQUAL-ONE)) (setf (aref output index) out-ch) (setf calculated-block-crc (logand #xffffffff (logxor (ash calculated-block-crc 8) (aref +bzip2-crc32-table+ (logxor (ash calculated-block-crc -24) out-ch))))) (decf out-len) (incf index)) LEN-EQUAL-ONE (when (= index end) (setf out-len 1) (go FINISH)) (setf (aref output index) out-ch) (setf calculated-block-crc (logand #xffffffff (logxor (ash calculated-block-crc 8) (aref +bzip2-crc32-table+ (logxor (ash calculated-block-crc -24) out-ch))))) (incf index) GRAB-MORE ;; "Only caused by corrupt data stream?" (when (> n-blocks-used nblockpp) (return-from undo-rle-obuf-to-output t)) (when (= n-blocks-used nblockpp) (setf out-len 0) (go FINISH)) (setf out-ch k0) (setf k1 (get-fast)) (incf n-blocks-used) (unless (= k1 k0) (setf k0 k1) (go LEN-EQUAL-ONE)) (when (= n-blocks-used nblockpp) (go LEN-EQUAL-ONE)) (setf out-len 2) (setf k1 (get-fast)) (incf n-blocks-used) (when (= n-blocks-used nblockpp) (go CONTINUE)) (unless (= k1 k0) (setf k0 k1) (go CONTINUE)) (setf out-len 3) (setf k1 (get-fast)) (incf n-blocks-used) (when (= n-blocks-used nblockpp) (go CONTINUE)) (unless (= k1 k0) (setf k0 k1) (go CONTINUE)) (setf k1 (get-fast)) (incf n-blocks-used) (setf out-len (+ k1 4)) (setf k0 (get-fast)) (incf n-blocks-used) CONTINUE (go START) FINISH) #+nil (incf (bzip2-state-total-out state) (- index (bzip2-state-output-index state) )) ;; Restore cached values. (setf (bzip2-state-calculated-block-crc state) calculated-block-crc (bzip2-state-out-ch state) out-ch (bzip2-state-out-len state) out-len (bzip2-state-n-blocks-used state) n-blocks-used (bzip2-state-k0 state) k0 (bzip2-state-t-position state) t-position (bzip2-state-output-index state) index) nil))))) ;;; decompress.c has various logic relating to whether the user has ;;; chosen "small" decompression, which uses less memory. We're just ;;; going to be memory-intensive and always pick the large option. Maybe ;;; someday we can come back and add the small option. (defun %bzip2-state-machine (state) (declare (type bzip2-state state)) (declare (optimize (speed 3) (debug 1) (space 0) (compilation-speed 0))) ;; See the enormous comment in %INFLATE-STATE-MACHINE for what's going ;; on here. (macrolet ((transition-to (next-state) `(progn (setf (bzip2-state-state state) #',next-state) #+(or sbcl cmu) (,next-state state)))) (labels ( (read-bits (n state) (declare (type (integer 0 32) n)) (declare (type bzip2-state state)) (prog1 ;; We don't use (BYTE N (- ...)) here because doing it ;; this way is ~10% faster on SBCL. (ldb (byte n 0) (ash (bzip2-state-bits state) (the (integer -31 0) (- n (bzip2-state-n-bits state))))) (decf (bzip2-state-n-bits state) n))) (ensure-bits (n state) (declare (type (integer 0 32) n)) (declare (type bzip2-state state)) (let ((bits (bzip2-state-bits state)) (n-bits (bzip2-state-n-bits state)) (input-index (bzip2-state-input-index state))) (declare (type (unsigned-byte 32) bits)) (loop while (< n-bits n) when (>= input-index (bzip2-state-input-end state)) do (progn (setf (bzip2-state-bits state) bits (bzip2-state-n-bits state) n-bits (bzip2-state-input-index state) input-index) (throw 'bzip2-done nil)) do (let ((byte (aref (bzip2-state-input state) input-index))) (declare (type (unsigned-byte 8) byte)) (setf bits (logand #xffffffff (logior (ash bits 8) byte))) (incf n-bits 8) (incf input-index)) finally (setf (bzip2-state-bits state) bits (bzip2-state-n-bits state) n-bits (bzip2-state-input-index state) input-index)))) (ensure-and-read-bits (n state) (ensure-bits n state) (read-bits n state)) (bzip2-header (state) (declare (type bzip2-state state)) (let ((header-field (ensure-and-read-bits 32 state))) (declare (type (unsigned-byte 32) header-field)) (unless (and (= (ldb (byte 8 24) header-field) +bz-header-b+) (= (ldb (byte 8 16) header-field) +bz-header-z+) (= (ldb (byte 8 8) header-field) +bz-header-h+)) (error 'invalid-bzip2-magic)) (let ((block-size-magic-byte (ldb (byte 8 0) header-field))) (unless (<= (+ +bz-header-0+ 1) block-size-magic-byte (+ +bz-header-0+ 9)) (error 'invalid-bzip2-magic)) (setf (bzip2-state-100k-block-size state) (- block-size-magic-byte +bz-header-0+)) ;; BZIP2 SMALL (setf (bzip2-state-tt state) (make-array (* (bzip2-state-100k-block-size state) +100k+) :element-type '(unsigned-byte 32))) (transition-to bzip2-block-header1)))) (bzip2-block-header1 (state) (declare (type bzip2-state state)) (let ((byte (ensure-and-read-bits 8 state))) (case byte (#x17 (transition-to bzip2-end-header2)) (#x31 (transition-to bzip2-block-header2)) (t (error 'invalid-bzip2-data))))) (bzip2-block-header2 (state) (declare (type bzip2-state state)) (let ((byte (ensure-and-read-bits 8 state))) (if (= byte #x41) (transition-to bzip2-block-header3) (error 'invalid-bzip2-data)))) (bzip2-block-header3 (state) (declare (type bzip2-state state)) (let ((byte (ensure-and-read-bits 8 state))) (if (= byte #x59) (transition-to bzip2-block-header4) (error 'invalid-bzip2-data)))) (bzip2-block-header4 (state) (declare (type bzip2-state state)) (let ((byte (ensure-and-read-bits 8 state))) (if (= byte #x26) (transition-to bzip2-block-header5) (error 'invalid-bzip2-data)))) (bzip2-block-header5 (state) (declare (type bzip2-state state)) (let ((byte (ensure-and-read-bits 8 state))) (if (= byte #x53) (transition-to bzip2-block-header6) (error 'invalid-bzip2-data)))) (bzip2-block-header6 (state) (declare (type bzip2-state state)) (let ((byte (ensure-and-read-bits 8 state))) (unless (= byte #x59) (error 'invalid-bzip2-data)) (incf (bzip2-state-current-block-number state)) (transition-to bzip2-block-crc32))) (bzip2-block-crc32 (state) (declare (type bzip2-state state)) - (let ((crc32 (ensure-and-read-bits 32 state))) - (setf (bzip2-state-stored-block-crc state) crc32) + (let ((crc32-hi (ensure-and-read-bits 16 state)) + (crc32-lo (ensure-and-read-bits 16 state))) + (setf (bzip2-state-stored-block-crc state) + (logior (ash crc32-hi 16) crc32-lo)) (transition-to bzip2-block-randombit))) (bzip2-block-randombit (state) (declare (type bzip2-state state)) (let ((randomized-p (ensure-and-read-bits 1 state))) (setf (bzip2-state-block-randomized-p state) (= randomized-p 1)) (transition-to bzip2-original-pointer))) (bzip2-original-pointer (state) (declare (type bzip2-state state)) (let ((original-pointer (ensure-and-read-bits 24 state))) (unless (<= 0 original-pointer (+ 10 (* (bzip2-state-100k-block-size state) +100k+))) (error 'invalid-bzip2-data)) (setf (bzip2-state-original-pointer state) original-pointer) (transition-to bzip2-mapping-table1))) (bzip2-mapping-table1 (state) (declare (type bzip2-state state)) (let ((in-use-16 (reverse-ub16 (ensure-and-read-bits 16 state)))) (setf (bzip2-state-in-use-16 state) in-use-16) (setf (bzip2-state-i state) 0) (fill (bzip2-state-in-use state) nil) (transition-to bzip2-mapping-table2))) (bzip2-mapping-table2 (state) (declare (type bzip2-state state)) (loop with in-use-16 = (bzip2-state-in-use-16 state) with in-use-table = (bzip2-state-in-use state) while (< (bzip2-state-i state) 16) when (logbitp (bzip2-state-i state) in-use-16) do (let ((in-use (reverse-ub16 (ensure-and-read-bits 16 state)))) (dotimes (i 16) (setf (aref in-use-table (+ (* (bzip2-state-i state) 16) i)) (logbitp i in-use)))) do (incf (bzip2-state-i state))) (let ((n-in-use (make-maps state))) (when (zerop n-in-use) (error 'invalid-bzip2-data)) (setf (bzip2-state-alpha-size state) (+ n-in-use 2)) (transition-to bzip2-selector1))) (bzip2-selector1 (state) (declare (type bzip2-state state)) (let ((n-groups (ensure-and-read-bits 3 state))) (unless (<= 3 n-groups 6) (error 'invalid-bzip2-data)) (setf (bzip2-state-n-groups state) n-groups) (transition-to bzip2-selector2))) (bzip2-selector2 (state) (declare (type bzip2-state state)) (let ((n-selectors (ensure-and-read-bits 15 state))) (unless (plusp n-selectors) (error 'invalid-bzip2-data)) (setf (bzip2-state-n-selectors state) n-selectors) (setf (bzip2-state-i state) 0) (transition-to bzip2-selector3a))) (bzip2-selector3a (state) (declare (type bzip2-state state)) (setf (bzip2-state-j state) 0) (transition-to bzip2-selector3b)) (bzip2-selector3b (state) (declare (type bzip2-state state)) (loop do (let ((bit (ensure-and-read-bits 1 state))) (when (zerop bit) (loop-finish)) (when (>= (incf (bzip2-state-j state)) (bzip2-state-n-groups state)) (error 'invalid-bzip2-data))) finally (setf (aref (bzip2-state-selector-mtf state) (bzip2-state-i state)) (bzip2-state-j state))) (if (< (incf (bzip2-state-i state)) (bzip2-state-n-selectors state)) (transition-to bzip2-selector3a) (transition-to bzip2-selector-undo-mtf-values))) (bzip2-selector-undo-mtf-values (state) (declare (type bzip2-state state)) (let ((pos (make-array +bz-n-groups+ :element-type '(unsigned-byte 8))) (n-groups (bzip2-state-n-groups state)) (n-selectors (bzip2-state-n-selectors state)) (selector-table (bzip2-state-selector state)) (selector-mtf (bzip2-state-selector-mtf state))) (declare (dynamic-extent pos)) (dotimes (i n-groups) (setf (aref pos i) i)) (dotimes (i n-selectors) (let* ((v (aref selector-mtf i)) (tmp (aref pos v))) (loop until (zerop v) do (setf (aref pos v) (aref pos (1- v))) (decf v)) (setf (aref pos 0) tmp) (setf (aref selector-table i) tmp))) (setf (bzip2-state-j state) 0) (transition-to bzip2-coding-tables-groups-loop))) (bzip2-coding-tables-groups-loop (state) (declare (type bzip2-state state)) (cond ((< (bzip2-state-j state) (bzip2-state-n-groups state)) (setf (bzip2-state-curr state) (ensure-and-read-bits 5 state) (bzip2-state-i state) 0) (transition-to bzip2-coding-tables-alpha-loop)) (t (transition-to bzip2-create-huffman-decode-tables)))) (bzip2-coding-tables-alpha-loop (state) (declare (type bzip2-state state)) (unless (<= 1 (bzip2-state-curr state) 20) (error 'invalid-bzip2-data)) (let ((uc (ensure-and-read-bits 1 state))) (cond ((zerop uc) (setf (aref (bzip2-state-len state) (bzip2-state-j state) (bzip2-state-i state)) (bzip2-state-curr state)) (cond ((< (incf (bzip2-state-i state)) (bzip2-state-alpha-size state)) (bzip2-coding-tables-alpha-loop state)) (t (incf (bzip2-state-j state)) (transition-to bzip2-coding-tables-groups-loop)))) (t (transition-to bzip2-coding-tables-alpha-loop2))))) (bzip2-coding-tables-alpha-loop2 (state) (declare (type bzip2-state state)) (let ((uc (ensure-and-read-bits 1 state))) (if (zerop uc) (incf (bzip2-state-curr state)) (decf (bzip2-state-curr state))) (transition-to bzip2-coding-tables-alpha-loop))) (bzip2-create-huffman-decode-tables (state) (declare (type bzip2-state state)) (loop with n-groups = (bzip2-state-n-groups state) with len = (bzip2-state-len state) for x from 0 below n-groups do (loop with minLen = 32 with maxLen = 0 with alpha-size = (bzip2-state-alpha-size state) for y from 0 below alpha-size do (let ((xy (aref len x y))) (setf maxLen (max maxLen xy) minLen (min minLen xy))) finally (make-decode-tables state x minLen maxLen alpha-size) (setf (aref (bzip2-state-min-lengths state) x) minLen)) finally ;; We're not 'returning' anything here, we're just ;; forcing this call to be in tail position. (return (transition-to bzip2-initialize-mtf-values)))) (bzip2-initialize-mtf-values (state) (declare (type bzip2-state state)) (loop with kk = (1- +mtfa-size+) with mtfa = (bzip2-state-mtfa state) with mtfbase = (bzip2-state-mtfbase state) initially (setf (bzip2-state-EOB state) (1+ (bzip2-state-n-in-use state)) (bzip2-state-nblockMAX state) (* 100000 (bzip2-state-100k-block-size state)) (bzip2-state-group-number state) -1 (bzip2-state-group-position state) 0) (fill (bzip2-state-unzftab state) 0) for i from (1- (floor 256 +mtfl-size+)) downto 0 do (loop for j from (1- +mtfl-size+) downto 0 do (setf (aref mtfa kk) (+ (* i +mtfl-size+) j)) (decf kk) finally (setf (aref mtfbase i) (1+ kk))) finally (setf (bzip2-state-nblock state) 0 (bzip2-state-mtf-continuation state) #'bzip2-enter-mtf-decode-loop) ;; We're not 'returning' anything here, we're just ;; forcing this call to be in tail position. (return (transition-to bzip2-get-mtf-value)))) (bzip2-get-mtf-value (state) (declare (type bzip2-state state)) (when (zerop (bzip2-state-group-position state)) (when (>= (incf (bzip2-state-group-number state)) (bzip2-state-n-selectors state)) (error 'invalid-bzip2-data)) (let ((s (aref (bzip2-state-selector state) (bzip2-state-group-number state)))) (setf (bzip2-state-group-position state) +bz-g-size+ (bzip2-state-g-minlen state) (aref (bzip2-state-min-lengths state) s) (bzip2-state-g-limit state) (aref (bzip2-state-limit state) s) (bzip2-state-g-perm state) (aref (bzip2-state-perm state) s) (bzip2-state-g-base state) (aref (bzip2-state-base state) s)))) (decf (bzip2-state-group-position state)) (setf (bzip2-state-zn state) (bzip2-state-g-minlen state)) (transition-to bzip2-get-mtf-value1)) (bzip2-get-mtf-value1 (state) (declare (type bzip2-state state)) (let ((zvec (ensure-and-read-bits (bzip2-state-zn state) state))) (setf (bzip2-state-zvec state) zvec) (transition-to bzip2-get-mtf-value2))) (bzip2-get-mtf-value2 (state) (declare (type bzip2-state state)) (when (> (bzip2-state-zn state) 20) (error 'invalid-bzip2-data)) (cond ((<= (bzip2-state-zvec state) (aref (bzip2-state-g-limit state) (bzip2-state-zn state))) (transition-to bzip2-get-mtf-value-done)) (t (incf (bzip2-state-zn state)) (transition-to bzip2-get-mtf-value3)))) (bzip2-get-mtf-value3 (state) (declare (type bzip2-state state)) (let ((zj (ensure-and-read-bits 1 state))) (setf (bzip2-state-zvec state) (logior (ash (bzip2-state-zvec state) 1) zj)) (transition-to bzip2-get-mtf-value2))) (bzip2-get-mtf-value-done (state) (declare (type bzip2-state state)) (let* ((g-base (bzip2-state-g-base state)) (zn (bzip2-state-zn state)) (zvec (bzip2-state-zvec state)) (index (- zvec (aref g-base zn)))) (when (or (< index 0) (>= index +bz-max-alpha-size+)) (error 'invalid-bzip2-data)) (setf (bzip2-state-lval state) (aref (bzip2-state-g-perm state) index)) (let ((f (bzip2-state-mtf-continuation state))) (declare (type function f)) (setf (bzip2-state-state state) f) (funcall f state)))) (bzip2-enter-mtf-decode-loop (state) (declare (type bzip2-state state)) (let ((next-sym (bzip2-state-lval state))) (cond ((= next-sym (bzip2-state-EOB state)) (transition-to bzip2-prepare-cftab)) ((or (= next-sym +bz-runa+) (= next-sym +bz-runb+)) (setf (bzip2-state-es state) -1 (bzip2-state-N state) 1) (transition-to bzip2-decode-rle-sequence)) (t (transition-to bzip2-runc))))) (bzip2-decode-rle-sequence (state) (declare (type bzip2-state state)) (let ((next-sym (bzip2-state-lval state))) (cond ((= next-sym +bz-runa+) (incf (bzip2-state-es state) (bzip2-state-N state))) ((= next-sym +bz-runb+) (incf (bzip2-state-es state) (* (bzip2-state-N state) 2)))) (setf (bzip2-state-N state) (* (bzip2-state-N state) 2)) (setf (bzip2-state-mtf-continuation state) #'bzip2-maybe-finish-rle-sequence) (transition-to bzip2-get-mtf-value))) (bzip2-maybe-finish-rle-sequence (state) (declare (type bzip2-state state)) (let ((next-sym (bzip2-state-lval state))) (if (or (= next-sym +bz-runa+) (= next-sym +bz-runb+)) (transition-to bzip2-decode-rle-sequence) (transition-to bzip2-finish-rle-sequence)))) (bzip2-finish-rle-sequence (state) (declare (type bzip2-state state)) (let ((uc (aref (bzip2-state-seq-to-unseq state) (aref (bzip2-state-mtfa state) (aref (bzip2-state-mtfbase state) 0))))) (incf (aref (bzip2-state-unzftab state) uc) (incf (bzip2-state-es state))) (if (bzip2-state-small-decompression-p state) (error 'bzip2-small-decompression-unimplemented) (loop with nblock = (bzip2-state-nblock state) with nblockMAX = (bzip2-state-nblockMAX state) with tt = (bzip2-state-tt state) repeat (bzip2-state-es state) do (when (>= nblock nblockMAX) (error 'invalid-bzip2-data)) (setf (aref tt nblock) uc) (incf nblock) finally (setf (bzip2-state-nblock state) nblock) ;; We're not 'returning' anything here, we're ;; just forcing this call to be in tail ;; position. (return (transition-to bzip2-enter-mtf-decode-loop)))))) (bzip2-runc (state) (declare (type bzip2-state state)) (let ((next-sym (bzip2-state-lval state)) (uc 0)) (when (>= (bzip2-state-nblock state) (bzip2-state-nblockMAX state)) (error 'invalid-bzip2-data)) (let ((mtfbase (bzip2-state-mtfbase state)) (mtfa (bzip2-state-mtfa state)) (nn (1- next-sym))) (cond ((< nn +mtfl-size+) ;; "avoid general-case expense" (let ((pp (aref mtfbase 0))) (setf uc (aref mtfa (+ pp nn))) (replace mtfa mtfa :start1 (1+ pp) :end1 (+ pp nn 1) :start2 pp :end2 (+ pp nn)) (setf (aref mtfa pp) uc))) (t ;; "general case" (let* ((lno (truncate nn +mtfl-size+)) (off (rem nn +mtfl-size+)) (pp (+ (aref mtfbase lno) off))) (setf uc (aref mtfa pp)) (loop while (> pp (aref mtfbase lno)) do (setf (aref mtfa pp) (aref mtfa (1- pp))) (decf pp)) (incf (aref mtfbase lno)) (loop for x from lno above 0 do (setf (aref mtfa (decf (aref mtfbase x))) (aref mtfa (+ (aref mtfbase (1- x)) (1- +mtfl-size+))))) (setf (aref mtfa (decf (aref mtfbase 0))) uc) (when (zerop (aref mtfbase 0)) (loop with kk = (1- +mtfa-size+) for ii from (1- (floor 256 +mtfl-size+)) downto 0 do (loop for jj from (1- +mtfl-size+) downto 0 do (setf (aref mtfa kk) (aref mtfa (+ (aref mtfbase ii) jj))) (decf kk)) (setf (aref mtfbase ii) (1+ kk))))))) (incf (aref (bzip2-state-unzftab state) (aref (bzip2-state-seq-to-unseq state) uc))) (if (bzip2-state-small-decompression-p state) (error 'bzip2-small-decompression-unimplemented) (setf (aref (bzip2-state-tt state) (bzip2-state-nblock state)) (aref (bzip2-state-seq-to-unseq state) uc))) (incf (bzip2-state-nblock state)) (setf (bzip2-state-mtf-continuation state) #'bzip2-enter-mtf-decode-loop) (transition-to bzip2-get-mtf-value)))) (bzip2-prepare-cftab (state) (declare (type bzip2-state state)) (when (or (minusp (bzip2-state-original-pointer state)) (>= (bzip2-state-original-pointer state) (bzip2-state-nblock state))) (error 'invalid-bzip2-data)) (let ((cftab (bzip2-state-cftab state)) (unzftab (bzip2-state-unzftab state))) (setf (aref cftab 0) 0) (replace cftab unzftab :start1 1 :end1 257 :start2 0 :end2 256) (loop for i from 1 to 256 do (incf (aref cftab i) (aref cftab (1- i)))) (loop with nblock = (bzip2-state-nblock state) for i from 0 to 256 unless (<= 0 (aref cftab i) nblock) do (error 'invalid-bzip2-data)) (setf (bzip2-state-out-len state) 0 (bzip2-state-out-ch state) 0 (bzip2-state-calculated-block-crc state) #xffffffff) (loop with nblock = (bzip2-state-nblock state) with tt = (bzip2-state-tt state) for i from 0 below nblock do (let ((uc (logand (aref tt i) #xff))) (setf (aref tt (aref cftab uc)) (logior (aref tt (aref cftab uc)) (ash i 8))) (incf (aref cftab uc))) finally (setf (bzip2-state-t-position state) (ash (aref tt (bzip2-state-original-pointer state)) -8)) (setf (bzip2-state-n-blocks-used state) 0) (cond ((bzip2-state-block-randomized-p state) (error 'bzip2-randomized-blocks-unimplemented)) (t ;; BZIP2-STATE-T-POSITION was sometimes set to ;; a value outside its declared domain. Now ;; TEMP is used to store this value instead. (let ((temp (aref tt (bzip2-state-t-position state)))) (setf (bzip2-state-k0 state) (logand #xff temp) (bzip2-state-t-position state) (ash temp -8))) (incf (bzip2-state-n-blocks-used state)))) ;; We're not 'returning' anything here, we're just ;; forcing this call to be in tail position. (return (transition-to bzip2-output))))) (bzip2-output (state) (declare (type bzip2-state state)) (let ((corruptp (undo-rle-obuf-to-output state))) (when corruptp (error 'invalid-bzip2-data)) (unless (and (= (bzip2-state-n-blocks-used state) (1+ (bzip2-state-nblock state))) (zerop (bzip2-state-out-len state))) (throw 'bzip2-done :ok)) (let ((stored (bzip2-state-stored-block-crc state)) (calculated (bzip2-state-calculated-block-crc state))) (setf calculated (logand #xffffffff (lognot calculated))) (setf (bzip2-state-calculated-block-crc state) calculated) (unless (= calculated stored) (error 'checksum-mismatch :stored stored :computed calculated :kind :crc32)) (setf (bzip2-state-calculated-combined-crc state) (logand #xffffffff (logior (ash (bzip2-state-calculated-combined-crc state) 1) (ash (bzip2-state-calculated-combined-crc state) -31)))) (setf (bzip2-state-calculated-combined-crc state) (logand #xffffffff (logxor (bzip2-state-calculated-combined-crc state) calculated))) (transition-to bzip2-block-header1)))) (bzip2-end-header2 (state) (declare (type bzip2-state state)) (let ((byte (ensure-and-read-bits 8 state))) (if (= byte #x72) (transition-to bzip2-end-header3) (error 'invalid-bzip2-data)))) (bzip2-end-header3 (state) (declare (type bzip2-state state)) (let ((byte (ensure-and-read-bits 8 state))) (if (= byte #x45) (transition-to bzip2-end-header4) (error 'invalid-bzip2-data)))) (bzip2-end-header4 (state) (declare (type bzip2-state state)) (let ((byte (ensure-and-read-bits 8 state))) (if (= byte #x38) (transition-to bzip2-end-header5) (error 'invalid-bzip2-data)))) (bzip2-end-header5 (state) (declare (type bzip2-state state)) (let ((byte (ensure-and-read-bits 8 state))) (if (= byte #x50) (transition-to bzip2-end-header6) (error 'invalid-bzip2-data)))) (bzip2-end-header6 (state) (declare (type bzip2-state state)) (let ((byte (ensure-and-read-bits 8 state))) (unless (= byte #x90) (error 'invalid-bzip2-data)) (setf (bzip2-state-stored-combined-crc state) 0) (transition-to bzip2-stored-combined-crc32-1))) (bzip2-stored-combined-crc32-1 (state) (declare (type bzip2-state state)) (setf (bzip2-state-stored-combined-crc state) (ensure-and-read-bits 8 state)) (transition-to bzip2-stored-combined-crc32-2)) (bzip2-stored-combined-crc32-2 (state) (declare (type bzip2-state state)) (let ((byte (ensure-and-read-bits 8 state))) (setf (bzip2-state-stored-combined-crc state) (logand #xffffffff (logior (ash (bzip2-state-stored-combined-crc state) 8) byte))) (transition-to bzip2-stored-combined-crc32-3))) (bzip2-stored-combined-crc32-3 (state) (declare (type bzip2-state state)) (let ((byte (ensure-and-read-bits 8 state))) (setf (bzip2-state-stored-combined-crc state) (logand #xffffffff (logior (ash (bzip2-state-stored-combined-crc state) 8) byte))) (transition-to bzip2-stored-combined-crc32-4))) (bzip2-stored-combined-crc32-4 (state) (declare (type bzip2-state state)) (let ((byte (ensure-and-read-bits 8 state))) (setf (bzip2-state-stored-combined-crc state) (logand #xffffffff (logior (ash (bzip2-state-stored-combined-crc state) 8) byte))) (unless (= (bzip2-state-stored-combined-crc state) (bzip2-state-calculated-combined-crc state)) (error 'checksum-mismatch :stored (bzip2-state-stored-combined-crc state) :computed (bzip2-state-calculated-combined-crc state) :kind :crc32)) (setf (bzip2-state-done state) t) (transition-to bzip2-done))) (bzip2-done (state) (declare (ignore state)) (throw 'bzip2-done t)) ) (unless (bzip2-state-state state) (setf (bzip2-state-state state) #'bzip2-header)) (funcall (the function (bzip2-state-state state)) state))))
froydnj/chipz
c522fb97eec8bd9fb53f04781db20fbf8336a9a9
Fixed BZIP2-PREPARE-CFTAB in %bzip2-state-machine:
diff --git a/bzip2.lisp b/bzip2.lisp index 04990b5..d1c99f4 100644 --- a/bzip2.lisp +++ b/bzip2.lisp @@ -310,655 +310,658 @@ ;;; going to be memory-intensive and always pick the large option. Maybe ;;; someday we can come back and add the small option. (defun %bzip2-state-machine (state) (declare (type bzip2-state state)) (declare (optimize (speed 3) (debug 1) (space 0) (compilation-speed 0))) ;; See the enormous comment in %INFLATE-STATE-MACHINE for what's going ;; on here. (macrolet ((transition-to (next-state) `(progn (setf (bzip2-state-state state) #',next-state) #+(or sbcl cmu) (,next-state state)))) (labels ( (read-bits (n state) (declare (type (integer 0 32) n)) (declare (type bzip2-state state)) (prog1 ;; We don't use (BYTE N (- ...)) here because doing it ;; this way is ~10% faster on SBCL. (ldb (byte n 0) (ash (bzip2-state-bits state) (the (integer -31 0) (- n (bzip2-state-n-bits state))))) (decf (bzip2-state-n-bits state) n))) (ensure-bits (n state) (declare (type (integer 0 32) n)) (declare (type bzip2-state state)) (let ((bits (bzip2-state-bits state)) (n-bits (bzip2-state-n-bits state)) (input-index (bzip2-state-input-index state))) (declare (type (unsigned-byte 32) bits)) (loop while (< n-bits n) when (>= input-index (bzip2-state-input-end state)) do (progn (setf (bzip2-state-bits state) bits (bzip2-state-n-bits state) n-bits (bzip2-state-input-index state) input-index) (throw 'bzip2-done nil)) do (let ((byte (aref (bzip2-state-input state) input-index))) (declare (type (unsigned-byte 8) byte)) (setf bits (logand #xffffffff (logior (ash bits 8) byte))) (incf n-bits 8) (incf input-index)) finally (setf (bzip2-state-bits state) bits (bzip2-state-n-bits state) n-bits (bzip2-state-input-index state) input-index)))) (ensure-and-read-bits (n state) (ensure-bits n state) (read-bits n state)) (bzip2-header (state) (declare (type bzip2-state state)) (let ((header-field (ensure-and-read-bits 32 state))) (declare (type (unsigned-byte 32) header-field)) (unless (and (= (ldb (byte 8 24) header-field) +bz-header-b+) (= (ldb (byte 8 16) header-field) +bz-header-z+) (= (ldb (byte 8 8) header-field) +bz-header-h+)) (error 'invalid-bzip2-magic)) (let ((block-size-magic-byte (ldb (byte 8 0) header-field))) (unless (<= (+ +bz-header-0+ 1) block-size-magic-byte (+ +bz-header-0+ 9)) (error 'invalid-bzip2-magic)) (setf (bzip2-state-100k-block-size state) (- block-size-magic-byte +bz-header-0+)) ;; BZIP2 SMALL (setf (bzip2-state-tt state) (make-array (* (bzip2-state-100k-block-size state) +100k+) :element-type '(unsigned-byte 32))) (transition-to bzip2-block-header1)))) (bzip2-block-header1 (state) (declare (type bzip2-state state)) (let ((byte (ensure-and-read-bits 8 state))) (case byte (#x17 (transition-to bzip2-end-header2)) (#x31 (transition-to bzip2-block-header2)) (t (error 'invalid-bzip2-data))))) (bzip2-block-header2 (state) (declare (type bzip2-state state)) (let ((byte (ensure-and-read-bits 8 state))) (if (= byte #x41) (transition-to bzip2-block-header3) (error 'invalid-bzip2-data)))) (bzip2-block-header3 (state) (declare (type bzip2-state state)) (let ((byte (ensure-and-read-bits 8 state))) (if (= byte #x59) (transition-to bzip2-block-header4) (error 'invalid-bzip2-data)))) (bzip2-block-header4 (state) (declare (type bzip2-state state)) (let ((byte (ensure-and-read-bits 8 state))) (if (= byte #x26) (transition-to bzip2-block-header5) (error 'invalid-bzip2-data)))) (bzip2-block-header5 (state) (declare (type bzip2-state state)) (let ((byte (ensure-and-read-bits 8 state))) (if (= byte #x53) (transition-to bzip2-block-header6) (error 'invalid-bzip2-data)))) (bzip2-block-header6 (state) (declare (type bzip2-state state)) (let ((byte (ensure-and-read-bits 8 state))) (unless (= byte #x59) (error 'invalid-bzip2-data)) (incf (bzip2-state-current-block-number state)) (transition-to bzip2-block-crc32))) (bzip2-block-crc32 (state) (declare (type bzip2-state state)) (let ((crc32 (ensure-and-read-bits 32 state))) (setf (bzip2-state-stored-block-crc state) crc32) (transition-to bzip2-block-randombit))) (bzip2-block-randombit (state) (declare (type bzip2-state state)) (let ((randomized-p (ensure-and-read-bits 1 state))) (setf (bzip2-state-block-randomized-p state) (= randomized-p 1)) (transition-to bzip2-original-pointer))) (bzip2-original-pointer (state) (declare (type bzip2-state state)) (let ((original-pointer (ensure-and-read-bits 24 state))) (unless (<= 0 original-pointer (+ 10 (* (bzip2-state-100k-block-size state) +100k+))) (error 'invalid-bzip2-data)) (setf (bzip2-state-original-pointer state) original-pointer) (transition-to bzip2-mapping-table1))) (bzip2-mapping-table1 (state) (declare (type bzip2-state state)) (let ((in-use-16 (reverse-ub16 (ensure-and-read-bits 16 state)))) (setf (bzip2-state-in-use-16 state) in-use-16) (setf (bzip2-state-i state) 0) (fill (bzip2-state-in-use state) nil) (transition-to bzip2-mapping-table2))) (bzip2-mapping-table2 (state) (declare (type bzip2-state state)) (loop with in-use-16 = (bzip2-state-in-use-16 state) with in-use-table = (bzip2-state-in-use state) while (< (bzip2-state-i state) 16) when (logbitp (bzip2-state-i state) in-use-16) do (let ((in-use (reverse-ub16 (ensure-and-read-bits 16 state)))) (dotimes (i 16) (setf (aref in-use-table (+ (* (bzip2-state-i state) 16) i)) (logbitp i in-use)))) do (incf (bzip2-state-i state))) (let ((n-in-use (make-maps state))) (when (zerop n-in-use) (error 'invalid-bzip2-data)) (setf (bzip2-state-alpha-size state) (+ n-in-use 2)) (transition-to bzip2-selector1))) (bzip2-selector1 (state) (declare (type bzip2-state state)) (let ((n-groups (ensure-and-read-bits 3 state))) (unless (<= 3 n-groups 6) (error 'invalid-bzip2-data)) (setf (bzip2-state-n-groups state) n-groups) (transition-to bzip2-selector2))) (bzip2-selector2 (state) (declare (type bzip2-state state)) (let ((n-selectors (ensure-and-read-bits 15 state))) (unless (plusp n-selectors) (error 'invalid-bzip2-data)) (setf (bzip2-state-n-selectors state) n-selectors) (setf (bzip2-state-i state) 0) (transition-to bzip2-selector3a))) (bzip2-selector3a (state) (declare (type bzip2-state state)) (setf (bzip2-state-j state) 0) (transition-to bzip2-selector3b)) (bzip2-selector3b (state) (declare (type bzip2-state state)) (loop do (let ((bit (ensure-and-read-bits 1 state))) (when (zerop bit) (loop-finish)) (when (>= (incf (bzip2-state-j state)) (bzip2-state-n-groups state)) (error 'invalid-bzip2-data))) finally (setf (aref (bzip2-state-selector-mtf state) (bzip2-state-i state)) (bzip2-state-j state))) (if (< (incf (bzip2-state-i state)) (bzip2-state-n-selectors state)) (transition-to bzip2-selector3a) (transition-to bzip2-selector-undo-mtf-values))) (bzip2-selector-undo-mtf-values (state) (declare (type bzip2-state state)) (let ((pos (make-array +bz-n-groups+ :element-type '(unsigned-byte 8))) (n-groups (bzip2-state-n-groups state)) (n-selectors (bzip2-state-n-selectors state)) (selector-table (bzip2-state-selector state)) (selector-mtf (bzip2-state-selector-mtf state))) (declare (dynamic-extent pos)) (dotimes (i n-groups) (setf (aref pos i) i)) (dotimes (i n-selectors) (let* ((v (aref selector-mtf i)) (tmp (aref pos v))) (loop until (zerop v) do (setf (aref pos v) (aref pos (1- v))) (decf v)) (setf (aref pos 0) tmp) (setf (aref selector-table i) tmp))) (setf (bzip2-state-j state) 0) (transition-to bzip2-coding-tables-groups-loop))) (bzip2-coding-tables-groups-loop (state) (declare (type bzip2-state state)) (cond ((< (bzip2-state-j state) (bzip2-state-n-groups state)) (setf (bzip2-state-curr state) (ensure-and-read-bits 5 state) (bzip2-state-i state) 0) (transition-to bzip2-coding-tables-alpha-loop)) (t (transition-to bzip2-create-huffman-decode-tables)))) (bzip2-coding-tables-alpha-loop (state) (declare (type bzip2-state state)) (unless (<= 1 (bzip2-state-curr state) 20) (error 'invalid-bzip2-data)) (let ((uc (ensure-and-read-bits 1 state))) (cond ((zerop uc) (setf (aref (bzip2-state-len state) (bzip2-state-j state) (bzip2-state-i state)) (bzip2-state-curr state)) (cond ((< (incf (bzip2-state-i state)) (bzip2-state-alpha-size state)) (bzip2-coding-tables-alpha-loop state)) (t (incf (bzip2-state-j state)) (transition-to bzip2-coding-tables-groups-loop)))) (t (transition-to bzip2-coding-tables-alpha-loop2))))) (bzip2-coding-tables-alpha-loop2 (state) (declare (type bzip2-state state)) (let ((uc (ensure-and-read-bits 1 state))) (if (zerop uc) (incf (bzip2-state-curr state)) (decf (bzip2-state-curr state))) (transition-to bzip2-coding-tables-alpha-loop))) (bzip2-create-huffman-decode-tables (state) (declare (type bzip2-state state)) (loop with n-groups = (bzip2-state-n-groups state) with len = (bzip2-state-len state) for x from 0 below n-groups do (loop with minLen = 32 with maxLen = 0 with alpha-size = (bzip2-state-alpha-size state) for y from 0 below alpha-size do (let ((xy (aref len x y))) (setf maxLen (max maxLen xy) minLen (min minLen xy))) finally (make-decode-tables state x minLen maxLen alpha-size) (setf (aref (bzip2-state-min-lengths state) x) minLen)) finally ;; We're not 'returning' anything here, we're just ;; forcing this call to be in tail position. (return (transition-to bzip2-initialize-mtf-values)))) (bzip2-initialize-mtf-values (state) (declare (type bzip2-state state)) (loop with kk = (1- +mtfa-size+) with mtfa = (bzip2-state-mtfa state) with mtfbase = (bzip2-state-mtfbase state) initially (setf (bzip2-state-EOB state) (1+ (bzip2-state-n-in-use state)) (bzip2-state-nblockMAX state) (* 100000 (bzip2-state-100k-block-size state)) (bzip2-state-group-number state) -1 (bzip2-state-group-position state) 0) (fill (bzip2-state-unzftab state) 0) for i from (1- (floor 256 +mtfl-size+)) downto 0 do (loop for j from (1- +mtfl-size+) downto 0 do (setf (aref mtfa kk) (+ (* i +mtfl-size+) j)) (decf kk) finally (setf (aref mtfbase i) (1+ kk))) finally (setf (bzip2-state-nblock state) 0 (bzip2-state-mtf-continuation state) #'bzip2-enter-mtf-decode-loop) ;; We're not 'returning' anything here, we're just ;; forcing this call to be in tail position. (return (transition-to bzip2-get-mtf-value)))) (bzip2-get-mtf-value (state) (declare (type bzip2-state state)) (when (zerop (bzip2-state-group-position state)) (when (>= (incf (bzip2-state-group-number state)) (bzip2-state-n-selectors state)) (error 'invalid-bzip2-data)) (let ((s (aref (bzip2-state-selector state) (bzip2-state-group-number state)))) (setf (bzip2-state-group-position state) +bz-g-size+ (bzip2-state-g-minlen state) (aref (bzip2-state-min-lengths state) s) (bzip2-state-g-limit state) (aref (bzip2-state-limit state) s) (bzip2-state-g-perm state) (aref (bzip2-state-perm state) s) (bzip2-state-g-base state) (aref (bzip2-state-base state) s)))) (decf (bzip2-state-group-position state)) (setf (bzip2-state-zn state) (bzip2-state-g-minlen state)) (transition-to bzip2-get-mtf-value1)) (bzip2-get-mtf-value1 (state) (declare (type bzip2-state state)) (let ((zvec (ensure-and-read-bits (bzip2-state-zn state) state))) (setf (bzip2-state-zvec state) zvec) (transition-to bzip2-get-mtf-value2))) (bzip2-get-mtf-value2 (state) (declare (type bzip2-state state)) (when (> (bzip2-state-zn state) 20) (error 'invalid-bzip2-data)) (cond ((<= (bzip2-state-zvec state) (aref (bzip2-state-g-limit state) (bzip2-state-zn state))) (transition-to bzip2-get-mtf-value-done)) (t (incf (bzip2-state-zn state)) (transition-to bzip2-get-mtf-value3)))) (bzip2-get-mtf-value3 (state) (declare (type bzip2-state state)) (let ((zj (ensure-and-read-bits 1 state))) (setf (bzip2-state-zvec state) (logior (ash (bzip2-state-zvec state) 1) zj)) (transition-to bzip2-get-mtf-value2))) (bzip2-get-mtf-value-done (state) (declare (type bzip2-state state)) (let* ((g-base (bzip2-state-g-base state)) (zn (bzip2-state-zn state)) (zvec (bzip2-state-zvec state)) (index (- zvec (aref g-base zn)))) (when (or (< index 0) (>= index +bz-max-alpha-size+)) (error 'invalid-bzip2-data)) (setf (bzip2-state-lval state) (aref (bzip2-state-g-perm state) index)) (let ((f (bzip2-state-mtf-continuation state))) (declare (type function f)) (setf (bzip2-state-state state) f) (funcall f state)))) (bzip2-enter-mtf-decode-loop (state) (declare (type bzip2-state state)) (let ((next-sym (bzip2-state-lval state))) (cond ((= next-sym (bzip2-state-EOB state)) (transition-to bzip2-prepare-cftab)) ((or (= next-sym +bz-runa+) (= next-sym +bz-runb+)) (setf (bzip2-state-es state) -1 (bzip2-state-N state) 1) (transition-to bzip2-decode-rle-sequence)) (t (transition-to bzip2-runc))))) (bzip2-decode-rle-sequence (state) (declare (type bzip2-state state)) (let ((next-sym (bzip2-state-lval state))) (cond ((= next-sym +bz-runa+) (incf (bzip2-state-es state) (bzip2-state-N state))) ((= next-sym +bz-runb+) (incf (bzip2-state-es state) (* (bzip2-state-N state) 2)))) (setf (bzip2-state-N state) (* (bzip2-state-N state) 2)) (setf (bzip2-state-mtf-continuation state) #'bzip2-maybe-finish-rle-sequence) (transition-to bzip2-get-mtf-value))) (bzip2-maybe-finish-rle-sequence (state) (declare (type bzip2-state state)) (let ((next-sym (bzip2-state-lval state))) (if (or (= next-sym +bz-runa+) (= next-sym +bz-runb+)) (transition-to bzip2-decode-rle-sequence) (transition-to bzip2-finish-rle-sequence)))) (bzip2-finish-rle-sequence (state) (declare (type bzip2-state state)) (let ((uc (aref (bzip2-state-seq-to-unseq state) (aref (bzip2-state-mtfa state) (aref (bzip2-state-mtfbase state) 0))))) (incf (aref (bzip2-state-unzftab state) uc) (incf (bzip2-state-es state))) (if (bzip2-state-small-decompression-p state) (error 'bzip2-small-decompression-unimplemented) (loop with nblock = (bzip2-state-nblock state) with nblockMAX = (bzip2-state-nblockMAX state) with tt = (bzip2-state-tt state) repeat (bzip2-state-es state) do (when (>= nblock nblockMAX) (error 'invalid-bzip2-data)) (setf (aref tt nblock) uc) (incf nblock) finally (setf (bzip2-state-nblock state) nblock) ;; We're not 'returning' anything here, we're ;; just forcing this call to be in tail ;; position. (return (transition-to bzip2-enter-mtf-decode-loop)))))) (bzip2-runc (state) (declare (type bzip2-state state)) (let ((next-sym (bzip2-state-lval state)) (uc 0)) (when (>= (bzip2-state-nblock state) (bzip2-state-nblockMAX state)) (error 'invalid-bzip2-data)) (let ((mtfbase (bzip2-state-mtfbase state)) (mtfa (bzip2-state-mtfa state)) (nn (1- next-sym))) (cond ((< nn +mtfl-size+) ;; "avoid general-case expense" (let ((pp (aref mtfbase 0))) (setf uc (aref mtfa (+ pp nn))) (replace mtfa mtfa :start1 (1+ pp) :end1 (+ pp nn 1) :start2 pp :end2 (+ pp nn)) (setf (aref mtfa pp) uc))) (t ;; "general case" (let* ((lno (truncate nn +mtfl-size+)) (off (rem nn +mtfl-size+)) (pp (+ (aref mtfbase lno) off))) (setf uc (aref mtfa pp)) (loop while (> pp (aref mtfbase lno)) do (setf (aref mtfa pp) (aref mtfa (1- pp))) (decf pp)) (incf (aref mtfbase lno)) (loop for x from lno above 0 do (setf (aref mtfa (decf (aref mtfbase x))) (aref mtfa (+ (aref mtfbase (1- x)) (1- +mtfl-size+))))) (setf (aref mtfa (decf (aref mtfbase 0))) uc) (when (zerop (aref mtfbase 0)) (loop with kk = (1- +mtfa-size+) for ii from (1- (floor 256 +mtfl-size+)) downto 0 do (loop for jj from (1- +mtfl-size+) downto 0 do (setf (aref mtfa kk) (aref mtfa (+ (aref mtfbase ii) jj))) (decf kk)) (setf (aref mtfbase ii) (1+ kk))))))) (incf (aref (bzip2-state-unzftab state) (aref (bzip2-state-seq-to-unseq state) uc))) (if (bzip2-state-small-decompression-p state) (error 'bzip2-small-decompression-unimplemented) (setf (aref (bzip2-state-tt state) (bzip2-state-nblock state)) (aref (bzip2-state-seq-to-unseq state) uc))) (incf (bzip2-state-nblock state)) (setf (bzip2-state-mtf-continuation state) #'bzip2-enter-mtf-decode-loop) (transition-to bzip2-get-mtf-value)))) (bzip2-prepare-cftab (state) (declare (type bzip2-state state)) (when (or (minusp (bzip2-state-original-pointer state)) (>= (bzip2-state-original-pointer state) (bzip2-state-nblock state))) (error 'invalid-bzip2-data)) (let ((cftab (bzip2-state-cftab state)) (unzftab (bzip2-state-unzftab state))) (setf (aref cftab 0) 0) (replace cftab unzftab :start1 1 :end1 257 :start2 0 :end2 256) (loop for i from 1 to 256 do (incf (aref cftab i) (aref cftab (1- i)))) (loop with nblock = (bzip2-state-nblock state) for i from 0 to 256 unless (<= 0 (aref cftab i) nblock) do (error 'invalid-bzip2-data)) (setf (bzip2-state-out-len state) 0 (bzip2-state-out-ch state) 0 (bzip2-state-calculated-block-crc state) #xffffffff) (loop with nblock = (bzip2-state-nblock state) with tt = (bzip2-state-tt state) for i from 0 below nblock do (let ((uc (logand (aref tt i) #xff))) (setf (aref tt (aref cftab uc)) (logior (aref tt (aref cftab uc)) (ash i 8))) (incf (aref cftab uc))) finally (setf (bzip2-state-t-position state) (ash (aref tt (bzip2-state-original-pointer state)) -8)) (setf (bzip2-state-n-blocks-used state) 0) (cond ((bzip2-state-block-randomized-p state) (error 'bzip2-randomized-blocks-unimplemented)) (t - (setf (bzip2-state-t-position state) (aref tt (bzip2-state-t-position state)) - (bzip2-state-k0 state) (logand #xff (bzip2-state-t-position state)) - (bzip2-state-t-position state) (ash (bzip2-state-t-position state) -8)) + ;; BZIP2-STATE-T-POSITION was sometimes set to + ;; a value outside its declared domain. Now + ;; TEMP is used to store this value instead. + (let ((temp (aref tt (bzip2-state-t-position state)))) + (setf (bzip2-state-k0 state) (logand #xff temp) + (bzip2-state-t-position state) (ash temp -8))) (incf (bzip2-state-n-blocks-used state)))) ;; We're not 'returning' anything here, we're just ;; forcing this call to be in tail position. (return (transition-to bzip2-output))))) (bzip2-output (state) (declare (type bzip2-state state)) (let ((corruptp (undo-rle-obuf-to-output state))) (when corruptp (error 'invalid-bzip2-data)) (unless (and (= (bzip2-state-n-blocks-used state) (1+ (bzip2-state-nblock state))) (zerop (bzip2-state-out-len state))) (throw 'bzip2-done :ok)) (let ((stored (bzip2-state-stored-block-crc state)) (calculated (bzip2-state-calculated-block-crc state))) (setf calculated (logand #xffffffff (lognot calculated))) (setf (bzip2-state-calculated-block-crc state) calculated) (unless (= calculated stored) (error 'checksum-mismatch :stored stored :computed calculated :kind :crc32)) (setf (bzip2-state-calculated-combined-crc state) (logand #xffffffff (logior (ash (bzip2-state-calculated-combined-crc state) 1) (ash (bzip2-state-calculated-combined-crc state) -31)))) (setf (bzip2-state-calculated-combined-crc state) (logand #xffffffff (logxor (bzip2-state-calculated-combined-crc state) calculated))) (transition-to bzip2-block-header1)))) (bzip2-end-header2 (state) (declare (type bzip2-state state)) (let ((byte (ensure-and-read-bits 8 state))) (if (= byte #x72) (transition-to bzip2-end-header3) (error 'invalid-bzip2-data)))) (bzip2-end-header3 (state) (declare (type bzip2-state state)) (let ((byte (ensure-and-read-bits 8 state))) (if (= byte #x45) (transition-to bzip2-end-header4) (error 'invalid-bzip2-data)))) (bzip2-end-header4 (state) (declare (type bzip2-state state)) (let ((byte (ensure-and-read-bits 8 state))) (if (= byte #x38) (transition-to bzip2-end-header5) (error 'invalid-bzip2-data)))) (bzip2-end-header5 (state) (declare (type bzip2-state state)) (let ((byte (ensure-and-read-bits 8 state))) (if (= byte #x50) (transition-to bzip2-end-header6) (error 'invalid-bzip2-data)))) (bzip2-end-header6 (state) (declare (type bzip2-state state)) (let ((byte (ensure-and-read-bits 8 state))) (unless (= byte #x90) (error 'invalid-bzip2-data)) (setf (bzip2-state-stored-combined-crc state) 0) (transition-to bzip2-stored-combined-crc32-1))) (bzip2-stored-combined-crc32-1 (state) (declare (type bzip2-state state)) (setf (bzip2-state-stored-combined-crc state) (ensure-and-read-bits 8 state)) (transition-to bzip2-stored-combined-crc32-2)) (bzip2-stored-combined-crc32-2 (state) (declare (type bzip2-state state)) (let ((byte (ensure-and-read-bits 8 state))) (setf (bzip2-state-stored-combined-crc state) (logand #xffffffff (logior (ash (bzip2-state-stored-combined-crc state) 8) byte))) (transition-to bzip2-stored-combined-crc32-3))) (bzip2-stored-combined-crc32-3 (state) (declare (type bzip2-state state)) (let ((byte (ensure-and-read-bits 8 state))) (setf (bzip2-state-stored-combined-crc state) (logand #xffffffff (logior (ash (bzip2-state-stored-combined-crc state) 8) byte))) (transition-to bzip2-stored-combined-crc32-4))) (bzip2-stored-combined-crc32-4 (state) (declare (type bzip2-state state)) (let ((byte (ensure-and-read-bits 8 state))) (setf (bzip2-state-stored-combined-crc state) (logand #xffffffff (logior (ash (bzip2-state-stored-combined-crc state) 8) byte))) (unless (= (bzip2-state-stored-combined-crc state) (bzip2-state-calculated-combined-crc state)) (error 'checksum-mismatch :stored (bzip2-state-stored-combined-crc state) :computed (bzip2-state-calculated-combined-crc state) :kind :crc32)) (setf (bzip2-state-done state) t) (transition-to bzip2-done))) (bzip2-done (state) (declare (ignore state)) (throw 'bzip2-done t)) ) (unless (bzip2-state-state state) (setf (bzip2-state-state state) #'bzip2-header)) (funcall (the function (bzip2-state-state state)) state)))) (defun %bzip2-decompress (state input output &key (input-start 0) input-end (output-start 0) output-end) (declare (type bzip2-state state)) (let* ((input-end (or input-end (length input))) (output-end (or output-end (length output)))) (setf (bzip2-state-input state) input (bzip2-state-input-start state) input-start (bzip2-state-input-index state) input-start (bzip2-state-input-end state) input-end (bzip2-state-output state) output (bzip2-state-output-start state) output-start (bzip2-state-output-index state) output-start (bzip2-state-output-end state) output-end) (catch 'bzip2-done (%bzip2-state-machine state)) (values (- (bzip2-state-input-index state) input-start) (- (bzip2-state-output-index state) output-start)))) (defun make-bzip2-state () (let ((state (%make-bzip2-state))) (setf (dstate-checksum state) (make-crc32) (dstate-update-checksum state) #'update-crc32) state))
froydnj/chipz
1a1ab9eaf0140a3d34882c4c489b2e653e791430
add more methods on DECOMPRESS from a pathname
diff --git a/decompress.lisp b/decompress.lisp index 1f3ae39..ef50948 100644 --- a/decompress.lisp +++ b/decompress.lisp @@ -1,195 +1,216 @@ (in-package :chipz) ;;; We provide several convenience functions for decompression: ;;; ;;; * decompress a buffer to a newly-consed buffer; ;;; * decompress a stream to a newly-consed buffer; +;;; * decompress a pathane to a newly-consed buffer; ;;; * decompress a buffer to a user-specified buffer; ;;; * decompress a buffer to a stream; ;;; * decompress a stream to a stream. +;;; * decompress a pathname to another pathname; +;;; * decompress a pathname to a stream; ;;; ;;; We do not provide stream->buffer decompression, as we have no way of ;;; knowing how much to read from the stream to fill the buffer, no way ;;; of determining what to do with possible state left in the ;;; INFLATE-STATE that we used, etc. Application-specific logic will ;;; have to handle those bits. (defgeneric decompress (output state input &key &allow-other-keys) (:method (output format input &rest keys) (%decompress output format input keys))) (defun %decompress (output format input keys) (let ((state (make-dstate format))) (multiple-value-prog1 (apply #'decompress output state input keys) (finish-dstate state)))) ;;; SUBSEQ is specified to always make a copy. But we don't want an ;;; exact copy of a freshly-consed vector; that'd be wasteful. (defun maybe-subseq (v end) (if (= end (length v)) v (subseq v 0 end))) (defun decompress-fun-for-state (state) (typecase state (inflate-state #'%inflate) (bzip2-state #'%bzip2-decompress))) ;; For convenience. +(defun %decompress-from-pathname (output state pathname buffer-size) + (with-open-file (stream pathname :element-type '(unsigned-byte 8) + :direction :input) + (decompress output state stream + :buffer-size (if (eq buffer-size :file-length) + (file-length stream) + buffer-size)))) + (defmethod decompress ((output null) (state decompression-state) (input pathname) &key) - (with-open-file (stream input :element-type '(unsigned-byte 8) - :direction :input) - (decompress output state stream :buffer-size (file-length stream)))) + (%decompress-from-pathname output state input :file-length)) + +(defmethod decompress ((output pathname) (state decompression-state) (input pathname) + &key buffer-size) + (check-type buffer-size (or null integer)) + (with-open-file (stream output :element-type '(unsigned-byte 8) + :direction :output) + (%decompress-from-pathname stream state input buffer-size))) + +(defmethod decompress ((output stream) (state decompression-state) (input pathname) + &key buffer-size) + (check-type buffer-size (or null integer)) + (%decompress-from-pathname output state input buffer-size)) (defun %decompress/null-vector (state input fun input-start input-end buffer-size) (declare (type function fun)) (loop with output = (make-array buffer-size :element-type '(unsigned-byte 8)) with output-start = 0 do (cond ((= output-start (length output)) ;; Reallocate the output buffer. (let ((new (make-array (* 2 (length output)) :element-type '(unsigned-byte 8)))) (setf output (replace new output)))) (t (multiple-value-bind (consumed produced) (funcall fun state input output :input-start input-start :input-end input-end :output-start output-start :output-end (length output)) (incf input-start consumed) (incf output-start produced) (when (or (dstate-done state) (and (or (>= input-start input-end) (zerop consumed)) (zerop produced))) (return-from %decompress/null-vector (maybe-subseq output output-start)))))))) (defmethod decompress ((output null) (state decompression-state) (input vector) &key (input-start 0) input-end buffer-size) (%decompress/null-vector state input (decompress-fun-for-state state) input-start (or input-end (length input)) (or buffer-size +default-buffer-size+))) (defun %decompress/null-stream (state input fun buffer-size) (declare (type function fun)) (let ((input-buffer (make-array 8192 :element-type '(unsigned-byte 8)))) (declare (dynamic-extent input-buffer)) (loop with input-start = 0 with input-end = 0 with output = (make-array buffer-size :element-type '(unsigned-byte 8)) with output-start = 0 initially (setf input-end (read-sequence input-buffer input)) do (cond ((= output-start (length output)) ;; Reallocate the output buffer. (let ((new (make-array (* 2 (length output)) :element-type '(unsigned-byte 8)))) (setf output (replace new output)))) (t (multiple-value-bind (consumed produced) (funcall fun state input-buffer output :input-start input-start :input-end input-end :output-start output-start) (incf input-start consumed) (incf output-start produced) (let ((input-consumed-p (>= input-start input-end))) ;; Get more input if possible. (when input-consumed-p (setf input-start 0 input-end (read-sequence input-buffer input))) (when (or (dstate-done state) (and (or (and input-consumed-p (zerop input-end)) (zerop consumed)) (zerop produced))) (return-from %decompress/null-stream (maybe-subseq output output-start)))))))))) (defmethod decompress ((output null) (state decompression-state) (input stream) &key buffer-size) (%decompress/null-stream state input (decompress-fun-for-state state) (or buffer-size +default-buffer-size+))) (defun %decompress/vector-vector (output state input fun input-start input-end output-start output-end) (declare (type simple-octet-vector input output)) (declare (type function fun)) (loop with n-bytes-consumed = 0 and n-bytes-produced = 0 do (multiple-value-bind (consumed produced) (funcall fun state input output :input-start input-start :input-end input-end :output-start output-start :output-end output-end) (incf input-start consumed) (incf output-start produced) (incf n-bytes-consumed consumed) (incf n-bytes-produced produced) (when (and (or (>= input-start input-end) (zerop consumed)) (or (>= output-start output-end) (zerop produced))) (return-from %decompress/vector-vector (values n-bytes-consumed n-bytes-produced)))))) (defmethod decompress ((output vector) (state decompression-state) (input vector) &key (input-start 0) input-end (output-start 0) output-end) (%decompress/vector-vector output state input (decompress-fun-for-state state) input-start (or input-end (length input)) output-start (or output-end (length output)))) (defun %decompress/stream-vector (output state input fun input-start input-end) (declare (type function fun)) (let ((buffer (make-array 8192 :element-type '(unsigned-byte 8)))) (declare (dynamic-extent buffer)) (loop (multiple-value-bind (consumed produced) (funcall fun state input buffer :input-start input-start :input-end input-end) (incf input-start consumed) (write-sequence buffer output :end produced) (when (or (dstate-done state) (and (or (>= input-start input-end) (zerop consumed)) (zerop produced))) (return-from %decompress/stream-vector output)))))) (defmethod decompress ((output stream) (state decompression-state) (input vector) &key (input-start 0) input-end) (%decompress/stream-vector output state input (decompress-fun-for-state state) input-start (or input-end (length input)))) (defun %decompress/stream-stream (output state input fun) (declare (type function fun)) (let ((input-buffer (make-array 8192 :element-type '(unsigned-byte 8))) (output-buffer (make-array 8192 :element-type '(unsigned-byte 8)))) (declare (dynamic-extent input-buffer output-buffer)) (loop with input-start = 0 with input-end = 0 initially (setf input-end (read-sequence input-buffer input)) do (multiple-value-bind (consumed produced) (funcall fun state input-buffer output-buffer :input-start input-start :input-end input-end) (incf input-start consumed) (write-sequence output-buffer output :end produced) (let ((input-consumed-p (>= input-start input-end))) (when input-consumed-p (setf input-start 0 input-end (read-sequence input-buffer input))) (when (or (dstate-done state) (and (or (and input-consumed-p (zerop input-end)) (zerop consumed)) (zerop produced))) (return-from %decompress/stream-stream output))))))) (defmethod decompress ((output stream) (state decompression-state) (input stream) &key) (%decompress/stream-stream output state input (decompress-fun-for-state state)))
froydnj/chipz
ab76d48ad6e683d78e9f4b870c64602594aabf96
workaround ABCL structure accessor + VALUES bug
diff --git a/crc32.lisp b/crc32.lisp index d5f0c56..3f62ca0 100644 --- a/crc32.lisp +++ b/crc32.lisp @@ -1,85 +1,88 @@ ;;;; crc32.lisp -- implementation of the CRC32 checksum (in-package :chipz) #+sbcl (progn (defstruct (crc32 (:copier copy-crc32)) (crc #xffffffff :type (unsigned-byte 32))) (defun update-crc32 (state vector start end) (declare (type simple-octet-vector vector)) (declare (type index start end)) (do ((crc (crc32-crc state)) (i start (1+ i)) (table +crc32-table+)) ((>= i end) (setf (crc32-crc state) crc) state) (declare (type (unsigned-byte 32) crc)) (setf crc (logxor (aref table (logand (logxor crc (aref vector i)) #xff)) (ash crc -8))))) (defun produce-crc32 (state) (logxor #xffffffff (crc32-crc state))) ) ;; An implementation that conses significantly less on most ;; implementations. Credit to Zach Beane. #-sbcl (progn (defstruct (crc32 (:copier copy-crc32)) (low #xffff) (high #xffff)) (defun crc32-table () (let ((table (make-array 512 :element-type '(unsigned-byte 16)))) (dotimes (n 256 table) (let ((c n)) (declare (type (unsigned-byte 32) c)) (dotimes (k 8) (if (logbitp 0 c) (setf c (logxor #xEDB88320 (ash c -1))) (setf c (ash c -1))) (setf (aref table (ash n 1)) (ldb (byte 16 16) c) (aref table (1+ (ash n 1))) (ldb (byte 16 0) c))))))) (defvar *crc32-table* (crc32-table)) (defun crc32 (high low buf start count) (declare (type (unsigned-byte 16) high low) (type index start count) (type simple-octet-vector buf) (optimize speed)) (let ((i start) (table *crc32-table*)) (declare (type index i) (type (simple-array (unsigned-byte 16) (*)) table)) (dotimes (j count (values high low)) (let ((index (logxor (logand low #xFF) (aref buf i)))) (declare (type (integer 0 255) index)) (let ((high-index (ash index 1)) (low-index (1+ (ash index 1)))) (declare (type (integer 0 511) high-index low-index)) (let ((t-high (aref table high-index)) (t-low (aref table low-index))) (declare (type (unsigned-byte 16) t-high t-low)) (incf i) (setf low (logxor (ash (logand high #xFF) 8) (ash low -8) t-low)) (setf high (logxor (ash high -8) t-high)))))))) (defun update-crc32 (state vector start end) - (setf (values (crc32-high state) - (crc32-low state)) - (crc32 (crc32-high state) (crc32-low state) - vector start (- end start)))) + ;; ABCL used to miscompile (SETF (VALUES (ACCESSOR ...) ...) ...) + ;; in case you were wondering why we take this route. + (multiple-value-bind (high low) (crc32 (crc32-high state) (crc32-low state) + vector start (- end start)) + (setf (crc32-high state) high + (crc32-low state) low) + (values high low))) (defun produce-crc32 (state) (+ (ash (logxor (crc32-high state) #xFFFF) 16) (logxor (crc32-low state) #xFFFF))) )
froydnj/chipz
ebf13979e2947772d61b42df5aa774c35fa0b791
fix thinko in new DECOMPRESS method
diff --git a/decompress.lisp b/decompress.lisp index d851f99..1f3ae39 100644 --- a/decompress.lisp +++ b/decompress.lisp @@ -1,194 +1,195 @@ (in-package :chipz) ;;; We provide several convenience functions for decompression: ;;; ;;; * decompress a buffer to a newly-consed buffer; ;;; * decompress a stream to a newly-consed buffer; ;;; * decompress a buffer to a user-specified buffer; ;;; * decompress a buffer to a stream; ;;; * decompress a stream to a stream. ;;; ;;; We do not provide stream->buffer decompression, as we have no way of ;;; knowing how much to read from the stream to fill the buffer, no way ;;; of determining what to do with possible state left in the ;;; INFLATE-STATE that we used, etc. Application-specific logic will ;;; have to handle those bits. (defgeneric decompress (output state input &key &allow-other-keys) (:method (output format input &rest keys) (%decompress output format input keys))) (defun %decompress (output format input keys) (let ((state (make-dstate format))) (multiple-value-prog1 (apply #'decompress output state input keys) (finish-dstate state)))) ;;; SUBSEQ is specified to always make a copy. But we don't want an ;;; exact copy of a freshly-consed vector; that'd be wasteful. (defun maybe-subseq (v end) (if (= end (length v)) v (subseq v 0 end))) (defun decompress-fun-for-state (state) (typecase state (inflate-state #'%inflate) (bzip2-state #'%bzip2-decompress))) ;; For convenience. -(defmethod decompress ((output null) (state decompression-state) (input pathname)) +(defmethod decompress ((output null) (state decompression-state) (input pathname) + &key) (with-open-file (stream input :element-type '(unsigned-byte 8) :direction :input) (decompress output state stream :buffer-size (file-length stream)))) (defun %decompress/null-vector (state input fun input-start input-end buffer-size) (declare (type function fun)) (loop with output = (make-array buffer-size :element-type '(unsigned-byte 8)) with output-start = 0 do (cond ((= output-start (length output)) ;; Reallocate the output buffer. (let ((new (make-array (* 2 (length output)) :element-type '(unsigned-byte 8)))) (setf output (replace new output)))) (t (multiple-value-bind (consumed produced) (funcall fun state input output :input-start input-start :input-end input-end :output-start output-start :output-end (length output)) (incf input-start consumed) (incf output-start produced) (when (or (dstate-done state) (and (or (>= input-start input-end) (zerop consumed)) (zerop produced))) (return-from %decompress/null-vector (maybe-subseq output output-start)))))))) (defmethod decompress ((output null) (state decompression-state) (input vector) &key (input-start 0) input-end buffer-size) (%decompress/null-vector state input (decompress-fun-for-state state) input-start (or input-end (length input)) (or buffer-size +default-buffer-size+))) (defun %decompress/null-stream (state input fun buffer-size) (declare (type function fun)) (let ((input-buffer (make-array 8192 :element-type '(unsigned-byte 8)))) (declare (dynamic-extent input-buffer)) (loop with input-start = 0 with input-end = 0 with output = (make-array buffer-size :element-type '(unsigned-byte 8)) with output-start = 0 initially (setf input-end (read-sequence input-buffer input)) do (cond ((= output-start (length output)) ;; Reallocate the output buffer. (let ((new (make-array (* 2 (length output)) :element-type '(unsigned-byte 8)))) (setf output (replace new output)))) (t (multiple-value-bind (consumed produced) (funcall fun state input-buffer output :input-start input-start :input-end input-end :output-start output-start) (incf input-start consumed) (incf output-start produced) (let ((input-consumed-p (>= input-start input-end))) ;; Get more input if possible. (when input-consumed-p (setf input-start 0 input-end (read-sequence input-buffer input))) (when (or (dstate-done state) (and (or (and input-consumed-p (zerop input-end)) (zerop consumed)) (zerop produced))) (return-from %decompress/null-stream (maybe-subseq output output-start)))))))))) (defmethod decompress ((output null) (state decompression-state) (input stream) &key buffer-size) (%decompress/null-stream state input (decompress-fun-for-state state) (or buffer-size +default-buffer-size+))) (defun %decompress/vector-vector (output state input fun input-start input-end output-start output-end) (declare (type simple-octet-vector input output)) (declare (type function fun)) (loop with n-bytes-consumed = 0 and n-bytes-produced = 0 do (multiple-value-bind (consumed produced) (funcall fun state input output :input-start input-start :input-end input-end :output-start output-start :output-end output-end) (incf input-start consumed) (incf output-start produced) (incf n-bytes-consumed consumed) (incf n-bytes-produced produced) (when (and (or (>= input-start input-end) (zerop consumed)) (or (>= output-start output-end) (zerop produced))) (return-from %decompress/vector-vector (values n-bytes-consumed n-bytes-produced)))))) (defmethod decompress ((output vector) (state decompression-state) (input vector) &key (input-start 0) input-end (output-start 0) output-end) (%decompress/vector-vector output state input (decompress-fun-for-state state) input-start (or input-end (length input)) output-start (or output-end (length output)))) (defun %decompress/stream-vector (output state input fun input-start input-end) (declare (type function fun)) (let ((buffer (make-array 8192 :element-type '(unsigned-byte 8)))) (declare (dynamic-extent buffer)) (loop (multiple-value-bind (consumed produced) (funcall fun state input buffer :input-start input-start :input-end input-end) (incf input-start consumed) (write-sequence buffer output :end produced) (when (or (dstate-done state) (and (or (>= input-start input-end) (zerop consumed)) (zerop produced))) (return-from %decompress/stream-vector output)))))) (defmethod decompress ((output stream) (state decompression-state) (input vector) &key (input-start 0) input-end) (%decompress/stream-vector output state input (decompress-fun-for-state state) input-start (or input-end (length input)))) (defun %decompress/stream-stream (output state input fun) (declare (type function fun)) (let ((input-buffer (make-array 8192 :element-type '(unsigned-byte 8))) (output-buffer (make-array 8192 :element-type '(unsigned-byte 8)))) (declare (dynamic-extent input-buffer output-buffer)) (loop with input-start = 0 with input-end = 0 initially (setf input-end (read-sequence input-buffer input)) do (multiple-value-bind (consumed produced) (funcall fun state input-buffer output-buffer :input-start input-start :input-end input-end) (incf input-start consumed) (write-sequence output-buffer output :end produced) (let ((input-consumed-p (>= input-start input-end))) (when input-consumed-p (setf input-start 0 input-end (read-sequence input-buffer input))) (when (or (dstate-done state) (and (or (and input-consumed-p (zerop input-end)) (zerop consumed)) (zerop produced))) (return-from %decompress/stream-stream output))))))) (defmethod decompress ((output stream) (state decompression-state) (input stream) &key) (%decompress/stream-stream output state input (decompress-fun-for-state state)))
froydnj/chipz
b5c2feed6a83ab2a3dd94de49fbd1aaf5dcb8765
switch crc32 over to salza's crc32 algorithm
diff --git a/NEWS b/NEWS index 4f8dd45..c4fba3b 100644 --- a/NEWS +++ b/NEWS @@ -1,106 +1,111 @@ hey emacs, show me an -*- mode: outline -*- * Version ** bug fixes Stack overflow problems on several implementations have been fixed. (Thanks to Zach Beane for pointing this out.) +** improvements + +consing when computing the CRC32 checksum for gzip has been reduced. +(Thanks to Zach Beane for permission to pull his code from Salza.) + ** new features A new method on DECOMPRESS has been added for decompressing files into memory. * Version 0.7.4, released 2009-10-26 ** bug fixes CRC32 checksums are now calculated properly. (Thanks to Sven Van Caekenberghe.) ** improvements READ-SEQUENCE is now supported on Gray streams, which may result in a significant performance boost. * Version 0.7.3, released 2009-05-09 ** bug fixes Checksum errors now throw the correct error, rather than complaining about an unknown checksum-mismatch error. (Thanks to _3b on #lisp.) Fixed an error when decompressing raw deflate data. (Thanks to _3b on #lisp.) Fixed an error in rare cases when reading checksums. (Thanks to _3b on #lisp.) * Version 0.7.2, released 2008-12-20 ** bug fixes Gray streams now work correctly. (Thanks to Austin Haas.) * Version 0.7.1, released 2008-12-17 ** bug fixes Fixed some errors related to confusion between keywords and CHIPZ symbols. (Thanks to Austin Haas and Tomas Zellerin.) * Version 0.7.0, released 2008-10-24 ** new features bzip2 decompression is now included. Please see the documentation for more details. ** improvements DECOMPRESS now supports the keyword argument :BUFFER-SIZE. Please see the documentation for more details. Checksum verification is now performed for gzip and zlib data. * Version 0.6.1, released 2008-10-03 ** bug fixes Various fixes have been applied to increase Chipz's portability. (Thanks to Zach Beane.) * Version 0.6.0, released 2008-09-27 ** new features Gray streams are now supported on Lispworks, CMUCL, Allegro, and OpenMCL. There has been a significant amount of optimization work done on the library and decompression shows better than order-of-magnitude speedups on SBCL. * Version 0.5.1, released 2008-02-09 ** bug fixes DECOMPRESS now handles :INPUT-END properly in all cases. (Thanks to Jeremy English.) * Version 0.5, released 2008-01-02 Completely redid the structure of the library. The API is now modeled after that of `zlib', with convenience functions added. Gray streams interfaces added. * Version 0.1.1, released 2006-01-27 Fixed PROCESS-NO-COMPRESS-BLOCK to read from the underlying stream, rather than the bitstream. (Thanks to Eric Marsden.) * Version 0.1, released 2006-01-27 Initial release. diff --git a/crc32.lisp b/crc32.lisp index b08b0bc..d5f0c56 100644 --- a/crc32.lisp +++ b/crc32.lisp @@ -1,24 +1,85 @@ ;;;; crc32.lisp -- implementation of the CRC32 checksum (in-package :chipz) +#+sbcl +(progn (defstruct (crc32 (:copier copy-crc32)) (crc #xffffffff :type (unsigned-byte 32))) (defun update-crc32 (state vector start end) (declare (type simple-octet-vector vector)) (declare (type index start end)) (do ((crc (crc32-crc state)) (i start (1+ i)) (table +crc32-table+)) ((>= i end) (setf (crc32-crc state) crc) state) (declare (type (unsigned-byte 32) crc)) (setf crc (logxor (aref table (logand (logxor crc (aref vector i)) #xff)) (ash crc -8))))) (defun produce-crc32 (state) (logxor #xffffffff (crc32-crc state))) +) + +;; An implementation that conses significantly less on most +;; implementations. Credit to Zach Beane. +#-sbcl +(progn +(defstruct (crc32 + (:copier copy-crc32)) + (low #xffff) + (high #xffff)) + +(defun crc32-table () + (let ((table (make-array 512 :element-type '(unsigned-byte 16)))) + (dotimes (n 256 table) + (let ((c n)) + (declare (type (unsigned-byte 32) c)) + (dotimes (k 8) + (if (logbitp 0 c) + (setf c (logxor #xEDB88320 (ash c -1))) + (setf c (ash c -1))) + (setf (aref table (ash n 1)) (ldb (byte 16 16) c) + (aref table (1+ (ash n 1))) (ldb (byte 16 0) c))))))) + +(defvar *crc32-table* (crc32-table)) + +(defun crc32 (high low buf start count) + (declare (type (unsigned-byte 16) high low) + (type index start count) + (type simple-octet-vector buf) + (optimize speed)) + (let ((i start) + (table *crc32-table*)) + (declare (type index i) + (type (simple-array (unsigned-byte 16) (*)) table)) + (dotimes (j count (values high low)) + (let ((index (logxor (logand low #xFF) (aref buf i)))) + (declare (type (integer 0 255) index)) + (let ((high-index (ash index 1)) + (low-index (1+ (ash index 1)))) + (declare (type (integer 0 511) high-index low-index)) + (let ((t-high (aref table high-index)) + (t-low (aref table low-index))) + (declare (type (unsigned-byte 16) t-high t-low)) + (incf i) + (setf low (logxor (ash (logand high #xFF) 8) + (ash low -8) + t-low)) + (setf high (logxor (ash high -8) t-high)))))))) + +(defun update-crc32 (state vector start end) + (setf (values (crc32-high state) + (crc32-low state)) + (crc32 (crc32-high state) (crc32-low state) + vector start (- end start)))) + +(defun produce-crc32 (state) + (+ (ash (logxor (crc32-high state) #xFFFF) 16) + (logxor (crc32-low state) #xFFFF))) +)
froydnj/chipz
1550f1df08ccc7827d6a1a349c28405c4c70c76f
add convenience function for decompressing files
diff --git a/NEWS b/NEWS index 01ecc6e..4f8dd45 100644 --- a/NEWS +++ b/NEWS @@ -1,101 +1,106 @@ hey emacs, show me an -*- mode: outline -*- * Version ** bug fixes Stack overflow problems on several implementations have been fixed. (Thanks to Zach Beane for pointing this out.) +** new features + +A new method on DECOMPRESS has been added for decompressing files into +memory. + * Version 0.7.4, released 2009-10-26 ** bug fixes CRC32 checksums are now calculated properly. (Thanks to Sven Van Caekenberghe.) ** improvements READ-SEQUENCE is now supported on Gray streams, which may result in a significant performance boost. * Version 0.7.3, released 2009-05-09 ** bug fixes Checksum errors now throw the correct error, rather than complaining about an unknown checksum-mismatch error. (Thanks to _3b on #lisp.) Fixed an error when decompressing raw deflate data. (Thanks to _3b on #lisp.) Fixed an error in rare cases when reading checksums. (Thanks to _3b on #lisp.) * Version 0.7.2, released 2008-12-20 ** bug fixes Gray streams now work correctly. (Thanks to Austin Haas.) * Version 0.7.1, released 2008-12-17 ** bug fixes Fixed some errors related to confusion between keywords and CHIPZ symbols. (Thanks to Austin Haas and Tomas Zellerin.) * Version 0.7.0, released 2008-10-24 ** new features bzip2 decompression is now included. Please see the documentation for more details. ** improvements DECOMPRESS now supports the keyword argument :BUFFER-SIZE. Please see the documentation for more details. Checksum verification is now performed for gzip and zlib data. * Version 0.6.1, released 2008-10-03 ** bug fixes Various fixes have been applied to increase Chipz's portability. (Thanks to Zach Beane.) * Version 0.6.0, released 2008-09-27 ** new features Gray streams are now supported on Lispworks, CMUCL, Allegro, and OpenMCL. There has been a significant amount of optimization work done on the library and decompression shows better than order-of-magnitude speedups on SBCL. * Version 0.5.1, released 2008-02-09 ** bug fixes DECOMPRESS now handles :INPUT-END properly in all cases. (Thanks to Jeremy English.) * Version 0.5, released 2008-01-02 Completely redid the structure of the library. The API is now modeled after that of `zlib', with convenience functions added. Gray streams interfaces added. * Version 0.1.1, released 2006-01-27 Fixed PROCESS-NO-COMPRESS-BLOCK to read from the underlying stream, rather than the bitstream. (Thanks to Eric Marsden.) * Version 0.1, released 2006-01-27 Initial release. diff --git a/decompress.lisp b/decompress.lisp index 9f0e6fa..d851f99 100644 --- a/decompress.lisp +++ b/decompress.lisp @@ -1,188 +1,194 @@ (in-package :chipz) ;;; We provide several convenience functions for decompression: ;;; ;;; * decompress a buffer to a newly-consed buffer; ;;; * decompress a stream to a newly-consed buffer; ;;; * decompress a buffer to a user-specified buffer; ;;; * decompress a buffer to a stream; ;;; * decompress a stream to a stream. ;;; ;;; We do not provide stream->buffer decompression, as we have no way of ;;; knowing how much to read from the stream to fill the buffer, no way ;;; of determining what to do with possible state left in the ;;; INFLATE-STATE that we used, etc. Application-specific logic will ;;; have to handle those bits. (defgeneric decompress (output state input &key &allow-other-keys) (:method (output format input &rest keys) (%decompress output format input keys))) (defun %decompress (output format input keys) (let ((state (make-dstate format))) (multiple-value-prog1 (apply #'decompress output state input keys) (finish-dstate state)))) ;;; SUBSEQ is specified to always make a copy. But we don't want an ;;; exact copy of a freshly-consed vector; that'd be wasteful. (defun maybe-subseq (v end) (if (= end (length v)) v (subseq v 0 end))) (defun decompress-fun-for-state (state) (typecase state (inflate-state #'%inflate) (bzip2-state #'%bzip2-decompress))) +;; For convenience. +(defmethod decompress ((output null) (state decompression-state) (input pathname)) + (with-open-file (stream input :element-type '(unsigned-byte 8) + :direction :input) + (decompress output state stream :buffer-size (file-length stream)))) + (defun %decompress/null-vector (state input fun input-start input-end buffer-size) (declare (type function fun)) (loop with output = (make-array buffer-size :element-type '(unsigned-byte 8)) with output-start = 0 do (cond ((= output-start (length output)) ;; Reallocate the output buffer. (let ((new (make-array (* 2 (length output)) :element-type '(unsigned-byte 8)))) (setf output (replace new output)))) (t (multiple-value-bind (consumed produced) (funcall fun state input output :input-start input-start :input-end input-end :output-start output-start :output-end (length output)) (incf input-start consumed) (incf output-start produced) (when (or (dstate-done state) (and (or (>= input-start input-end) (zerop consumed)) (zerop produced))) (return-from %decompress/null-vector (maybe-subseq output output-start)))))))) (defmethod decompress ((output null) (state decompression-state) (input vector) &key (input-start 0) input-end buffer-size) (%decompress/null-vector state input (decompress-fun-for-state state) input-start (or input-end (length input)) (or buffer-size +default-buffer-size+))) (defun %decompress/null-stream (state input fun buffer-size) (declare (type function fun)) (let ((input-buffer (make-array 8192 :element-type '(unsigned-byte 8)))) (declare (dynamic-extent input-buffer)) (loop with input-start = 0 with input-end = 0 with output = (make-array buffer-size :element-type '(unsigned-byte 8)) with output-start = 0 initially (setf input-end (read-sequence input-buffer input)) do (cond ((= output-start (length output)) ;; Reallocate the output buffer. (let ((new (make-array (* 2 (length output)) :element-type '(unsigned-byte 8)))) (setf output (replace new output)))) (t (multiple-value-bind (consumed produced) (funcall fun state input-buffer output :input-start input-start :input-end input-end :output-start output-start) (incf input-start consumed) (incf output-start produced) (let ((input-consumed-p (>= input-start input-end))) ;; Get more input if possible. (when input-consumed-p (setf input-start 0 input-end (read-sequence input-buffer input))) (when (or (dstate-done state) (and (or (and input-consumed-p (zerop input-end)) (zerop consumed)) (zerop produced))) (return-from %decompress/null-stream (maybe-subseq output output-start)))))))))) (defmethod decompress ((output null) (state decompression-state) (input stream) &key buffer-size) (%decompress/null-stream state input (decompress-fun-for-state state) (or buffer-size +default-buffer-size+))) (defun %decompress/vector-vector (output state input fun input-start input-end output-start output-end) (declare (type simple-octet-vector input output)) (declare (type function fun)) (loop with n-bytes-consumed = 0 and n-bytes-produced = 0 do (multiple-value-bind (consumed produced) (funcall fun state input output :input-start input-start :input-end input-end :output-start output-start :output-end output-end) (incf input-start consumed) (incf output-start produced) (incf n-bytes-consumed consumed) (incf n-bytes-produced produced) (when (and (or (>= input-start input-end) (zerop consumed)) (or (>= output-start output-end) (zerop produced))) (return-from %decompress/vector-vector (values n-bytes-consumed n-bytes-produced)))))) (defmethod decompress ((output vector) (state decompression-state) (input vector) &key (input-start 0) input-end (output-start 0) output-end) (%decompress/vector-vector output state input (decompress-fun-for-state state) input-start (or input-end (length input)) output-start (or output-end (length output)))) (defun %decompress/stream-vector (output state input fun input-start input-end) (declare (type function fun)) (let ((buffer (make-array 8192 :element-type '(unsigned-byte 8)))) (declare (dynamic-extent buffer)) (loop (multiple-value-bind (consumed produced) (funcall fun state input buffer :input-start input-start :input-end input-end) (incf input-start consumed) (write-sequence buffer output :end produced) (when (or (dstate-done state) (and (or (>= input-start input-end) (zerop consumed)) (zerop produced))) (return-from %decompress/stream-vector output)))))) (defmethod decompress ((output stream) (state decompression-state) (input vector) &key (input-start 0) input-end) (%decompress/stream-vector output state input (decompress-fun-for-state state) input-start (or input-end (length input)))) (defun %decompress/stream-stream (output state input fun) (declare (type function fun)) (let ((input-buffer (make-array 8192 :element-type '(unsigned-byte 8))) (output-buffer (make-array 8192 :element-type '(unsigned-byte 8)))) (declare (dynamic-extent input-buffer output-buffer)) (loop with input-start = 0 with input-end = 0 initially (setf input-end (read-sequence input-buffer input)) do (multiple-value-bind (consumed produced) (funcall fun state input-buffer output-buffer :input-start input-start :input-end input-end) (incf input-start consumed) (write-sequence output-buffer output :end produced) (let ((input-consumed-p (>= input-start input-end))) (when input-consumed-p (setf input-start 0 input-end (read-sequence input-buffer input))) (when (or (dstate-done state) (and (or (and input-consumed-p (zerop input-end)) (zerop consumed)) (zerop produced))) (return-from %decompress/stream-stream output))))))) (defmethod decompress ((output stream) (state decompression-state) (input stream) &key) (%decompress/stream-stream output state input (decompress-fun-for-state state)))
froydnj/chipz
9a4ba87ad053c210e1a9c77be97a9e171da199f8
make stack overflow less likely in state machines
diff --git a/NEWS b/NEWS index 62a8e08..01ecc6e 100644 --- a/NEWS +++ b/NEWS @@ -1,94 +1,101 @@ hey emacs, show me an -*- mode: outline -*- +* Version + +** bug fixes + +Stack overflow problems on several implementations have been fixed. +(Thanks to Zach Beane for pointing this out.) + * Version 0.7.4, released 2009-10-26 ** bug fixes CRC32 checksums are now calculated properly. (Thanks to Sven Van Caekenberghe.) ** improvements READ-SEQUENCE is now supported on Gray streams, which may result in a significant performance boost. * Version 0.7.3, released 2009-05-09 ** bug fixes Checksum errors now throw the correct error, rather than complaining about an unknown checksum-mismatch error. (Thanks to _3b on #lisp.) Fixed an error when decompressing raw deflate data. (Thanks to _3b on #lisp.) Fixed an error in rare cases when reading checksums. (Thanks to _3b on #lisp.) * Version 0.7.2, released 2008-12-20 ** bug fixes Gray streams now work correctly. (Thanks to Austin Haas.) * Version 0.7.1, released 2008-12-17 ** bug fixes Fixed some errors related to confusion between keywords and CHIPZ symbols. (Thanks to Austin Haas and Tomas Zellerin.) * Version 0.7.0, released 2008-10-24 ** new features bzip2 decompression is now included. Please see the documentation for more details. ** improvements DECOMPRESS now supports the keyword argument :BUFFER-SIZE. Please see the documentation for more details. Checksum verification is now performed for gzip and zlib data. * Version 0.6.1, released 2008-10-03 ** bug fixes Various fixes have been applied to increase Chipz's portability. (Thanks to Zach Beane.) * Version 0.6.0, released 2008-09-27 ** new features Gray streams are now supported on Lispworks, CMUCL, Allegro, and OpenMCL. There has been a significant amount of optimization work done on the library and decompression shows better than order-of-magnitude speedups on SBCL. * Version 0.5.1, released 2008-02-09 ** bug fixes DECOMPRESS now handles :INPUT-END properly in all cases. (Thanks to Jeremy English.) * Version 0.5, released 2008-01-02 Completely redid the structure of the library. The API is now modeled after that of `zlib', with convenience functions added. Gray streams interfaces added. * Version 0.1.1, released 2006-01-27 Fixed PROCESS-NO-COMPRESS-BLOCK to read from the underlying stream, rather than the bitstream. (Thanks to Eric Marsden.) * Version 0.1, released 2006-01-27 Initial release. diff --git a/bzip2.lisp b/bzip2.lisp index b7c7653..04990b5 100644 --- a/bzip2.lisp +++ b/bzip2.lisp @@ -1,961 +1,964 @@ (in-package :chipz) ;;; bzip2's decompress.c looks relatively simple, but a great deal of ;;; complexity and cleverness is hidden behind C preprpocessor macro. ;;; The single biggest help in understand what is going on behind the ;;; macros is to read "Coroutines in C" by Simon Tatham: ;;; ;;; http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html ;;; ;;; decompress.c is using the same technique described in the paper, ;;; although with a slightly different implementation. ;;; ;;; Lisp, fortunately/alas, does not admit the same sort of techniques ;;; that C does--at least not expressed exactly the same way. So our ;;; translation naturally differs in some places. For example, to make ;;; it easier to figure out how much state we have to preserve, we ;;; choose to read more in at one time than decompress.c--the magic ;;; number header all at once or the bits for the mapping table in ;;; larger chunks than 1 bit at a time, for instance. ;;; Reading things in larger chunks than bits means that we have to do ;;; bit-reversal of various quantities. (defun reverse-ub4 (x) (let ((table (load-time-value (make-array 16 :element-type 'fixnum :initial-contents '(0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15))))) (aref table x))) (defun reverse-ub8 (x) (logior (ash (reverse-ub4 (ldb (byte 4 0) x)) 4) (reverse-ub4 (ldb (byte 4 4) x)))) (defun reverse-ub16 (x) (logior (ash (reverse-ub8 (ldb (byte 8 0) x)) 8) (reverse-ub8 (ldb (byte 8 8) x)))) -(defmacro transition-to (next-state) - `(progn - (setf (bzip2-state-state state) #',next-state) - (,next-state state))) (defvar *dummy-vec* (make-array #.+bz-max-alpha-size+ :element-type '(unsigned-byte 32))) (defstruct (bzip2-state (:include decompression-state) (:constructor %make-bzip2-state)) ;; For doing the final run-length decoding. (out-ch 0 :type (unsigned-byte 8)) (out-len 0 :type (integer 0 260)) (block-randomized-p nil) (rntogo 0 :type (unsigned-byte 32)) (rntpos 0 :type (unsigned-byte 32)) (100k-block-size 1 :type (integer 1 9)) (small-decompression-p nil) (current-block-number 0) ;; For undoing the Burrows-Wheeler transform. */ (original-pointer 0) (t-position 0 :type (integer 0 (900000))) (k0 0) (unzftab (make-array 256 :element-type '(unsigned-byte 32)) :type (simple-array (unsigned-byte 32) (256))) (n-blocks-used 0) (cftab (make-array 257 :element-type '(unsigned-byte 32)) :type (simple-array (unsigned-byte 32) (257))) (cftab-copy (make-array 257 :element-type '(unsigned-byte 32)) :type (simple-array (unsigned-byte 32) (257))) ;; For undoing the Burrows-Wheeler transform (FAST). (tt (make-array 0 :element-type '(unsigned-byte 32)) :type (simple-array (unsigned-byte 32) (*))) ;; Stored and calculated CRCs. (stored-block-crc 0 :type (unsigned-byte 32)) (stored-combined-crc 0 :type (unsigned-byte 32)) (calculated-block-crc #xffffffff :type (unsigned-byte 32)) (calculated-combined-crc 0 :type (unsigned-byte 32)) ;; Map of bytes used in block ("mapping table"). (n-in-use 0 :type (integer 0 256)) (in-use (make-array 256 :initial-element nil) :type (simple-array t (256))) ;; This was a byte array; we have chosen to make it a simple integer ;; and index it with LOGBITP. (in-use-16 0 :type (unsigned-byte 16)) (seq-to-unseq (make-array 256 :element-type '(unsigned-byte 8)) :type (simple-array (unsigned-byte 8) (256))) ;; For decoding the MTF values. (mtfa (make-array +mtfa-size+ :element-type '(unsigned-byte 8)) :type (simple-array (unsigned-byte 8) (#.+mtfa-size+))) (mtfbase (make-array (/ 256 +mtfl-size+) :element-type '(unsigned-byte 16)) :type (simple-array (unsigned-byte 16) (#.(/ 256 +mtfl-size+)))) (selector (make-array +bz-max-selectors+ :element-type '(unsigned-byte 8)) :type (simple-array (unsigned-byte 8) (#.+bz-max-selectors+))) (selector-mtf (make-array +bz-max-selectors+ :element-type '(unsigned-byte 8)) :type (simple-array (unsigned-byte 8) (#.+bz-max-selectors+))) (len (make-array '(#.+bz-n-groups+ #.+bz-max-alpha-size+) :element-type '(unsigned-byte 8)) :type (simple-array (unsigned-byte 8) (#.+bz-n-groups+ #.+bz-max-alpha-size+))) (mtf-continuation nil :type (or null function)) (limit #1=(let ((w (make-array +bz-n-groups+))) (dotimes (i +bz-n-groups+ w) (setf (aref w i) (make-array +bz-max-alpha-size+ :element-type '(unsigned-byte 32))))) :type (simple-array t (#.+bz-n-groups+))) (base #1# :type (simple-array t (#.+bz-n-groups+))) (perm #1# :type (simple-array t (#.+bz-n-groups+))) (min-lengths (make-array #.+bz-n-groups+ :element-type '(unsigned-byte 32)) :type (simple-array (unsigned-byte 32) (#.+bz-n-groups+))) ;; Save variables for scalars in the decompression code. (i 0) (j 0) (alpha-size 0 :type (integer 0 258)) (n-groups 0) (n-selectors 0) (EOB 0 :type (integer 0 257)) ;; FIXME: check on the declarations for these three. (group-number 0 :type fixnum) (group-position 0 :type fixnum) (lval 0 :type fixnum) (nblockMAX 0 :type (integer 0 900000)) (nblock 0 :type (integer 0 (900000))) (es 0 :type fixnum) (N 0 :type fixnum) (curr 0 :type (integer 0 20)) (zn 0 :type (integer 0 20)) (zvec 0 :type (integer 0 #.(expt 2 20))) (g-minlen 0 :type (integer 0 23)) (g-limit *dummy-vec* :type (simple-array (unsigned-byte 32) (#.+bz-max-alpha-size+))) (g-base *dummy-vec* :type (simple-array (unsigned-byte 32) (#.+bz-max-alpha-size+))) (g-perm *dummy-vec* :type (simple-array (unsigned-byte 32) (#.+bz-max-alpha-size+)))) (defmethod print-object ((object bzip2-state) stream) (print-unreadable-object (object stream) (format stream "Bzip2 state bits: ~X/~D input: ~D/~D output ~D/~D" (bzip2-state-bits object) (bzip2-state-n-bits object) (bzip2-state-input-index object) (bzip2-state-input-end object) (bzip2-state-output-index object) (bzip2-state-output-end object)))) (defun make-maps (state) (declare (type bzip2-state state)) (loop with n-in-use = 0 with in-use-table = (bzip2-state-in-use state) with seq-to-unseq = (bzip2-state-seq-to-unseq state) for i from 0 below 256 when (aref in-use-table i) do (setf (aref seq-to-unseq n-in-use) i n-in-use (1+ n-in-use)) finally (return (setf (bzip2-state-n-in-use state) n-in-use)))) (defun make-decode-tables (state group min-len max-len alpha-size) (declare (type bzip2-state state)) (let* ((limit (aref (bzip2-state-limit state) group)) (base (aref (bzip2-state-base state) group)) (perm (aref (bzip2-state-perm state) group)) (len (bzip2-state-len state)) (rmi (array-row-major-index len group 0))) (loop with pp = 0 for i from min-len to max-len do (dotimes (j alpha-size) (when (= (row-major-aref len (+ rmi j)) i) (setf (aref perm pp) j) (incf pp)))) (loop for i from 0 below +bz-max-code-len+ do (setf (aref base i) 0 (aref limit i) 0)) (loop for i from 0 below alpha-size do (incf (aref base (1+ (row-major-aref len (+ i rmi)))))) (loop for i from 1 below +bz-max-code-len+ do (incf (aref base i) (aref base (1- i)))) (loop with vec = 0 for i from min-len to max-len do (incf vec (- (aref base (1+ i)) (aref base i))) (setf (aref limit i) (1- vec) vec (ash vec 1))) (loop for i from (+ min-len 1) to max-len do (setf (aref base i) (- (ash (1+ (aref limit (1- i))) 1) (aref base i)))))) (defun undo-rle-obuf-to-output (state) (declare (optimize speed)) (cond ((bzip2-state-block-randomized-p state) (error 'bzip2-randomized-blocks-unimplemented)) (t (let ((calculated-block-crc (bzip2-state-calculated-block-crc state)) (out-ch (bzip2-state-out-ch state)) (out-len (bzip2-state-out-len state)) (n-blocks-used (bzip2-state-n-blocks-used state)) (k0 (bzip2-state-k0 state)) (k1 0) (tt (bzip2-state-tt state)) (t-position (bzip2-state-t-position state)) (nblockpp (1+ (bzip2-state-nblock state))) (output (bzip2-state-output state)) (index (bzip2-state-output-index state)) (end (bzip2-state-output-end state))) (declare (type (unsigned-byte 32) calculated-block-crc)) (declare (type (integer 0 260) out-len)) (declare (type (unsigned-byte 8) k0 k1)) (declare (type (integer 0 900000) n-blocks-used nblockpp)) (declare (type (unsigned-byte 32) t-position)) (macrolet ((get-fast () `(prog2 (setf t-position (aref tt t-position)) (logand t-position #xff) (setf t-position (ash t-position -8))))) (tagbody START ;; "try to finish existing run" (when (zerop out-len) (go GRAB-MORE)) (loop (when (= index end) (go FINISH)) (when (= out-len 1) (go LEN-EQUAL-ONE)) (setf (aref output index) out-ch) (setf calculated-block-crc (logand #xffffffff (logxor (ash calculated-block-crc 8) (aref +bzip2-crc32-table+ (logxor (ash calculated-block-crc -24) out-ch))))) (decf out-len) (incf index)) LEN-EQUAL-ONE (when (= index end) (setf out-len 1) (go FINISH)) (setf (aref output index) out-ch) (setf calculated-block-crc (logand #xffffffff (logxor (ash calculated-block-crc 8) (aref +bzip2-crc32-table+ (logxor (ash calculated-block-crc -24) out-ch))))) (incf index) GRAB-MORE ;; "Only caused by corrupt data stream?" (when (> n-blocks-used nblockpp) (return-from undo-rle-obuf-to-output t)) (when (= n-blocks-used nblockpp) (setf out-len 0) (go FINISH)) (setf out-ch k0) (setf k1 (get-fast)) (incf n-blocks-used) (unless (= k1 k0) (setf k0 k1) (go LEN-EQUAL-ONE)) (when (= n-blocks-used nblockpp) (go LEN-EQUAL-ONE)) (setf out-len 2) (setf k1 (get-fast)) (incf n-blocks-used) (when (= n-blocks-used nblockpp) (go CONTINUE)) (unless (= k1 k0) (setf k0 k1) (go CONTINUE)) (setf out-len 3) (setf k1 (get-fast)) (incf n-blocks-used) (when (= n-blocks-used nblockpp) (go CONTINUE)) (unless (= k1 k0) (setf k0 k1) (go CONTINUE)) (setf k1 (get-fast)) (incf n-blocks-used) (setf out-len (+ k1 4)) (setf k0 (get-fast)) (incf n-blocks-used) CONTINUE (go START) FINISH) #+nil (incf (bzip2-state-total-out state) (- index (bzip2-state-output-index state) )) ;; Restore cached values. (setf (bzip2-state-calculated-block-crc state) calculated-block-crc (bzip2-state-out-ch state) out-ch (bzip2-state-out-len state) out-len (bzip2-state-n-blocks-used state) n-blocks-used (bzip2-state-k0 state) k0 (bzip2-state-t-position state) t-position (bzip2-state-output-index state) index) nil))))) ;;; decompress.c has various logic relating to whether the user has ;;; chosen "small" decompression, which uses less memory. We're just ;;; going to be memory-intensive and always pick the large option. Maybe ;;; someday we can come back and add the small option. (defun %bzip2-state-machine (state) (declare (type bzip2-state state)) - (declare (optimize speed)) - (labels ( - (read-bits (n state) - (declare (type (integer 0 32) n)) - (declare (type bzip2-state state)) - (prog1 - ;; We don't use (BYTE N (- ...)) here because doing it - ;; this way is ~10% faster on SBCL. - (ldb (byte n 0) - (ash (bzip2-state-bits state) - (the (integer -31 0) - (- n (bzip2-state-n-bits state))))) - (decf (bzip2-state-n-bits state) n))) - - (ensure-bits (n state) - (declare (type (integer 0 32) n)) - (declare (type bzip2-state state)) - (let ((bits (bzip2-state-bits state)) - (n-bits (bzip2-state-n-bits state)) - (input-index (bzip2-state-input-index state))) - (declare (type (unsigned-byte 32) bits)) - (loop while (< n-bits n) - when (>= input-index (bzip2-state-input-end state)) - do (progn - (setf (bzip2-state-bits state) bits - (bzip2-state-n-bits state) n-bits - (bzip2-state-input-index state) input-index) - (throw 'bzip2-done nil)) - do (let ((byte (aref (bzip2-state-input state) input-index))) - (declare (type (unsigned-byte 8) byte)) - (setf bits - (logand #xffffffff (logior (ash bits 8) byte))) - (incf n-bits 8) - (incf input-index)) - finally (setf (bzip2-state-bits state) bits - (bzip2-state-n-bits state) n-bits - (bzip2-state-input-index state) input-index)))) - - (ensure-and-read-bits (n state) - (ensure-bits n state) - (read-bits n state)) - - (bzip2-header (state) - (declare (type bzip2-state state)) - (let ((header-field (ensure-and-read-bits 32 state))) - (declare (type (unsigned-byte 32) header-field)) - (unless (and (= (ldb (byte 8 24) header-field) +bz-header-b+) - (= (ldb (byte 8 16) header-field) +bz-header-z+) - (= (ldb (byte 8 8) header-field) +bz-header-h+)) - (error 'invalid-bzip2-magic)) - (let ((block-size-magic-byte (ldb (byte 8 0) header-field))) - (unless (<= (+ +bz-header-0+ 1) - block-size-magic-byte - (+ +bz-header-0+ 9)) + (declare (optimize (speed 3) (debug 1) (space 0) (compilation-speed 0))) + ;; See the enormous comment in %INFLATE-STATE-MACHINE for what's going + ;; on here. + (macrolet ((transition-to (next-state) + `(progn + (setf (bzip2-state-state state) #',next-state) + #+(or sbcl cmu) + (,next-state state)))) + (labels ( + (read-bits (n state) + (declare (type (integer 0 32) n)) + (declare (type bzip2-state state)) + (prog1 + ;; We don't use (BYTE N (- ...)) here because doing it + ;; this way is ~10% faster on SBCL. + (ldb (byte n 0) + (ash (bzip2-state-bits state) + (the (integer -31 0) + (- n (bzip2-state-n-bits state))))) + (decf (bzip2-state-n-bits state) n))) + + (ensure-bits (n state) + (declare (type (integer 0 32) n)) + (declare (type bzip2-state state)) + (let ((bits (bzip2-state-bits state)) + (n-bits (bzip2-state-n-bits state)) + (input-index (bzip2-state-input-index state))) + (declare (type (unsigned-byte 32) bits)) + (loop while (< n-bits n) + when (>= input-index (bzip2-state-input-end state)) + do (progn + (setf (bzip2-state-bits state) bits + (bzip2-state-n-bits state) n-bits + (bzip2-state-input-index state) input-index) + (throw 'bzip2-done nil)) + do (let ((byte (aref (bzip2-state-input state) input-index))) + (declare (type (unsigned-byte 8) byte)) + (setf bits + (logand #xffffffff (logior (ash bits 8) byte))) + (incf n-bits 8) + (incf input-index)) + finally (setf (bzip2-state-bits state) bits + (bzip2-state-n-bits state) n-bits + (bzip2-state-input-index state) input-index)))) + + (ensure-and-read-bits (n state) + (ensure-bits n state) + (read-bits n state)) + + (bzip2-header (state) + (declare (type bzip2-state state)) + (let ((header-field (ensure-and-read-bits 32 state))) + (declare (type (unsigned-byte 32) header-field)) + (unless (and (= (ldb (byte 8 24) header-field) +bz-header-b+) + (= (ldb (byte 8 16) header-field) +bz-header-z+) + (= (ldb (byte 8 8) header-field) +bz-header-h+)) (error 'invalid-bzip2-magic)) - (setf (bzip2-state-100k-block-size state) (- block-size-magic-byte - +bz-header-0+)) - ;; BZIP2 SMALL - (setf (bzip2-state-tt state) - (make-array (* (bzip2-state-100k-block-size state) +100k+) - :element-type '(unsigned-byte 32))) - (transition-to bzip2-block-header1)))) - - (bzip2-block-header1 (state) - (declare (type bzip2-state state)) - (let ((byte (ensure-and-read-bits 8 state))) - (case byte - (#x17 (transition-to bzip2-end-header2)) - (#x31 (transition-to bzip2-block-header2)) - (t (error 'invalid-bzip2-data))))) - - (bzip2-block-header2 (state) - (declare (type bzip2-state state)) - (let ((byte (ensure-and-read-bits 8 state))) - (if (= byte #x41) - (transition-to bzip2-block-header3) - (error 'invalid-bzip2-data)))) - - (bzip2-block-header3 (state) - (declare (type bzip2-state state)) - (let ((byte (ensure-and-read-bits 8 state))) - (if (= byte #x59) - (transition-to bzip2-block-header4) - (error 'invalid-bzip2-data)))) - - (bzip2-block-header4 (state) - (declare (type bzip2-state state)) - (let ((byte (ensure-and-read-bits 8 state))) - (if (= byte #x26) - (transition-to bzip2-block-header5) - (error 'invalid-bzip2-data)))) - - (bzip2-block-header5 (state) - (declare (type bzip2-state state)) - (let ((byte (ensure-and-read-bits 8 state))) - (if (= byte #x53) - (transition-to bzip2-block-header6) - (error 'invalid-bzip2-data)))) - - (bzip2-block-header6 (state) - (declare (type bzip2-state state)) - (let ((byte (ensure-and-read-bits 8 state))) - (unless (= byte #x59) - (error 'invalid-bzip2-data)) - (incf (bzip2-state-current-block-number state)) - (transition-to bzip2-block-crc32))) - - (bzip2-block-crc32 (state) - (declare (type bzip2-state state)) - (let ((crc32 (ensure-and-read-bits 32 state))) - (setf (bzip2-state-stored-block-crc state) crc32) - (transition-to bzip2-block-randombit))) - - (bzip2-block-randombit (state) - (declare (type bzip2-state state)) - (let ((randomized-p (ensure-and-read-bits 1 state))) - (setf (bzip2-state-block-randomized-p state) (= randomized-p 1)) - (transition-to bzip2-original-pointer))) - - (bzip2-original-pointer (state) - (declare (type bzip2-state state)) - (let ((original-pointer (ensure-and-read-bits 24 state))) - (unless (<= 0 original-pointer - (+ 10 (* (bzip2-state-100k-block-size state) +100k+))) - (error 'invalid-bzip2-data)) - (setf (bzip2-state-original-pointer state) original-pointer) - (transition-to bzip2-mapping-table1))) - - (bzip2-mapping-table1 (state) - (declare (type bzip2-state state)) - (let ((in-use-16 (reverse-ub16 (ensure-and-read-bits 16 state)))) - (setf (bzip2-state-in-use-16 state) in-use-16) - (setf (bzip2-state-i state) 0) - (fill (bzip2-state-in-use state) nil) - (transition-to bzip2-mapping-table2))) - - (bzip2-mapping-table2 (state) - (declare (type bzip2-state state)) - (loop with in-use-16 = (bzip2-state-in-use-16 state) - with in-use-table = (bzip2-state-in-use state) - while (< (bzip2-state-i state) 16) - when (logbitp (bzip2-state-i state) in-use-16) - do (let ((in-use (reverse-ub16 (ensure-and-read-bits 16 state)))) - (dotimes (i 16) - (setf (aref in-use-table (+ (* (bzip2-state-i state) 16) - i)) - (logbitp i in-use)))) - do + (let ((block-size-magic-byte (ldb (byte 8 0) header-field))) + (unless (<= (+ +bz-header-0+ 1) + block-size-magic-byte + (+ +bz-header-0+ 9)) + (error 'invalid-bzip2-magic)) + (setf (bzip2-state-100k-block-size state) (- block-size-magic-byte + +bz-header-0+)) + ;; BZIP2 SMALL + (setf (bzip2-state-tt state) + (make-array (* (bzip2-state-100k-block-size state) +100k+) + :element-type '(unsigned-byte 32))) + (transition-to bzip2-block-header1)))) + + (bzip2-block-header1 (state) + (declare (type bzip2-state state)) + (let ((byte (ensure-and-read-bits 8 state))) + (case byte + (#x17 (transition-to bzip2-end-header2)) + (#x31 (transition-to bzip2-block-header2)) + (t (error 'invalid-bzip2-data))))) + + (bzip2-block-header2 (state) + (declare (type bzip2-state state)) + (let ((byte (ensure-and-read-bits 8 state))) + (if (= byte #x41) + (transition-to bzip2-block-header3) + (error 'invalid-bzip2-data)))) + + (bzip2-block-header3 (state) + (declare (type bzip2-state state)) + (let ((byte (ensure-and-read-bits 8 state))) + (if (= byte #x59) + (transition-to bzip2-block-header4) + (error 'invalid-bzip2-data)))) + + (bzip2-block-header4 (state) + (declare (type bzip2-state state)) + (let ((byte (ensure-and-read-bits 8 state))) + (if (= byte #x26) + (transition-to bzip2-block-header5) + (error 'invalid-bzip2-data)))) + + (bzip2-block-header5 (state) + (declare (type bzip2-state state)) + (let ((byte (ensure-and-read-bits 8 state))) + (if (= byte #x53) + (transition-to bzip2-block-header6) + (error 'invalid-bzip2-data)))) + + (bzip2-block-header6 (state) + (declare (type bzip2-state state)) + (let ((byte (ensure-and-read-bits 8 state))) + (unless (= byte #x59) + (error 'invalid-bzip2-data)) + (incf (bzip2-state-current-block-number state)) + (transition-to bzip2-block-crc32))) + + (bzip2-block-crc32 (state) + (declare (type bzip2-state state)) + (let ((crc32 (ensure-and-read-bits 32 state))) + (setf (bzip2-state-stored-block-crc state) crc32) + (transition-to bzip2-block-randombit))) + + (bzip2-block-randombit (state) + (declare (type bzip2-state state)) + (let ((randomized-p (ensure-and-read-bits 1 state))) + (setf (bzip2-state-block-randomized-p state) (= randomized-p 1)) + (transition-to bzip2-original-pointer))) + + (bzip2-original-pointer (state) + (declare (type bzip2-state state)) + (let ((original-pointer (ensure-and-read-bits 24 state))) + (unless (<= 0 original-pointer + (+ 10 (* (bzip2-state-100k-block-size state) +100k+))) + (error 'invalid-bzip2-data)) + (setf (bzip2-state-original-pointer state) original-pointer) + (transition-to bzip2-mapping-table1))) + + (bzip2-mapping-table1 (state) + (declare (type bzip2-state state)) + (let ((in-use-16 (reverse-ub16 (ensure-and-read-bits 16 state)))) + (setf (bzip2-state-in-use-16 state) in-use-16) + (setf (bzip2-state-i state) 0) + (fill (bzip2-state-in-use state) nil) + (transition-to bzip2-mapping-table2))) + + (bzip2-mapping-table2 (state) + (declare (type bzip2-state state)) + (loop with in-use-16 = (bzip2-state-in-use-16 state) + with in-use-table = (bzip2-state-in-use state) + while (< (bzip2-state-i state) 16) + when (logbitp (bzip2-state-i state) in-use-16) + do (let ((in-use (reverse-ub16 (ensure-and-read-bits 16 state)))) + (dotimes (i 16) + (setf (aref in-use-table (+ (* (bzip2-state-i state) 16) + i)) + (logbitp i in-use)))) + do (incf (bzip2-state-i state))) - (let ((n-in-use (make-maps state))) - (when (zerop n-in-use) - (error 'invalid-bzip2-data)) - (setf (bzip2-state-alpha-size state) - (+ n-in-use 2)) - (transition-to bzip2-selector1))) - - (bzip2-selector1 (state) - (declare (type bzip2-state state)) - (let ((n-groups (ensure-and-read-bits 3 state))) - (unless (<= 3 n-groups 6) - (error 'invalid-bzip2-data)) - (setf (bzip2-state-n-groups state) n-groups) - (transition-to bzip2-selector2))) - - (bzip2-selector2 (state) - (declare (type bzip2-state state)) - (let ((n-selectors (ensure-and-read-bits 15 state))) - (unless (plusp n-selectors) - (error 'invalid-bzip2-data)) - (setf (bzip2-state-n-selectors state) n-selectors) - (setf (bzip2-state-i state) 0) - (transition-to bzip2-selector3a))) - - (bzip2-selector3a (state) - (declare (type bzip2-state state)) - (setf (bzip2-state-j state) 0) - (transition-to bzip2-selector3b)) - - (bzip2-selector3b (state) - (declare (type bzip2-state state)) - (loop - do (let ((bit (ensure-and-read-bits 1 state))) - (when (zerop bit) (loop-finish)) - (when (>= (incf (bzip2-state-j state)) - (bzip2-state-n-groups state)) - (error 'invalid-bzip2-data))) - finally - (setf (aref (bzip2-state-selector-mtf state) - (bzip2-state-i state)) - (bzip2-state-j state))) - (if (< (incf (bzip2-state-i state)) - (bzip2-state-n-selectors state)) - (transition-to bzip2-selector3a) - (transition-to bzip2-selector-undo-mtf-values))) - - (bzip2-selector-undo-mtf-values (state) - (declare (type bzip2-state state)) - (let ((pos (make-array +bz-n-groups+ - :element-type '(unsigned-byte 8))) - (n-groups (bzip2-state-n-groups state)) - (n-selectors (bzip2-state-n-selectors state)) - (selector-table (bzip2-state-selector state)) - (selector-mtf (bzip2-state-selector-mtf state))) - (declare (dynamic-extent pos)) - (dotimes (i n-groups) - (setf (aref pos i) i)) - (dotimes (i n-selectors) - (let* ((v (aref selector-mtf i)) - (tmp (aref pos v))) - (loop until (zerop v) - do (setf (aref pos v) (aref pos (1- v))) - (decf v)) - (setf (aref pos 0) tmp) - (setf (aref selector-table i) tmp))) + (let ((n-in-use (make-maps state))) + (when (zerop n-in-use) + (error 'invalid-bzip2-data)) + (setf (bzip2-state-alpha-size state) + (+ n-in-use 2)) + (transition-to bzip2-selector1))) + + (bzip2-selector1 (state) + (declare (type bzip2-state state)) + (let ((n-groups (ensure-and-read-bits 3 state))) + (unless (<= 3 n-groups 6) + (error 'invalid-bzip2-data)) + (setf (bzip2-state-n-groups state) n-groups) + (transition-to bzip2-selector2))) + + (bzip2-selector2 (state) + (declare (type bzip2-state state)) + (let ((n-selectors (ensure-and-read-bits 15 state))) + (unless (plusp n-selectors) + (error 'invalid-bzip2-data)) + (setf (bzip2-state-n-selectors state) n-selectors) + (setf (bzip2-state-i state) 0) + (transition-to bzip2-selector3a))) + + (bzip2-selector3a (state) + (declare (type bzip2-state state)) (setf (bzip2-state-j state) 0) - (transition-to bzip2-coding-tables-groups-loop))) - - (bzip2-coding-tables-groups-loop (state) - (declare (type bzip2-state state)) - (cond - ((< (bzip2-state-j state) (bzip2-state-n-groups state)) - (setf (bzip2-state-curr state) (ensure-and-read-bits 5 state) - (bzip2-state-i state) 0) - (transition-to bzip2-coding-tables-alpha-loop)) - (t - (transition-to bzip2-create-huffman-decode-tables)))) - - (bzip2-coding-tables-alpha-loop (state) - (declare (type bzip2-state state)) - (unless (<= 1 (bzip2-state-curr state) 20) - (error 'invalid-bzip2-data)) - (let ((uc (ensure-and-read-bits 1 state))) + (transition-to bzip2-selector3b)) + + (bzip2-selector3b (state) + (declare (type bzip2-state state)) + (loop + do (let ((bit (ensure-and-read-bits 1 state))) + (when (zerop bit) (loop-finish)) + (when (>= (incf (bzip2-state-j state)) + (bzip2-state-n-groups state)) + (error 'invalid-bzip2-data))) + finally + (setf (aref (bzip2-state-selector-mtf state) + (bzip2-state-i state)) + (bzip2-state-j state))) + (if (< (incf (bzip2-state-i state)) + (bzip2-state-n-selectors state)) + (transition-to bzip2-selector3a) + (transition-to bzip2-selector-undo-mtf-values))) + + (bzip2-selector-undo-mtf-values (state) + (declare (type bzip2-state state)) + (let ((pos (make-array +bz-n-groups+ + :element-type '(unsigned-byte 8))) + (n-groups (bzip2-state-n-groups state)) + (n-selectors (bzip2-state-n-selectors state)) + (selector-table (bzip2-state-selector state)) + (selector-mtf (bzip2-state-selector-mtf state))) + (declare (dynamic-extent pos)) + (dotimes (i n-groups) + (setf (aref pos i) i)) + (dotimes (i n-selectors) + (let* ((v (aref selector-mtf i)) + (tmp (aref pos v))) + (loop until (zerop v) + do (setf (aref pos v) (aref pos (1- v))) + (decf v)) + (setf (aref pos 0) tmp) + (setf (aref selector-table i) tmp))) + (setf (bzip2-state-j state) 0) + (transition-to bzip2-coding-tables-groups-loop))) + + (bzip2-coding-tables-groups-loop (state) + (declare (type bzip2-state state)) (cond - ((zerop uc) - (setf (aref (bzip2-state-len state) (bzip2-state-j state) (bzip2-state-i state)) - (bzip2-state-curr state)) - (cond - ((< (incf (bzip2-state-i state)) - (bzip2-state-alpha-size state)) - (bzip2-coding-tables-alpha-loop state)) - (t - (incf (bzip2-state-j state)) - (transition-to bzip2-coding-tables-groups-loop)))) + ((< (bzip2-state-j state) (bzip2-state-n-groups state)) + (setf (bzip2-state-curr state) (ensure-and-read-bits 5 state) + (bzip2-state-i state) 0) + (transition-to bzip2-coding-tables-alpha-loop)) (t - (transition-to bzip2-coding-tables-alpha-loop2))))) - - (bzip2-coding-tables-alpha-loop2 (state) - (declare (type bzip2-state state)) - (let ((uc (ensure-and-read-bits 1 state))) - (if (zerop uc) - (incf (bzip2-state-curr state)) - (decf (bzip2-state-curr state))) - (transition-to bzip2-coding-tables-alpha-loop))) - - (bzip2-create-huffman-decode-tables (state) - (declare (type bzip2-state state)) - (loop with n-groups = (bzip2-state-n-groups state) - with len = (bzip2-state-len state) - for x from 0 below n-groups - do (loop with minLen = 32 - with maxLen = 0 - with alpha-size = (bzip2-state-alpha-size state) - for y from 0 below alpha-size - do (let ((xy (aref len x y))) - (setf maxLen (max maxLen xy) - minLen (min minLen xy))) - finally - (make-decode-tables state x minLen maxLen alpha-size) - (setf (aref (bzip2-state-min-lengths state) x) minLen)) - finally - ;; We're not 'returning' anything here, we're just - ;; forcing this call to be in tail position. - (return (transition-to bzip2-initialize-mtf-values)))) + (transition-to bzip2-create-huffman-decode-tables)))) - (bzip2-initialize-mtf-values (state) - (declare (type bzip2-state state)) - (loop - with kk = (1- +mtfa-size+) - with mtfa = (bzip2-state-mtfa state) - with mtfbase = (bzip2-state-mtfbase state) - initially - (setf (bzip2-state-EOB state) (1+ (bzip2-state-n-in-use state)) - (bzip2-state-nblockMAX state) (* 100000 (bzip2-state-100k-block-size state)) - (bzip2-state-group-number state) -1 - (bzip2-state-group-position state) 0) - (fill (bzip2-state-unzftab state) 0) - for i from (1- (floor 256 +mtfl-size+)) downto 0 - do (loop for j from (1- +mtfl-size+) downto 0 - do - (setf (aref mtfa kk) (+ (* i +mtfl-size+) j)) - (decf kk) - finally - (setf (aref mtfbase i) (1+ kk))) - finally - (setf (bzip2-state-nblock state) 0 - (bzip2-state-mtf-continuation state) #'bzip2-enter-mtf-decode-loop) + (bzip2-coding-tables-alpha-loop (state) + (declare (type bzip2-state state)) + (unless (<= 1 (bzip2-state-curr state) 20) + (error 'invalid-bzip2-data)) + (let ((uc (ensure-and-read-bits 1 state))) + (cond + ((zerop uc) + (setf (aref (bzip2-state-len state) (bzip2-state-j state) (bzip2-state-i state)) + (bzip2-state-curr state)) + (cond + ((< (incf (bzip2-state-i state)) + (bzip2-state-alpha-size state)) + (bzip2-coding-tables-alpha-loop state)) + (t + (incf (bzip2-state-j state)) + (transition-to bzip2-coding-tables-groups-loop)))) + (t + (transition-to bzip2-coding-tables-alpha-loop2))))) + + (bzip2-coding-tables-alpha-loop2 (state) + (declare (type bzip2-state state)) + (let ((uc (ensure-and-read-bits 1 state))) + (if (zerop uc) + (incf (bzip2-state-curr state)) + (decf (bzip2-state-curr state))) + (transition-to bzip2-coding-tables-alpha-loop))) + + (bzip2-create-huffman-decode-tables (state) + (declare (type bzip2-state state)) + (loop with n-groups = (bzip2-state-n-groups state) + with len = (bzip2-state-len state) + for x from 0 below n-groups + do (loop with minLen = 32 + with maxLen = 0 + with alpha-size = (bzip2-state-alpha-size state) + for y from 0 below alpha-size + do (let ((xy (aref len x y))) + (setf maxLen (max maxLen xy) + minLen (min minLen xy))) + finally + (make-decode-tables state x minLen maxLen alpha-size) + (setf (aref (bzip2-state-min-lengths state) x) minLen)) + finally ;; We're not 'returning' anything here, we're just ;; forcing this call to be in tail position. - (return (transition-to bzip2-get-mtf-value)))) + (return (transition-to bzip2-initialize-mtf-values)))) - (bzip2-get-mtf-value (state) - (declare (type bzip2-state state)) - (when (zerop (bzip2-state-group-position state)) - (when (>= (incf (bzip2-state-group-number state)) - (bzip2-state-n-selectors state)) - (error 'invalid-bzip2-data)) - (let ((s (aref (bzip2-state-selector state) - (bzip2-state-group-number state)))) - (setf (bzip2-state-group-position state) +bz-g-size+ - (bzip2-state-g-minlen state) (aref (bzip2-state-min-lengths state) s) - (bzip2-state-g-limit state) (aref (bzip2-state-limit state) s) - (bzip2-state-g-perm state) (aref (bzip2-state-perm state) s) - (bzip2-state-g-base state) (aref (bzip2-state-base state) s)))) - (decf (bzip2-state-group-position state)) - (setf (bzip2-state-zn state) (bzip2-state-g-minlen state)) - (transition-to bzip2-get-mtf-value1)) - - (bzip2-get-mtf-value1 (state) - (declare (type bzip2-state state)) - (let ((zvec (ensure-and-read-bits (bzip2-state-zn state) state))) - (setf (bzip2-state-zvec state) zvec) - (transition-to bzip2-get-mtf-value2))) - - (bzip2-get-mtf-value2 (state) - (declare (type bzip2-state state)) - (when (> (bzip2-state-zn state) 20) - (error 'invalid-bzip2-data)) - (cond - ((<= (bzip2-state-zvec state) - (aref (bzip2-state-g-limit state) - (bzip2-state-zn state))) - (transition-to bzip2-get-mtf-value-done)) - (t - (incf (bzip2-state-zn state)) - (transition-to bzip2-get-mtf-value3)))) - - (bzip2-get-mtf-value3 (state) - (declare (type bzip2-state state)) - (let ((zj (ensure-and-read-bits 1 state))) - (setf (bzip2-state-zvec state) - (logior (ash (bzip2-state-zvec state) 1) zj)) - (transition-to bzip2-get-mtf-value2))) - - (bzip2-get-mtf-value-done (state) - (declare (type bzip2-state state)) - (let* ((g-base (bzip2-state-g-base state)) - (zn (bzip2-state-zn state)) - (zvec (bzip2-state-zvec state)) - (index (- zvec (aref g-base zn)))) - (when (or (< index 0) (>= index +bz-max-alpha-size+)) + (bzip2-initialize-mtf-values (state) + (declare (type bzip2-state state)) + (loop + with kk = (1- +mtfa-size+) + with mtfa = (bzip2-state-mtfa state) + with mtfbase = (bzip2-state-mtfbase state) + initially + (setf (bzip2-state-EOB state) (1+ (bzip2-state-n-in-use state)) + (bzip2-state-nblockMAX state) (* 100000 (bzip2-state-100k-block-size state)) + (bzip2-state-group-number state) -1 + (bzip2-state-group-position state) 0) + (fill (bzip2-state-unzftab state) 0) + for i from (1- (floor 256 +mtfl-size+)) downto 0 + do (loop for j from (1- +mtfl-size+) downto 0 + do + (setf (aref mtfa kk) (+ (* i +mtfl-size+) j)) + (decf kk) + finally + (setf (aref mtfbase i) (1+ kk))) + finally + (setf (bzip2-state-nblock state) 0 + (bzip2-state-mtf-continuation state) #'bzip2-enter-mtf-decode-loop) + ;; We're not 'returning' anything here, we're just + ;; forcing this call to be in tail position. + (return (transition-to bzip2-get-mtf-value)))) + + (bzip2-get-mtf-value (state) + (declare (type bzip2-state state)) + (when (zerop (bzip2-state-group-position state)) + (when (>= (incf (bzip2-state-group-number state)) + (bzip2-state-n-selectors state)) + (error 'invalid-bzip2-data)) + (let ((s (aref (bzip2-state-selector state) + (bzip2-state-group-number state)))) + (setf (bzip2-state-group-position state) +bz-g-size+ + (bzip2-state-g-minlen state) (aref (bzip2-state-min-lengths state) s) + (bzip2-state-g-limit state) (aref (bzip2-state-limit state) s) + (bzip2-state-g-perm state) (aref (bzip2-state-perm state) s) + (bzip2-state-g-base state) (aref (bzip2-state-base state) s)))) + (decf (bzip2-state-group-position state)) + (setf (bzip2-state-zn state) (bzip2-state-g-minlen state)) + (transition-to bzip2-get-mtf-value1)) + + (bzip2-get-mtf-value1 (state) + (declare (type bzip2-state state)) + (let ((zvec (ensure-and-read-bits (bzip2-state-zn state) state))) + (setf (bzip2-state-zvec state) zvec) + (transition-to bzip2-get-mtf-value2))) + + (bzip2-get-mtf-value2 (state) + (declare (type bzip2-state state)) + (when (> (bzip2-state-zn state) 20) (error 'invalid-bzip2-data)) - (setf (bzip2-state-lval state) - (aref (bzip2-state-g-perm state) index)) - (let ((f (bzip2-state-mtf-continuation state))) - (declare (type function f)) - (setf (bzip2-state-state state) f) - (funcall f state)))) - - (bzip2-enter-mtf-decode-loop (state) - (declare (type bzip2-state state)) - (let ((next-sym (bzip2-state-lval state))) (cond - ((= next-sym (bzip2-state-EOB state)) - (transition-to bzip2-prepare-cftab)) - ((or (= next-sym +bz-runa+) (= next-sym +bz-runb+)) - (setf (bzip2-state-es state) -1 - (bzip2-state-N state) 1) - (transition-to bzip2-decode-rle-sequence)) + ((<= (bzip2-state-zvec state) + (aref (bzip2-state-g-limit state) + (bzip2-state-zn state))) + (transition-to bzip2-get-mtf-value-done)) (t - (transition-to bzip2-runc))))) + (incf (bzip2-state-zn state)) + (transition-to bzip2-get-mtf-value3)))) + + (bzip2-get-mtf-value3 (state) + (declare (type bzip2-state state)) + (let ((zj (ensure-and-read-bits 1 state))) + (setf (bzip2-state-zvec state) + (logior (ash (bzip2-state-zvec state) 1) zj)) + (transition-to bzip2-get-mtf-value2))) + + (bzip2-get-mtf-value-done (state) + (declare (type bzip2-state state)) + (let* ((g-base (bzip2-state-g-base state)) + (zn (bzip2-state-zn state)) + (zvec (bzip2-state-zvec state)) + (index (- zvec (aref g-base zn)))) + (when (or (< index 0) (>= index +bz-max-alpha-size+)) + (error 'invalid-bzip2-data)) + (setf (bzip2-state-lval state) + (aref (bzip2-state-g-perm state) index)) + (let ((f (bzip2-state-mtf-continuation state))) + (declare (type function f)) + (setf (bzip2-state-state state) f) + (funcall f state)))) + + (bzip2-enter-mtf-decode-loop (state) + (declare (type bzip2-state state)) + (let ((next-sym (bzip2-state-lval state))) + (cond + ((= next-sym (bzip2-state-EOB state)) + (transition-to bzip2-prepare-cftab)) + ((or (= next-sym +bz-runa+) (= next-sym +bz-runb+)) + (setf (bzip2-state-es state) -1 + (bzip2-state-N state) 1) + (transition-to bzip2-decode-rle-sequence)) + (t + (transition-to bzip2-runc))))) - (bzip2-decode-rle-sequence (state) - (declare (type bzip2-state state)) - (let ((next-sym (bzip2-state-lval state))) - (cond - ((= next-sym +bz-runa+) - (incf (bzip2-state-es state) (bzip2-state-N state))) - ((= next-sym +bz-runb+) - (incf (bzip2-state-es state) (* (bzip2-state-N state) 2)))) - (setf (bzip2-state-N state) (* (bzip2-state-N state) 2)) - (setf (bzip2-state-mtf-continuation state) #'bzip2-maybe-finish-rle-sequence) - (transition-to bzip2-get-mtf-value))) - - (bzip2-maybe-finish-rle-sequence (state) - (declare (type bzip2-state state)) - (let ((next-sym (bzip2-state-lval state))) - (if (or (= next-sym +bz-runa+) (= next-sym +bz-runb+)) - (transition-to bzip2-decode-rle-sequence) - (transition-to bzip2-finish-rle-sequence)))) - - (bzip2-finish-rle-sequence (state) - (declare (type bzip2-state state)) - (let ((uc (aref (bzip2-state-seq-to-unseq state) - (aref (bzip2-state-mtfa state) - (aref (bzip2-state-mtfbase state) 0))))) - (incf (aref (bzip2-state-unzftab state) uc) - (incf (bzip2-state-es state))) - (if (bzip2-state-small-decompression-p state) - (error 'bzip2-small-decompression-unimplemented) - (loop with nblock = (bzip2-state-nblock state) - with nblockMAX = (bzip2-state-nblockMAX state) - with tt = (bzip2-state-tt state) - repeat (bzip2-state-es state) - do + (bzip2-decode-rle-sequence (state) + (declare (type bzip2-state state)) + (let ((next-sym (bzip2-state-lval state))) + (cond + ((= next-sym +bz-runa+) + (incf (bzip2-state-es state) (bzip2-state-N state))) + ((= next-sym +bz-runb+) + (incf (bzip2-state-es state) (* (bzip2-state-N state) 2)))) + (setf (bzip2-state-N state) (* (bzip2-state-N state) 2)) + (setf (bzip2-state-mtf-continuation state) #'bzip2-maybe-finish-rle-sequence) + (transition-to bzip2-get-mtf-value))) + + (bzip2-maybe-finish-rle-sequence (state) + (declare (type bzip2-state state)) + (let ((next-sym (bzip2-state-lval state))) + (if (or (= next-sym +bz-runa+) (= next-sym +bz-runb+)) + (transition-to bzip2-decode-rle-sequence) + (transition-to bzip2-finish-rle-sequence)))) + + (bzip2-finish-rle-sequence (state) + (declare (type bzip2-state state)) + (let ((uc (aref (bzip2-state-seq-to-unseq state) + (aref (bzip2-state-mtfa state) + (aref (bzip2-state-mtfbase state) 0))))) + (incf (aref (bzip2-state-unzftab state) uc) + (incf (bzip2-state-es state))) + (if (bzip2-state-small-decompression-p state) + (error 'bzip2-small-decompression-unimplemented) + (loop with nblock = (bzip2-state-nblock state) + with nblockMAX = (bzip2-state-nblockMAX state) + with tt = (bzip2-state-tt state) + repeat (bzip2-state-es state) + do (when (>= nblock nblockMAX) (error 'invalid-bzip2-data)) (setf (aref tt nblock) uc) (incf nblock) - finally + finally (setf (bzip2-state-nblock state) nblock) ;; We're not 'returning' anything here, we're ;; just forcing this call to be in tail ;; position. (return (transition-to bzip2-enter-mtf-decode-loop)))))) - (bzip2-runc (state) - (declare (type bzip2-state state)) - (let ((next-sym (bzip2-state-lval state)) - (uc 0)) - (when (>= (bzip2-state-nblock state) - (bzip2-state-nblockMAX state)) - (error 'invalid-bzip2-data)) - (let ((mtfbase (bzip2-state-mtfbase state)) - (mtfa (bzip2-state-mtfa state)) - (nn (1- next-sym))) - (cond - ((< nn +mtfl-size+) - ;; "avoid general-case expense" - (let ((pp (aref mtfbase 0))) - (setf uc (aref mtfa (+ pp nn))) - (replace mtfa mtfa :start1 (1+ pp) :end1 (+ pp nn 1) - :start2 pp :end2 (+ pp nn)) - (setf (aref mtfa pp) uc))) - (t - ;; "general case" - (let* ((lno (truncate nn +mtfl-size+)) - (off (rem nn +mtfl-size+)) - (pp (+ (aref mtfbase lno) off))) - (setf uc (aref mtfa pp)) - (loop while (> pp (aref mtfbase lno)) - do (setf (aref mtfa pp) (aref mtfa (1- pp))) - (decf pp)) - (incf (aref mtfbase lno)) - (loop for x from lno above 0 - do - (setf (aref mtfa (decf (aref mtfbase x))) - (aref mtfa (+ (aref mtfbase (1- x)) (1- +mtfl-size+))))) - (setf (aref mtfa (decf (aref mtfbase 0))) uc) - (when (zerop (aref mtfbase 0)) - (loop with kk = (1- +mtfa-size+) - for ii from (1- (floor 256 +mtfl-size+)) downto 0 - do (loop for jj from (1- +mtfl-size+) downto 0 - do (setf (aref mtfa kk) - (aref mtfa (+ (aref mtfbase ii) jj))) - (decf kk)) - (setf (aref mtfbase ii) (1+ kk))))))) - (incf (aref (bzip2-state-unzftab state) + (bzip2-runc (state) + (declare (type bzip2-state state)) + (let ((next-sym (bzip2-state-lval state)) + (uc 0)) + (when (>= (bzip2-state-nblock state) + (bzip2-state-nblockMAX state)) + (error 'invalid-bzip2-data)) + (let ((mtfbase (bzip2-state-mtfbase state)) + (mtfa (bzip2-state-mtfa state)) + (nn (1- next-sym))) + (cond + ((< nn +mtfl-size+) + ;; "avoid general-case expense" + (let ((pp (aref mtfbase 0))) + (setf uc (aref mtfa (+ pp nn))) + (replace mtfa mtfa :start1 (1+ pp) :end1 (+ pp nn 1) + :start2 pp :end2 (+ pp nn)) + (setf (aref mtfa pp) uc))) + (t + ;; "general case" + (let* ((lno (truncate nn +mtfl-size+)) + (off (rem nn +mtfl-size+)) + (pp (+ (aref mtfbase lno) off))) + (setf uc (aref mtfa pp)) + (loop while (> pp (aref mtfbase lno)) + do (setf (aref mtfa pp) (aref mtfa (1- pp))) + (decf pp)) + (incf (aref mtfbase lno)) + (loop for x from lno above 0 + do + (setf (aref mtfa (decf (aref mtfbase x))) + (aref mtfa (+ (aref mtfbase (1- x)) (1- +mtfl-size+))))) + (setf (aref mtfa (decf (aref mtfbase 0))) uc) + (when (zerop (aref mtfbase 0)) + (loop with kk = (1- +mtfa-size+) + for ii from (1- (floor 256 +mtfl-size+)) downto 0 + do (loop for jj from (1- +mtfl-size+) downto 0 + do (setf (aref mtfa kk) + (aref mtfa (+ (aref mtfbase ii) jj))) + (decf kk)) + (setf (aref mtfbase ii) (1+ kk))))))) + (incf (aref (bzip2-state-unzftab state) + (aref (bzip2-state-seq-to-unseq state) uc))) + (if (bzip2-state-small-decompression-p state) + (error 'bzip2-small-decompression-unimplemented) + (setf (aref (bzip2-state-tt state) (bzip2-state-nblock state)) (aref (bzip2-state-seq-to-unseq state) uc))) - (if (bzip2-state-small-decompression-p state) - (error 'bzip2-small-decompression-unimplemented) - (setf (aref (bzip2-state-tt state) (bzip2-state-nblock state)) - (aref (bzip2-state-seq-to-unseq state) uc))) - (incf (bzip2-state-nblock state)) - (setf (bzip2-state-mtf-continuation state) #'bzip2-enter-mtf-decode-loop) - (transition-to bzip2-get-mtf-value)))) - - (bzip2-prepare-cftab (state) - (declare (type bzip2-state state)) - (when (or (minusp (bzip2-state-original-pointer state)) - (>= (bzip2-state-original-pointer state) - (bzip2-state-nblock state))) - (error 'invalid-bzip2-data)) - (let ((cftab (bzip2-state-cftab state)) - (unzftab (bzip2-state-unzftab state))) - (setf (aref cftab 0) 0) - (replace cftab unzftab :start1 1 :end1 257 :start2 0 :end2 256) - (loop for i from 1 to 256 - do (incf (aref cftab i) (aref cftab (1- i)))) - (loop with nblock = (bzip2-state-nblock state) - for i from 0 to 256 - unless (<= 0 (aref cftab i) nblock) - do (error 'invalid-bzip2-data)) - (setf (bzip2-state-out-len state) 0 - (bzip2-state-out-ch state) 0 - (bzip2-state-calculated-block-crc state) #xffffffff) - (loop with nblock = (bzip2-state-nblock state) - with tt = (bzip2-state-tt state) - for i from 0 below nblock - do (let ((uc (logand (aref tt i) #xff))) - (setf (aref tt (aref cftab uc)) - (logior (aref tt (aref cftab uc)) (ash i 8))) - (incf (aref cftab uc))) - finally + (incf (bzip2-state-nblock state)) + (setf (bzip2-state-mtf-continuation state) #'bzip2-enter-mtf-decode-loop) + (transition-to bzip2-get-mtf-value)))) + + (bzip2-prepare-cftab (state) + (declare (type bzip2-state state)) + (when (or (minusp (bzip2-state-original-pointer state)) + (>= (bzip2-state-original-pointer state) + (bzip2-state-nblock state))) + (error 'invalid-bzip2-data)) + (let ((cftab (bzip2-state-cftab state)) + (unzftab (bzip2-state-unzftab state))) + (setf (aref cftab 0) 0) + (replace cftab unzftab :start1 1 :end1 257 :start2 0 :end2 256) + (loop for i from 1 to 256 + do (incf (aref cftab i) (aref cftab (1- i)))) + (loop with nblock = (bzip2-state-nblock state) + for i from 0 to 256 + unless (<= 0 (aref cftab i) nblock) + do (error 'invalid-bzip2-data)) + (setf (bzip2-state-out-len state) 0 + (bzip2-state-out-ch state) 0 + (bzip2-state-calculated-block-crc state) #xffffffff) + (loop with nblock = (bzip2-state-nblock state) + with tt = (bzip2-state-tt state) + for i from 0 below nblock + do (let ((uc (logand (aref tt i) #xff))) + (setf (aref tt (aref cftab uc)) + (logior (aref tt (aref cftab uc)) (ash i 8))) + (incf (aref cftab uc))) + finally (setf (bzip2-state-t-position state) (ash (aref tt (bzip2-state-original-pointer state)) -8)) (setf (bzip2-state-n-blocks-used state) 0) (cond ((bzip2-state-block-randomized-p state) (error 'bzip2-randomized-blocks-unimplemented)) (t (setf (bzip2-state-t-position state) (aref tt (bzip2-state-t-position state)) (bzip2-state-k0 state) (logand #xff (bzip2-state-t-position state)) (bzip2-state-t-position state) (ash (bzip2-state-t-position state) -8)) (incf (bzip2-state-n-blocks-used state)))) ;; We're not 'returning' anything here, we're just ;; forcing this call to be in tail position. (return (transition-to bzip2-output))))) - (bzip2-output (state) - (declare (type bzip2-state state)) - (let ((corruptp (undo-rle-obuf-to-output state))) - (when corruptp - (error 'invalid-bzip2-data)) - (unless (and (= (bzip2-state-n-blocks-used state) - (1+ (bzip2-state-nblock state))) - (zerop (bzip2-state-out-len state))) - (throw 'bzip2-done :ok)) - (let ((stored (bzip2-state-stored-block-crc state)) - (calculated (bzip2-state-calculated-block-crc state))) - (setf calculated (logand #xffffffff (lognot calculated))) - (setf (bzip2-state-calculated-block-crc state) calculated) - (unless (= calculated stored) - (error 'checksum-mismatch - :stored stored - :computed calculated - :kind :crc32)) - (setf (bzip2-state-calculated-combined-crc state) - (logand #xffffffff - (logior (ash (bzip2-state-calculated-combined-crc state) 1) - (ash (bzip2-state-calculated-combined-crc state) -31)))) - (setf (bzip2-state-calculated-combined-crc state) - (logand #xffffffff - (logxor (bzip2-state-calculated-combined-crc state) - calculated))) - (transition-to bzip2-block-header1)))) - - (bzip2-end-header2 (state) - (declare (type bzip2-state state)) - (let ((byte (ensure-and-read-bits 8 state))) - (if (= byte #x72) - (transition-to bzip2-end-header3) - (error 'invalid-bzip2-data)))) - - (bzip2-end-header3 (state) - (declare (type bzip2-state state)) - (let ((byte (ensure-and-read-bits 8 state))) - (if (= byte #x45) - (transition-to bzip2-end-header4) - (error 'invalid-bzip2-data)))) - - (bzip2-end-header4 (state) - (declare (type bzip2-state state)) - (let ((byte (ensure-and-read-bits 8 state))) - (if (= byte #x38) - (transition-to bzip2-end-header5) - (error 'invalid-bzip2-data)))) - - (bzip2-end-header5 (state) - (declare (type bzip2-state state)) - (let ((byte (ensure-and-read-bits 8 state))) - (if (= byte #x50) - (transition-to bzip2-end-header6) - (error 'invalid-bzip2-data)))) - - (bzip2-end-header6 (state) - (declare (type bzip2-state state)) - (let ((byte (ensure-and-read-bits 8 state))) - (unless (= byte #x90) - (error 'invalid-bzip2-data)) - (setf (bzip2-state-stored-combined-crc state) 0) - (transition-to bzip2-stored-combined-crc32-1))) - - (bzip2-stored-combined-crc32-1 (state) - (declare (type bzip2-state state)) - (setf (bzip2-state-stored-combined-crc state) - (ensure-and-read-bits 8 state)) - (transition-to bzip2-stored-combined-crc32-2)) - - (bzip2-stored-combined-crc32-2 (state) - (declare (type bzip2-state state)) - (let ((byte (ensure-and-read-bits 8 state))) + (bzip2-output (state) + (declare (type bzip2-state state)) + (let ((corruptp (undo-rle-obuf-to-output state))) + (when corruptp + (error 'invalid-bzip2-data)) + (unless (and (= (bzip2-state-n-blocks-used state) + (1+ (bzip2-state-nblock state))) + (zerop (bzip2-state-out-len state))) + (throw 'bzip2-done :ok)) + (let ((stored (bzip2-state-stored-block-crc state)) + (calculated (bzip2-state-calculated-block-crc state))) + (setf calculated (logand #xffffffff (lognot calculated))) + (setf (bzip2-state-calculated-block-crc state) calculated) + (unless (= calculated stored) + (error 'checksum-mismatch + :stored stored + :computed calculated + :kind :crc32)) + (setf (bzip2-state-calculated-combined-crc state) + (logand #xffffffff + (logior (ash (bzip2-state-calculated-combined-crc state) 1) + (ash (bzip2-state-calculated-combined-crc state) -31)))) + (setf (bzip2-state-calculated-combined-crc state) + (logand #xffffffff + (logxor (bzip2-state-calculated-combined-crc state) + calculated))) + (transition-to bzip2-block-header1)))) + + (bzip2-end-header2 (state) + (declare (type bzip2-state state)) + (let ((byte (ensure-and-read-bits 8 state))) + (if (= byte #x72) + (transition-to bzip2-end-header3) + (error 'invalid-bzip2-data)))) + + (bzip2-end-header3 (state) + (declare (type bzip2-state state)) + (let ((byte (ensure-and-read-bits 8 state))) + (if (= byte #x45) + (transition-to bzip2-end-header4) + (error 'invalid-bzip2-data)))) + + (bzip2-end-header4 (state) + (declare (type bzip2-state state)) + (let ((byte (ensure-and-read-bits 8 state))) + (if (= byte #x38) + (transition-to bzip2-end-header5) + (error 'invalid-bzip2-data)))) + + (bzip2-end-header5 (state) + (declare (type bzip2-state state)) + (let ((byte (ensure-and-read-bits 8 state))) + (if (= byte #x50) + (transition-to bzip2-end-header6) + (error 'invalid-bzip2-data)))) + + (bzip2-end-header6 (state) + (declare (type bzip2-state state)) + (let ((byte (ensure-and-read-bits 8 state))) + (unless (= byte #x90) + (error 'invalid-bzip2-data)) + (setf (bzip2-state-stored-combined-crc state) 0) + (transition-to bzip2-stored-combined-crc32-1))) + + (bzip2-stored-combined-crc32-1 (state) + (declare (type bzip2-state state)) (setf (bzip2-state-stored-combined-crc state) - (logand #xffffffff - (logior (ash (bzip2-state-stored-combined-crc state) 8) - byte))) - (transition-to bzip2-stored-combined-crc32-3))) - - (bzip2-stored-combined-crc32-3 (state) - (declare (type bzip2-state state)) - (let ((byte (ensure-and-read-bits 8 state))) - (setf (bzip2-state-stored-combined-crc state) - (logand #xffffffff - (logior (ash (bzip2-state-stored-combined-crc state) 8) - byte))) - (transition-to bzip2-stored-combined-crc32-4))) + (ensure-and-read-bits 8 state)) + (transition-to bzip2-stored-combined-crc32-2)) - (bzip2-stored-combined-crc32-4 (state) - (declare (type bzip2-state state)) - (let ((byte (ensure-and-read-bits 8 state))) - (setf (bzip2-state-stored-combined-crc state) - (logand #xffffffff - (logior (ash (bzip2-state-stored-combined-crc state) 8) - byte))) - (unless (= (bzip2-state-stored-combined-crc state) - (bzip2-state-calculated-combined-crc state)) - (error 'checksum-mismatch - :stored (bzip2-state-stored-combined-crc state) - :computed (bzip2-state-calculated-combined-crc state) - :kind :crc32)) - (setf (bzip2-state-done state) t) - (transition-to bzip2-done))) - - (bzip2-done (state) - (declare (ignore state)) - (throw 'bzip2-done t)) - ) - (unless (bzip2-state-state state) - (setf (bzip2-state-state state) #'bzip2-header)) - (funcall (the function (bzip2-state-state state)) state))) + (bzip2-stored-combined-crc32-2 (state) + (declare (type bzip2-state state)) + (let ((byte (ensure-and-read-bits 8 state))) + (setf (bzip2-state-stored-combined-crc state) + (logand #xffffffff + (logior (ash (bzip2-state-stored-combined-crc state) 8) + byte))) + (transition-to bzip2-stored-combined-crc32-3))) + + (bzip2-stored-combined-crc32-3 (state) + (declare (type bzip2-state state)) + (let ((byte (ensure-and-read-bits 8 state))) + (setf (bzip2-state-stored-combined-crc state) + (logand #xffffffff + (logior (ash (bzip2-state-stored-combined-crc state) 8) + byte))) + (transition-to bzip2-stored-combined-crc32-4))) + + (bzip2-stored-combined-crc32-4 (state) + (declare (type bzip2-state state)) + (let ((byte (ensure-and-read-bits 8 state))) + (setf (bzip2-state-stored-combined-crc state) + (logand #xffffffff + (logior (ash (bzip2-state-stored-combined-crc state) 8) + byte))) + (unless (= (bzip2-state-stored-combined-crc state) + (bzip2-state-calculated-combined-crc state)) + (error 'checksum-mismatch + :stored (bzip2-state-stored-combined-crc state) + :computed (bzip2-state-calculated-combined-crc state) + :kind :crc32)) + (setf (bzip2-state-done state) t) + (transition-to bzip2-done))) + + (bzip2-done (state) + (declare (ignore state)) + (throw 'bzip2-done t)) + ) + (unless (bzip2-state-state state) + (setf (bzip2-state-state state) #'bzip2-header)) + (funcall (the function (bzip2-state-state state)) state)))) (defun %bzip2-decompress (state input output &key (input-start 0) input-end (output-start 0) output-end) (declare (type bzip2-state state)) (let* ((input-end (or input-end (length input))) (output-end (or output-end (length output)))) (setf (bzip2-state-input state) input (bzip2-state-input-start state) input-start (bzip2-state-input-index state) input-start (bzip2-state-input-end state) input-end (bzip2-state-output state) output (bzip2-state-output-start state) output-start (bzip2-state-output-index state) output-start (bzip2-state-output-end state) output-end) (catch 'bzip2-done (%bzip2-state-machine state)) (values (- (bzip2-state-input-index state) input-start) (- (bzip2-state-output-index state) output-start)))) (defun make-bzip2-state () (let ((state (%make-bzip2-state))) (setf (dstate-checksum state) (make-crc32) (dstate-update-checksum state) #'update-crc32) state)) diff --git a/inflate.lisp b/inflate.lisp index b313602..ffa286f 100644 --- a/inflate.lisp +++ b/inflate.lisp @@ -1,594 +1,595 @@ (in-package :chipz) (defun update-window (state) (declare (type inflate-state state)) (let* ((output (inflate-state-output state)) (start (inflate-state-output-start state)) (index (inflate-state-output-index state)) (n-bytes-to-copy (- index start)) (window (inflate-state-window state)) (window-index (inflate-state-window-index state))) (cond ((>= n-bytes-to-copy (length window)) ;; can "flush" the window (setf (inflate-state-window-index state) 0) (replace window output :start2 (- index (length window)) :end2 index)) (t (let ((window-space (- (length window) window-index))) (cond ((> n-bytes-to-copy window-space) (replace window output :start1 window-index :start2 start :end2 index) (replace window output :start2 (+ start window-space) :end2 index) (setf (inflate-state-window-index state) (- n-bytes-to-copy window-space))) (t (replace window output :start1 window-index :start2 start :end2 index) (setf (inflate-state-window-index state) (mod (+ window-index n-bytes-to-copy) (length window)))))))))) ;;; This is used behind-the-scenes to do efficient buffer->buffer ;;; decompression. Everything user-visible that's related to ;;; decompression ultimately comes down to this function. (defun %inflate (state input output &key (input-start 0) input-end (output-start 0) output-end) "Decompresses data in INPUT between INPUT-START and INPUT-END and places the result in OUTPUT between OUTPUT-START and OUTPUT-END. -START and -END arguments follow the convention of the sequence functions. Returns the number of bytes pulled from the input and the number of bytes written to the output." (declare (type inflate-state state)) (let* ((input-end (or input-end (length input))) (output-end (or output-end (length output)))) (setf (inflate-state-input state) input (inflate-state-input-start state) input-start (inflate-state-input-index state) input-start (inflate-state-input-end state) input-end (inflate-state-output state) output (inflate-state-output-start state) output-start (inflate-state-output-index state) output-start (inflate-state-output-end state) output-end) (catch 'inflate-done (%inflate-state-machine state)) (update-window state) (when (dstate-update-checksum state) (funcall (dstate-update-checksum state) (dstate-checksum state) output output-start (inflate-state-output-index state))) (values (- (inflate-state-input-index state) input-start) (- (inflate-state-output-index state) output-start)))) (defun record-code-length (state value) (setf (aref (inflate-state-code-lengths state) (aref *code-length-code-order* (inflate-state-n-values-read state))) value) (incf (inflate-state-n-values-read state))) ;;; internal inflate function (defun %inflate-state-machine (state) (declare (type inflate-state state)) - ;; The reasoning behind this monstrosity is that we were using - ;; SYMBOL-FUNCTION to drive a nice elegant state machine...except that - ;; SYMBOL-FUNCTION is a horrible thing to call in inner loops. So we - ;; changed to this, which avoids the function lookup overhead. - (labels ( - (read-bits (n state) - (declare (type (integer 0 32) n)) - (declare (type inflate-state state)) - (prog1 (ldb (byte n 0) (inflate-state-bits state)) - (setf (inflate-state-bits state) - (ash (inflate-state-bits state) (- n))) - (decf (inflate-state-n-bits state) n))) - - (ensure-bits (n state) - (declare (type (integer 0 32) n)) - (declare (type inflate-state state)) - (let ((bits (inflate-state-bits state)) - (n-bits (inflate-state-n-bits state)) - (input-index (inflate-state-input-index state))) - (declare (type (unsigned-byte 32) bits)) - (loop while (< n-bits n) - when (>= input-index (inflate-state-input-end state)) - do (progn - (setf (inflate-state-bits state) bits - (inflate-state-n-bits state) n-bits - (inflate-state-input-index state) input-index) - (throw 'inflate-done nil)) - do (let ((byte (aref (inflate-state-input state) input-index))) - (declare (type (unsigned-byte 8) byte)) - (setf bits - (logand #xffffffff (logior (ash byte n-bits) bits))) - (incf n-bits 8) - (incf input-index)) - finally (setf (inflate-state-bits state) bits - (inflate-state-n-bits state) n-bits - (inflate-state-input-index state) input-index)))) - - (ensure-and-read-bits (n state) - (ensure-bits n state) - (read-bits n state)) - - (align-bits-bytewise (state) - (declare (type inflate-state state)) - (let ((n-bits (inflate-state-n-bits state))) - (decf (inflate-state-n-bits state) (rem n-bits 8)) - (setf (inflate-state-bits state) - (ash (inflate-state-bits state) - (- (rem n-bits 8)))) - (values))) - - (decode-value (table state) - (declare (type huffman-decode-table table)) - (declare (type inflate-state state)) - (declare (optimize (speed 3))) - (ensure-bits (hdt-bits table) state) - (let ((bits (inflate-state-bits state))) - (declare (type (unsigned-byte 32) bits)) - (do ((counts (hdt-counts table)) - (len 1 (1+ len)) - (first 0 (probably-the-fixnum (ash first 1))) - (code 0 (probably-the-fixnum (ash code 1)))) - ((>= len +max-code-length+) nil) - (declare (type (and fixnum (integer 0 *)) first code)) - ;; We would normally do this with READ-BITS, but DECODE-VALUE - ;; is a hotspot in profiles along with this would-be call to - ;; READ-BITS, so we inline it all here. - (setf code (logior code (logand bits 1)) - bits (ash bits -1)) - (let ((count (aref counts len))) - (when (< (- code count) first) - (setf (inflate-state-bits state) bits) - (decf (inflate-state-n-bits state) len) - (return-from decode-value (aref (hdt-symbols table) - (probably-the-fixnum - (+ (aref (hdt-offsets table) (1- len)) - (- code first)))))) - (setf first - (probably-the-fixnum (+ first count))))))) - - (read-dynamic-table (state decoder n-values) - (declare (type inflate-state state)) - (loop with lengths = (inflate-state-code-lengths state) - while (< (inflate-state-n-values-read state) n-values) - do (ensure-bits (+ (hdt-bits decoder) 7) state) - (let ((value (decode-value decoder state))) - (cond - ((< value 16) - (setf (aref lengths (inflate-state-n-values-read state)) value) - (incf (inflate-state-n-values-read state))) - (t - (let ((len 0) (sym 0)) - (cond - ((= value 16) - (setf sym (aref lengths (1- (inflate-state-n-values-read state)))) - (setf len (+ 3 (read-bits 2 state)))) - ((= value 17) - (setf len (+ 3 (read-bits 3 state)))) - ((= value 18) - (setf len (+ 11 (read-bits 7 state))))) - (fill lengths sym :start (inflate-state-n-values-read state) - :end (+ (inflate-state-n-values-read state) len)) - (incf (inflate-state-n-values-read state) len))))) - finally (progn - (assert (= n-values (inflate-state-n-values-read state))) - (return (construct-huffman-decode-table lengths n-values))))) - - ;; Basic starter functions. - (done (state) - (declare (ignore state)) - (throw 'inflate-done t)) - - (block-type (state) - (cond - ((inflate-state-final-block-p state) - (align-bits-bytewise state) - (setf (inflate-state-state state) - (ecase (inflate-state-data-format state) - (deflate - (setf (inflate-state-done state) t) - #'done) - (zlib #'check-zlib-adler32) - (gzip #'gzip-crc32)))) - (t - (ensure-bits 3 state) - (setf (inflate-state-final-block-p state) (= 1 (read-bits 1 state))) - (ecase (read-bits 2 state) - (#.+block-no-compress+ - (setf (inflate-state-state state) #'uncompressed-block) - (uncompressed-block state)) - (#.+block-fixed-codes+ - (setf (inflate-state-literal/length-table state) - *fixed-literal/length-table* - (inflate-state-distance-table state) - *fixed-distance-table* - (inflate-state-state state) #'literal/length) - (literal/length state)) - (#.+block-dynamic-codes+ - (setf (inflate-state-state state) #'dynamic-tables) - (dynamic-tables state)) - (#.+block-invalid+ - (error 'reserved-block-type-error)))))) + (declare (optimize (speed 3) (debug 1) (space 0) (compilation-speed 0))) + ;; Once upon a time, the individual functions in the LABELS below were + ;; separate functions. We drove the state machine of this function + ;; using LOOP and SYMBOL-FUNCTION. This scheme looked lovely...except + ;; that SYMBOL-FUNCTION is a horrible thing to call in inner loops, + ;; and we were calling it for just about every byte of input. + ;; + ;; So we switched to this huge LABELS. Each function then stored a + ;; reference to its next state in INFLATE-STATE-STATE before jumping + ;; to the next function. Some compilers were even able to optimize + ;; the call into a fallthru, which provides a nice approximation of a + ;; C switch statement. That was fine and dandy...except that the jump + ;; is a tail call, Common Lisp is not Scheme, and some implementations + ;; do not optimize tail calls. This combination led to stack + ;; overflows if you handed a large input buffer to this function. + ;; + ;; So we provide alternatives now through the TRANSITION-TO macro. On + ;; implementations we're sure we can trust to DTRT, we keep the second + ;; scheme above. On other implementations, we use a variant of the + ;; first scheme we tried, which is to simply store the next state's + ;; function in INFLATE-STATE-STATE and return. This at least avoids + ;; SYMBOL-FUNCTION and keeps constant stack space; the LOOP in the + ;; body of the LABELS (waaay down there) makes sure that we don't stop + ;; until we THROW. + (macrolet ((transition-to (next-state) + `(progn + (setf (inflate-state-state state) #',next-state) + #+(or sbcl cmu) + (,next-state state) + ;; Just fall through for other implementations and + ;; return normally. + ))) + (labels ( + (read-bits (n state) + (declare (type (integer 0 32) n)) + (declare (type inflate-state state)) + (prog1 (ldb (byte n 0) (inflate-state-bits state)) + (setf (inflate-state-bits state) + (ash (inflate-state-bits state) (- n))) + (decf (inflate-state-n-bits state) n))) + + (ensure-bits (n state) + (declare (type (integer 0 32) n)) + (declare (type inflate-state state)) + (let ((bits (inflate-state-bits state)) + (n-bits (inflate-state-n-bits state)) + (input-index (inflate-state-input-index state))) + (declare (type (unsigned-byte 32) bits)) + (loop while (< n-bits n) + when (>= input-index (inflate-state-input-end state)) + do (progn + (setf (inflate-state-bits state) bits + (inflate-state-n-bits state) n-bits + (inflate-state-input-index state) input-index) + (throw 'inflate-done nil)) + do (let ((byte (aref (inflate-state-input state) input-index))) + (declare (type (unsigned-byte 8) byte)) + (setf bits + (logand #xffffffff (logior (ash byte n-bits) bits))) + (incf n-bits 8) + (incf input-index)) + finally (setf (inflate-state-bits state) bits + (inflate-state-n-bits state) n-bits + (inflate-state-input-index state) input-index)))) + + (ensure-and-read-bits (n state) + (ensure-bits n state) + (read-bits n state)) + + (align-bits-bytewise (state) + (declare (type inflate-state state)) + (let ((n-bits (inflate-state-n-bits state))) + (decf (inflate-state-n-bits state) (rem n-bits 8)) + (setf (inflate-state-bits state) + (ash (inflate-state-bits state) + (- (rem n-bits 8)))) + (values))) + + (decode-value (table state) + (declare (type huffman-decode-table table)) + (declare (type inflate-state state)) + (declare (optimize (speed 3))) + (ensure-bits (hdt-bits table) state) + (let ((bits (inflate-state-bits state))) + (declare (type (unsigned-byte 32) bits)) + (do ((counts (hdt-counts table)) + (len 1 (1+ len)) + (first 0 (probably-the-fixnum (ash first 1))) + (code 0 (probably-the-fixnum (ash code 1)))) + ((>= len +max-code-length+) nil) + (declare (type (and fixnum (integer 0 *)) first code)) + ;; We would normally do this with READ-BITS, but DECODE-VALUE + ;; is a hotspot in profiles along with this would-be call to + ;; READ-BITS, so we inline it all here. + (setf code (logior code (logand bits 1)) + bits (ash bits -1)) + (let ((count (aref counts len))) + (when (< (- code count) first) + (setf (inflate-state-bits state) bits) + (decf (inflate-state-n-bits state) len) + (return-from decode-value (aref (hdt-symbols table) + (probably-the-fixnum + (+ (aref (hdt-offsets table) (1- len)) + (- code first)))))) + (setf first + (probably-the-fixnum (+ first count))))))) + + (read-dynamic-table (state decoder n-values) + (declare (type inflate-state state)) + (loop with lengths = (inflate-state-code-lengths state) + while (< (inflate-state-n-values-read state) n-values) + do (ensure-bits (+ (hdt-bits decoder) 7) state) + (let ((value (decode-value decoder state))) + (cond + ((< value 16) + (setf (aref lengths (inflate-state-n-values-read state)) value) + (incf (inflate-state-n-values-read state))) + (t + (let ((len 0) (sym 0)) + (cond + ((= value 16) + (setf sym (aref lengths (1- (inflate-state-n-values-read state)))) + (setf len (+ 3 (read-bits 2 state)))) + ((= value 17) + (setf len (+ 3 (read-bits 3 state)))) + ((= value 18) + (setf len (+ 11 (read-bits 7 state))))) + (fill lengths sym :start (inflate-state-n-values-read state) + :end (+ (inflate-state-n-values-read state) len)) + (incf (inflate-state-n-values-read state) len))))) + finally (progn + (assert (= n-values (inflate-state-n-values-read state))) + (return (construct-huffman-decode-table lengths n-values))))) + + ;; Basic starter functions. + (done (state) + (declare (ignore state)) + (throw 'inflate-done t)) + + (block-type (state) + (cond + ((inflate-state-final-block-p state) + (align-bits-bytewise state) + (setf (inflate-state-state state) + (ecase (inflate-state-data-format state) + (deflate + (setf (inflate-state-done state) t) + #'done) + (zlib #'check-zlib-adler32) + (gzip #'gzip-crc32)))) + (t + (ensure-bits 3 state) + (setf (inflate-state-final-block-p state) (= 1 (read-bits 1 state))) + (ecase (read-bits 2 state) + (#.+block-no-compress+ + (transition-to uncompressed-block)) + (#.+block-fixed-codes+ + (setf (inflate-state-literal/length-table state) + *fixed-literal/length-table* + (inflate-state-distance-table state) + *fixed-distance-table*) + (transition-to literal/length)) + (#.+block-dynamic-codes+ + (transition-to dynamic-tables)) + (#.+block-invalid+ + (error 'reserved-block-type-error)))))) ;;; processing uncompressed blocks - (uncompressed-block (state) - (align-bits-bytewise state) - (let* ((len (ensure-and-read-bits 16 state)) - (nlen (ensure-and-read-bits 16 state))) - (unless (zerop (logand len nlen)) - ;; Apparently Adobe's PDF generator(s) get this wrong, so let the - ;; user continue on if they choose to do so. - (cerror "Use the invalid stored block length." - 'invalid-stored-block-length-error)) - (setf (inflate-state-length state) len - (inflate-state-state state) #'copy-bytes))) - - (copy-bytes (state) - (declare (type inflate-state state)) - (if (zerop (inflate-state-length state)) - (setf (inflate-state-state state) #'block-type) - (let ((n-copied-bytes (min (inflate-state-length state) - (- (inflate-state-input-end state) - (inflate-state-input-index state)) - (- (inflate-state-output-end state) - (inflate-state-output-index state))))) - (cond - ((zerop n-copied-bytes) (throw 'inflate-done nil)) - (t - (replace (inflate-state-output state) - (inflate-state-input state) - :start1 (inflate-state-output-index state) - :end1 (+ (inflate-state-output-index state) - n-copied-bytes) - :start2 (inflate-state-input-index state) - :end2 (+ (inflate-state-input-index state) - n-copied-bytes)) - (incf (inflate-state-input-index state) n-copied-bytes) - (incf (inflate-state-output-index state) n-copied-bytes) - (decf (inflate-state-length state) n-copied-bytes))))) - (values)) + (uncompressed-block (state) + (align-bits-bytewise state) + (let* ((len (ensure-and-read-bits 16 state)) + (nlen (ensure-and-read-bits 16 state))) + (unless (zerop (logand len nlen)) + ;; Apparently Adobe's PDF generator(s) get this wrong, so let the + ;; user continue on if they choose to do so. + (cerror "Use the invalid stored block length." + 'invalid-stored-block-length-error)) + (setf (inflate-state-length state) len) + (transition-to copy-bytes))) + + (copy-bytes (state) + (declare (type inflate-state state)) + (if (zerop (inflate-state-length state)) + (setf (inflate-state-state state) #'block-type) + (let ((n-copied-bytes (min (inflate-state-length state) + (- (inflate-state-input-end state) + (inflate-state-input-index state)) + (- (inflate-state-output-end state) + (inflate-state-output-index state))))) + (cond + ((zerop n-copied-bytes) (throw 'inflate-done nil)) + (t + (replace (inflate-state-output state) + (inflate-state-input state) + :start1 (inflate-state-output-index state) + :end1 (+ (inflate-state-output-index state) + n-copied-bytes) + :start2 (inflate-state-input-index state) + :end2 (+ (inflate-state-input-index state) + n-copied-bytes)) + (incf (inflate-state-input-index state) n-copied-bytes) + (incf (inflate-state-output-index state) n-copied-bytes) + (decf (inflate-state-length state) n-copied-bytes))))) + (values)) ;;; dynamic block compression tables - (dynamic-tables (state) - (declare (type inflate-state state)) - (ensure-bits 14 state) - (setf (inflate-state-n-length-codes state) (+ (read-bits 5 state) 257) - (inflate-state-n-distance-codes state) (+ (read-bits 5 state) 1) - (inflate-state-n-codes state) (+ (read-bits 4 state) 4) - (inflate-state-n-values-read state) 0 - (inflate-state-state state) #'dynamic-code-lengths) - (dynamic-code-lengths state)) - - (dynamic-code-lengths (state) - (declare (type inflate-state state)) - (loop while (< (inflate-state-n-values-read state) - (inflate-state-n-codes state)) - do (ensure-bits 3 state) - (record-code-length state (read-bits 3 state))) - (loop while (< (inflate-state-n-values-read state) +max-n-code-lengths+) - do (record-code-length state 0)) - (setf (inflate-state-codes-table state) - (construct-huffman-decode-table (inflate-state-code-lengths state) - +max-n-code-lengths+) - (inflate-state-n-values-read state) 0 - (inflate-state-state state) #'dynamic-literal/length-table) - (dynamic-literal/length-table state)) - - (dynamic-literal/length-table (state) - (declare (type inflate-state state)) - (setf (inflate-state-literal/length-table state) - (read-dynamic-table state (inflate-state-codes-table state) - (inflate-state-n-length-codes state)) - (inflate-state-n-values-read state) 0 - (inflate-state-state state) #'dynamic-distance-table) - (dynamic-distance-table state)) - - (dynamic-distance-table (state) - (declare (type inflate-state state)) - (setf (inflate-state-distance-table state) - (read-dynamic-table state (inflate-state-codes-table state) - (inflate-state-n-distance-codes state)) - (inflate-state-state state) #'literal/length) - (literal/length state)) + (dynamic-tables (state) + (declare (type inflate-state state)) + (ensure-bits 14 state) + (setf (inflate-state-n-length-codes state) (+ (read-bits 5 state) 257) + (inflate-state-n-distance-codes state) (+ (read-bits 5 state) 1) + (inflate-state-n-codes state) (+ (read-bits 4 state) 4) + (inflate-state-n-values-read state) 0) + (transition-to dynamic-code-lengths)) + + (dynamic-code-lengths (state) + (declare (type inflate-state state)) + (loop while (< (inflate-state-n-values-read state) + (inflate-state-n-codes state)) + do (ensure-bits 3 state) + (record-code-length state (read-bits 3 state))) + (loop while (< (inflate-state-n-values-read state) +max-n-code-lengths+) + do (record-code-length state 0)) + (setf (inflate-state-codes-table state) + (construct-huffman-decode-table (inflate-state-code-lengths state) + +max-n-code-lengths+) + (inflate-state-n-values-read state) 0) + (transition-to dynamic-literal/length-table)) + + (dynamic-literal/length-table (state) + (declare (type inflate-state state)) + (setf (inflate-state-literal/length-table state) + (read-dynamic-table state (inflate-state-codes-table state) + (inflate-state-n-length-codes state)) + (inflate-state-n-values-read state) 0) + (transition-to dynamic-distance-table)) + + (dynamic-distance-table (state) + (declare (type inflate-state state)) + (setf (inflate-state-distance-table state) + (read-dynamic-table state (inflate-state-codes-table state) + (inflate-state-n-distance-codes state))) + (transition-to literal/length)) ;;; normal operation on compressed blocks - (literal/length (state) - (declare (type inflate-state state)) - (let ((value (decode-value (inflate-state-literal/length-table state) - state))) - (declare (type (integer 0 288) value)) + (literal/length (state) + (declare (type inflate-state state)) + (let ((value (decode-value (inflate-state-literal/length-table state) + state))) + (declare (type (integer 0 288) value)) + (cond + ((< value 256) + (setf (inflate-state-length state) value) + (transition-to literal)) + ((> value 256) + (setf (inflate-state-length-code state) (- value 257)) + (transition-to length-code)) + (t #+nil (= value 256) + (transition-to block-type))))) + + (literal (state) + (declare (type inflate-state state)) (cond - ((< value 256) - (setf (inflate-state-length state) value - (inflate-state-state state) #'literal) - (literal state)) - ((> value 256) - (setf (inflate-state-length-code state) (- value 257) - (inflate-state-state state) #'length-code) - (length-code state)) - (t #+nil (= value 256) - (setf (inflate-state-state state) #'block-type) - (block-type state))))) - - (literal (state) - (declare (type inflate-state state)) - (cond - ((= (inflate-state-output-index state) - (inflate-state-output-end state)) (throw 'inflate-done nil)) - (t (setf (aref (inflate-state-output state) - (inflate-state-output-index state)) - (inflate-state-length state)) + ((= (inflate-state-output-index state) + (inflate-state-output-end state)) (throw 'inflate-done nil)) + (t (setf (aref (inflate-state-output state) + (inflate-state-output-index state)) + (inflate-state-length state)) (incf (inflate-state-output-index state)) - (setf (inflate-state-state state) #'literal/length) - (literal/length state)))) - - (length-code (state) - (declare (type inflate-state state)) - (let* ((length-code (inflate-state-length-code state)) - (length-extra (ensure-and-read-bits (n-length-extra-bits length-code) state))) - (setf (inflate-state-length state) - (+ (length-base length-code) length-extra) - (inflate-state-state state) #'distance) - (distance state))) - - (distance (state) - (declare (type inflate-state state)) - (let ((value (decode-value (inflate-state-distance-table state) - state))) - (setf (inflate-state-distance state) value - (inflate-state-state state) #'distance-extra) - (distance-extra state))) - - (distance-extra (state) - (declare (type inflate-state state)) - (let* ((bits (n-distance-extra-bits (inflate-state-distance state))) - (distance-extra (if (zerop bits) - 0 - (ensure-and-read-bits bits state)))) - (setf (inflate-state-distance state) - (+ (distance-base (inflate-state-distance state)) distance-extra) - (inflate-state-state state) #'copy-match) - (copy-match state))) - - (copy-match (state) - (declare (type inflate-state state)) - (let* ((distance (inflate-state-distance state)) - (length (inflate-state-length state)) - (start (inflate-state-output-start state)) - (index (inflate-state-output-index state)) - (end (inflate-state-output-end state)) - (window-index (inflate-state-window-index state)) - (n-bytes-to-copy (min length (- end index)))) - (when (= index end) - (throw 'inflate-done nil)) - (flet ((frob-by-copying-from (copy-source copy-index n-bytes-to-copy) - (declare (type (simple-array (unsigned-byte 8) (*)) copy-source)) - (decf (inflate-state-length state) n-bytes-to-copy) - (incf (inflate-state-output-index state) n-bytes-to-copy) - (loop with output = (inflate-state-output state) - for i from index below (the fixnum (+ index n-bytes-to-copy)) - for j from copy-index below (the fixnum (+ copy-index n-bytes-to-copy)) - do (setf (aref output i) (aref copy-source j))))) + (transition-to literal/length)))) + + (length-code (state) + (declare (type inflate-state state)) + (let* ((length-code (inflate-state-length-code state)) + (length-extra (ensure-and-read-bits (n-length-extra-bits length-code) state))) + (setf (inflate-state-length state) + (+ (length-base length-code) length-extra)) + (transition-to distance))) + + (distance (state) + (declare (type inflate-state state)) + (let ((value (decode-value (inflate-state-distance-table state) + state))) + (setf (inflate-state-distance state) value) + (transition-to distance-extra))) + + (distance-extra (state) + (declare (type inflate-state state)) + (let* ((bits (n-distance-extra-bits (inflate-state-distance state))) + (distance-extra (if (zerop bits) + 0 + (ensure-and-read-bits bits state)))) + (setf (inflate-state-distance state) + (+ (distance-base (inflate-state-distance state)) distance-extra)) + (transition-to copy-match))) + + (copy-match (state) + (declare (type inflate-state state)) + (let* ((distance (inflate-state-distance state)) + (length (inflate-state-length state)) + (start (inflate-state-output-start state)) + (index (inflate-state-output-index state)) + (end (inflate-state-output-end state)) + (window-index (inflate-state-window-index state)) + (n-bytes-to-copy (min length (- end index)))) + (when (= index end) + (throw 'inflate-done nil)) + (flet ((frob-by-copying-from (copy-source copy-index n-bytes-to-copy) + (declare (type (simple-array (unsigned-byte 8) (*)) copy-source)) + (decf (inflate-state-length state) n-bytes-to-copy) + (incf (inflate-state-output-index state) n-bytes-to-copy) + (loop with output = (inflate-state-output state) + for i from index below (the fixnum (+ index n-bytes-to-copy)) + for j from copy-index below (the fixnum (+ copy-index n-bytes-to-copy)) + do (setf (aref output i) (aref copy-source j))))) + (cond + ((<= distance (- index start)) + ;; we are within the output we have produced + (frob-by-copying-from (inflate-state-output state) + (- index distance) + n-bytes-to-copy)) + (t + (let ((copy-index (+ (- window-index distance) (- index start)))) + (cond + ((not (minusp copy-index)) + ;; we are within the non-wraparound portion of the window + ;; + ;; can only copy up to the window's index, though + (let ((n-bytes-to-copy (min n-bytes-to-copy (- window-index copy-index)))) + (frob-by-copying-from (inflate-state-window state) + copy-index + n-bytes-to-copy))) + (t + ;; we are within the wraparound portion of the window + (let* ((copy-index (+ copy-index + (length (inflate-state-window state)))) + (n-bytes-to-copy (min n-bytes-to-copy + (- (length (inflate-state-window state)) + copy-index)))) + (frob-by-copying-from (inflate-state-window state) + copy-index + n-bytes-to-copy))))))) + (when (zerop (inflate-state-length state)) + (transition-to literal/length))))) + + ;; GZIP + (gzip-header-id (state) + (declare (type inflate-state state)) + (let ((header-field (ensure-and-read-bits 16 state))) + (unless (and (= (ldb (byte 8 0) header-field) #x1f) + (= (ldb (byte 8 8) header-field) #x8b)) + (error 'invalid-gzip-header-error)) + (transition-to gzip-cm))) + + (gzip-cm (state) + (declare (type inflate-state state)) + (let ((cm-byte (ensure-and-read-bits 8 state))) + (setf (inflate-state-header state) + (make-instance 'gzip-header :compression-method cm-byte)) + (transition-to gzip-flags))) + + (gzip-flags (state) + (declare (type inflate-state state)) + (let ((flags-byte (ensure-and-read-bits 8 state))) + (setf (flags (inflate-state-header state)) flags-byte) + (transition-to gzip-mtime))) + + (gzip-mtime (state) + (declare (type inflate-state state)) + (let ((mtime (ensure-and-read-bits 32 state))) + (setf (mtime (inflate-state-header state)) mtime) + (transition-to gzip-xfl))) + + (gzip-xfl (state) + (declare (type inflate-state state)) + (let ((xfl-byte (ensure-and-read-bits 8 state))) + (setf (extra-flags (inflate-state-header state)) xfl-byte) + (transition-to gzip-os))) + + (gzip-os (state) + (declare (type inflate-state state)) + (let ((os-byte (ensure-and-read-bits 8 state))) + (setf (os (inflate-state-header state)) os-byte) + (transition-to gzip-xlen-len))) + + (gzip-xlen-len (state) + (declare (type inflate-state state)) + (let ((flags (flags (inflate-state-header state)))) (cond - ((<= distance (- index start)) - ;; we are within the output we have produced - (frob-by-copying-from (inflate-state-output state) - (- index distance) - n-bytes-to-copy)) + ((logbitp +gzip-flag-extra+ flags) + (error "gzip extra field not supported yet")) (t - (let ((copy-index (+ (- window-index distance) (- index start)))) + (transition-to gzip-fname))))) + + (gzip-fname (state) + (declare (type inflate-state state)) + (process-gzip-zero-terminated-field state +gzip-flag-name+ + #'filename #'(setf filename) + #'gzip-fcomment)) + + (gzip-fcomment (state) + (declare (type inflate-state state)) + (process-gzip-zero-terminated-field state +gzip-flag-comment+ + #'comment #'(setf comment) + #'gzip-crc16)) + + (process-gzip-zero-terminated-field (state control-bit + slot set-slot + next-state) + (let ((header (inflate-state-header state))) + (cond + ((logbitp control-bit (flags header)) + (let ((byte (ensure-and-read-bits 8 state))) (cond - ((not (minusp copy-index)) - ;; we are within the non-wraparound portion of the window - ;; - ;; can only copy up to the window's index, though - (let ((n-bytes-to-copy (min n-bytes-to-copy (- window-index copy-index)))) - (frob-by-copying-from (inflate-state-window state) - copy-index - n-bytes-to-copy))) + ((zerop byte) + ;; the end, convert to sane form + (funcall set-slot + (coerce (funcall slot header) + '(vector (unsigned-byte 8))) + header) + (setf (inflate-state-state state) next-state)) (t - ;; we are within the wraparound portion of the window - (let* ((copy-index (+ copy-index - (length (inflate-state-window state)))) - (n-bytes-to-copy (min n-bytes-to-copy - (- (length (inflate-state-window state)) - copy-index)))) - (frob-by-copying-from (inflate-state-window state) - copy-index - n-bytes-to-copy))))))) - (when (zerop (inflate-state-length state)) - (setf (inflate-state-state state) #'literal/length) - (literal/length state))))) - - ;; GZIP - (gzip-header-id (state) - (declare (type inflate-state state)) - (let ((header-field (ensure-and-read-bits 16 state))) - (unless (and (= (ldb (byte 8 0) header-field) #x1f) - (= (ldb (byte 8 8) header-field) #x8b)) - (error 'invalid-gzip-header-error)) - (setf (inflate-state-state state) #'gzip-cm) - (gzip-cm state))) - - (gzip-cm (state) - (declare (type inflate-state state)) - (let ((cm-byte (ensure-and-read-bits 8 state))) - (setf (inflate-state-header state) - (make-instance 'gzip-header :compression-method cm-byte) - (inflate-state-state state) #'gzip-flags) - (gzip-flags state))) - - (gzip-flags (state) - (declare (type inflate-state state)) - (let ((flags-byte (ensure-and-read-bits 8 state))) - (setf (flags (inflate-state-header state)) flags-byte - (inflate-state-state state) #'gzip-mtime) - (gzip-mtime state))) - - (gzip-mtime (state) - (declare (type inflate-state state)) - (let ((mtime (ensure-and-read-bits 32 state))) - (setf (mtime (inflate-state-header state)) mtime - (inflate-state-state state) #'gzip-xfl) - (gzip-xfl state))) - - (gzip-xfl (state) - (declare (type inflate-state state)) - (let ((xfl-byte (ensure-and-read-bits 8 state))) - (setf (extra-flags (inflate-state-header state)) xfl-byte - (inflate-state-state state) #'gzip-os) - (gzip-os state))) - - (gzip-os (state) - (declare (type inflate-state state)) - (let ((os-byte (ensure-and-read-bits 8 state))) - (setf (os (inflate-state-header state)) os-byte - (inflate-state-state state) #'gzip-xlen-len) - (gzip-xlen-len state))) - - (gzip-xlen-len (state) - (declare (type inflate-state state)) - (let ((flags (flags (inflate-state-header state)))) - (cond - ((logbitp +gzip-flag-extra+ flags) - (error "gzip extra field not supported yet")) - (t - (setf (inflate-state-state state) #'gzip-fname) - (gzip-fname state))))) - - (gzip-fname (state) - (declare (type inflate-state state)) - (process-gzip-zero-terminated-field state +gzip-flag-name+ - #'filename #'(setf filename) - #'gzip-fcomment)) - - (gzip-fcomment (state) - (declare (type inflate-state state)) - (process-gzip-zero-terminated-field state +gzip-flag-comment+ - #'comment #'(setf comment) - #'gzip-crc16)) - - (process-gzip-zero-terminated-field (state control-bit - slot set-slot - next-state) - (let ((header (inflate-state-header state))) - (cond - ((logbitp control-bit (flags header)) - (let ((byte (ensure-and-read-bits 8 state))) - (cond - ((zerop byte) - ;; the end, convert to sane form - (funcall set-slot - (coerce (funcall slot header) - '(vector (unsigned-byte 8))) - header) - (setf (inflate-state-state state) next-state)) - (t - ;; wish we could use PUSH here - (funcall set-slot - (cons byte (funcall slot header)) - header))))) - (t - (setf (inflate-state-state state) next-state))) - (values))) - - (gzip-crc16 (state) - (declare (type inflate-state state)) - (let ((header (inflate-state-header state))) - (when (logbitp +gzip-flag-crc+ (flags header)) - (let ((crc16 (ensure-and-read-bits 16 state))) - ;; FIXME: would be good to perform integrity checking here - (declare (ignore crc16)))) - (setf (inflate-state-state state) #'block-type) - (block-type state))) - - (gzip-crc32 (state) - (declare (type inflate-state state)) - (let ((stored (ensure-and-read-bits 32 state)) - (crc32 (copy-crc32 (inflate-state-checksum state)))) - (update-crc32 crc32 - (inflate-state-output state) - (inflate-state-output-start state) - (inflate-state-output-index state)) - (unless (= stored (produce-crc32 crc32)) - (error 'invalid-checksum-error - :stored stored - :computed (produce-crc32 crc32) - :kind :crc32)) - (setf (inflate-state-state state) #'gzip-isize) - (gzip-isize state))) - - (gzip-isize (state) - (declare (type inflate-state state)) - (let ((isize (ensure-and-read-bits 32 state))) - (declare (ignore isize)) - (setf (inflate-state-state state) #'done) - (setf (inflate-state-done state) t))) - - ;; ZLIB - (zlib-cmf (state) - (declare (type inflate-state state)) - (let ((cmf-byte (ensure-and-read-bits 8 state))) - (setf (inflate-state-header state) - (make-instance 'zlib-header :cmf cmf-byte) - (inflate-state-state state) #'zlib-flags) - (zlib-flags state))) - - (zlib-flags (state) - (declare (type inflate-state state)) - (let ((flags-byte (ensure-and-read-bits 8 state)) - (header (inflate-state-header state))) - ;; check - (unless (zerop (mod (+ (* (cmf header) 256) flags-byte) 31)) - (error 'invalid-zlib-header-error)) - (setf (flags header) flags-byte - (inflate-state-state state) #'zlib-fdict) - (zlib-fdict state))) - - (zlib-fdict (state) - (declare (type inflate-state state)) - (let* ((header (inflate-state-header state)) - (flags-byte (flags header))) - (when (logbitp +zlib-flag-fdict+ flags-byte) - (let ((fdict (ensure-and-read-bits 32 state))) - (setf (fdict header) fdict))) - (setf (inflate-state-state state) #'block-type) - (block-type state))) - - (check-zlib-adler32 (state) - (declare (type inflate-state state)) - (let ((stored (let ((x (ensure-and-read-bits 32 state))) - (logior (ash (ldb (byte 8 0) x) 24) - (ash (ldb (byte 8 8) x) 16) - (ash (ldb (byte 8 16) x) 8) - (ldb (byte 8 24) x)))) - (adler32 (copy-adler32 (inflate-state-checksum state)))) - (update-adler32 adler32 + ;; wish we could use PUSH here + (funcall set-slot + (cons byte (funcall slot header)) + header))))) + (t + (setf (inflate-state-state state) next-state))) + (values))) + + (gzip-crc16 (state) + (declare (type inflate-state state)) + (let ((header (inflate-state-header state))) + (when (logbitp +gzip-flag-crc+ (flags header)) + (let ((crc16 (ensure-and-read-bits 16 state))) + ;; FIXME: would be good to perform integrity checking here + (declare (ignore crc16)))) + (transition-to block-type))) + + (gzip-crc32 (state) + (declare (type inflate-state state)) + (let ((stored (ensure-and-read-bits 32 state)) + (crc32 (copy-crc32 (inflate-state-checksum state)))) + (update-crc32 crc32 (inflate-state-output state) (inflate-state-output-start state) (inflate-state-output-index state)) - (unless (= stored - (produce-adler32 adler32)) - (error 'invalid-checksum-error - :stored stored - :computed (produce-adler32 adler32) - :kind :adler32)) - (setf (inflate-state-done state) t - (inflate-state-state state) #'done))) - ) - (unless (inflate-state-state state) - (setf (inflate-state-state state) - (ecase (inflate-state-data-format state) - (deflate #'block-type) - (zlib #'zlib-cmf) - (gzip #'gzip-header-id)))) - (loop (funcall (inflate-state-state state) state)))) + (unless (= stored (produce-crc32 crc32)) + (error 'invalid-checksum-error + :stored stored + :computed (produce-crc32 crc32) + :kind :crc32)) + (transition-to gzip-isize))) + + (gzip-isize (state) + (declare (type inflate-state state)) + (let ((isize (ensure-and-read-bits 32 state))) + (declare (ignore isize)) + (setf (inflate-state-done state) t) + (transition-to done))) + + ;; ZLIB + (zlib-cmf (state) + (declare (type inflate-state state)) + (let ((cmf-byte (ensure-and-read-bits 8 state))) + (setf (inflate-state-header state) + (make-instance 'zlib-header :cmf cmf-byte)) + (transition-to zlib-flags))) + + (zlib-flags (state) + (declare (type inflate-state state)) + (let ((flags-byte (ensure-and-read-bits 8 state)) + (header (inflate-state-header state))) + ;; check + (unless (zerop (mod (+ (* (cmf header) 256) flags-byte) 31)) + (error 'invalid-zlib-header-error)) + (setf (flags header) flags-byte) + (transition-to zlib-fdict))) + + (zlib-fdict (state) + (declare (type inflate-state state)) + (let* ((header (inflate-state-header state)) + (flags-byte (flags header))) + (when (logbitp +zlib-flag-fdict+ flags-byte) + (let ((fdict (ensure-and-read-bits 32 state))) + (setf (fdict header) fdict))) + (transition-to block-type))) + + (check-zlib-adler32 (state) + (declare (type inflate-state state)) + (let ((stored (let ((x (ensure-and-read-bits 32 state))) + (logior (ash (ldb (byte 8 0) x) 24) + (ash (ldb (byte 8 8) x) 16) + (ash (ldb (byte 8 16) x) 8) + (ldb (byte 8 24) x)))) + (adler32 (copy-adler32 (inflate-state-checksum state)))) + (update-adler32 adler32 + (inflate-state-output state) + (inflate-state-output-start state) + (inflate-state-output-index state)) + (unless (= stored + (produce-adler32 adler32)) + (error 'invalid-checksum-error + :stored stored + :computed (produce-adler32 adler32) + :kind :adler32)) + (setf (inflate-state-done state) t) + (transition-to done))) + ) + (unless (inflate-state-state state) + (setf (inflate-state-state state) + (ecase (inflate-state-data-format state) + (deflate #'block-type) + (zlib #'zlib-cmf) + (gzip #'gzip-header-id)))) + (loop (funcall (inflate-state-state state) state)))))
froydnj/chipz
d5d41cc5f37666433dab39013525096c1a002521
remove &ALLOW-OTHER-KEYS from method lambda lists
diff --git a/decompress.lisp b/decompress.lisp index 387b637..9f0e6fa 100644 --- a/decompress.lisp +++ b/decompress.lisp @@ -1,189 +1,188 @@ (in-package :chipz) ;;; We provide several convenience functions for decompression: ;;; ;;; * decompress a buffer to a newly-consed buffer; ;;; * decompress a stream to a newly-consed buffer; ;;; * decompress a buffer to a user-specified buffer; ;;; * decompress a buffer to a stream; ;;; * decompress a stream to a stream. ;;; ;;; We do not provide stream->buffer decompression, as we have no way of ;;; knowing how much to read from the stream to fill the buffer, no way ;;; of determining what to do with possible state left in the ;;; INFLATE-STATE that we used, etc. Application-specific logic will ;;; have to handle those bits. (defgeneric decompress (output state input &key &allow-other-keys) (:method (output format input &rest keys) (%decompress output format input keys))) (defun %decompress (output format input keys) (let ((state (make-dstate format))) (multiple-value-prog1 (apply #'decompress output state input keys) (finish-dstate state)))) ;;; SUBSEQ is specified to always make a copy. But we don't want an ;;; exact copy of a freshly-consed vector; that'd be wasteful. (defun maybe-subseq (v end) (if (= end (length v)) v (subseq v 0 end))) (defun decompress-fun-for-state (state) (typecase state (inflate-state #'%inflate) (bzip2-state #'%bzip2-decompress))) (defun %decompress/null-vector (state input fun input-start input-end buffer-size) (declare (type function fun)) (loop with output = (make-array buffer-size :element-type '(unsigned-byte 8)) with output-start = 0 do (cond ((= output-start (length output)) ;; Reallocate the output buffer. (let ((new (make-array (* 2 (length output)) :element-type '(unsigned-byte 8)))) (setf output (replace new output)))) (t (multiple-value-bind (consumed produced) (funcall fun state input output :input-start input-start :input-end input-end :output-start output-start :output-end (length output)) (incf input-start consumed) (incf output-start produced) (when (or (dstate-done state) (and (or (>= input-start input-end) (zerop consumed)) (zerop produced))) (return-from %decompress/null-vector (maybe-subseq output output-start)))))))) (defmethod decompress ((output null) (state decompression-state) (input vector) - &key (input-start 0) input-end buffer-size - &allow-other-keys) + &key (input-start 0) input-end buffer-size) (%decompress/null-vector state input (decompress-fun-for-state state) input-start (or input-end (length input)) (or buffer-size +default-buffer-size+))) (defun %decompress/null-stream (state input fun buffer-size) (declare (type function fun)) (let ((input-buffer (make-array 8192 :element-type '(unsigned-byte 8)))) (declare (dynamic-extent input-buffer)) (loop with input-start = 0 with input-end = 0 with output = (make-array buffer-size :element-type '(unsigned-byte 8)) with output-start = 0 initially (setf input-end (read-sequence input-buffer input)) do (cond ((= output-start (length output)) ;; Reallocate the output buffer. (let ((new (make-array (* 2 (length output)) :element-type '(unsigned-byte 8)))) (setf output (replace new output)))) (t (multiple-value-bind (consumed produced) (funcall fun state input-buffer output :input-start input-start :input-end input-end :output-start output-start) (incf input-start consumed) (incf output-start produced) (let ((input-consumed-p (>= input-start input-end))) ;; Get more input if possible. (when input-consumed-p (setf input-start 0 input-end (read-sequence input-buffer input))) (when (or (dstate-done state) (and (or (and input-consumed-p (zerop input-end)) (zerop consumed)) (zerop produced))) (return-from %decompress/null-stream (maybe-subseq output output-start)))))))))) (defmethod decompress ((output null) (state decompression-state) (input stream) - &key buffer-size &allow-other-keys) + &key buffer-size) (%decompress/null-stream state input (decompress-fun-for-state state) (or buffer-size +default-buffer-size+))) (defun %decompress/vector-vector (output state input fun input-start input-end output-start output-end) (declare (type simple-octet-vector input output)) (declare (type function fun)) (loop with n-bytes-consumed = 0 and n-bytes-produced = 0 do (multiple-value-bind (consumed produced) (funcall fun state input output :input-start input-start :input-end input-end :output-start output-start :output-end output-end) (incf input-start consumed) (incf output-start produced) (incf n-bytes-consumed consumed) (incf n-bytes-produced produced) (when (and (or (>= input-start input-end) (zerop consumed)) (or (>= output-start output-end) (zerop produced))) (return-from %decompress/vector-vector (values n-bytes-consumed n-bytes-produced)))))) (defmethod decompress ((output vector) (state decompression-state) (input vector) &key (input-start 0) input-end - (output-start 0) output-end &allow-other-keys) + (output-start 0) output-end) (%decompress/vector-vector output state input (decompress-fun-for-state state) input-start (or input-end (length input)) output-start (or output-end (length output)))) (defun %decompress/stream-vector (output state input fun input-start input-end) (declare (type function fun)) (let ((buffer (make-array 8192 :element-type '(unsigned-byte 8)))) (declare (dynamic-extent buffer)) (loop (multiple-value-bind (consumed produced) (funcall fun state input buffer :input-start input-start :input-end input-end) (incf input-start consumed) (write-sequence buffer output :end produced) (when (or (dstate-done state) (and (or (>= input-start input-end) (zerop consumed)) (zerop produced))) (return-from %decompress/stream-vector output)))))) (defmethod decompress ((output stream) (state decompression-state) (input vector) - &key (input-start 0) input-end &allow-other-keys) + &key (input-start 0) input-end) (%decompress/stream-vector output state input (decompress-fun-for-state state) input-start (or input-end (length input)))) (defun %decompress/stream-stream (output state input fun) (declare (type function fun)) (let ((input-buffer (make-array 8192 :element-type '(unsigned-byte 8))) (output-buffer (make-array 8192 :element-type '(unsigned-byte 8)))) (declare (dynamic-extent input-buffer output-buffer)) (loop with input-start = 0 with input-end = 0 initially (setf input-end (read-sequence input-buffer input)) do (multiple-value-bind (consumed produced) (funcall fun state input-buffer output-buffer :input-start input-start :input-end input-end) (incf input-start consumed) (write-sequence output-buffer output :end produced) (let ((input-consumed-p (>= input-start input-end))) (when input-consumed-p (setf input-start 0 input-end (read-sequence input-buffer input))) (when (or (dstate-done state) (and (or (and input-consumed-p (zerop input-end)) (zerop consumed)) (zerop produced))) (return-from %decompress/stream-stream output))))))) (defmethod decompress ((output stream) (state decompression-state) (input stream) - &key &allow-other-keys) + &key) (%decompress/stream-stream output state input (decompress-fun-for-state state)))
froydnj/chipz
0ae865833a6acec0089fe71be81852bf092fe94b
reduce number of methods for DECOMPRESS
diff --git a/decompress.lisp b/decompress.lisp index 1fdcf87..387b637 100644 --- a/decompress.lisp +++ b/decompress.lisp @@ -1,205 +1,189 @@ (in-package :chipz) ;;; We provide several convenience functions for decompression: ;;; ;;; * decompress a buffer to a newly-consed buffer; ;;; * decompress a stream to a newly-consed buffer; ;;; * decompress a buffer to a user-specified buffer; ;;; * decompress a buffer to a stream; ;;; * decompress a stream to a stream. ;;; ;;; We do not provide stream->buffer decompression, as we have no way of ;;; knowing how much to read from the stream to fill the buffer, no way ;;; of determining what to do with possible state left in the ;;; INFLATE-STATE that we used, etc. Application-specific logic will ;;; have to handle those bits. (defgeneric decompress (output state input &key &allow-other-keys) (:method (output format input &rest keys) - (error 'invalid-format-error :format format)) - (:method (output (format (eql :deflate)) input &rest keys) - #1=(%decompress output format input keys)) - (:method (output (format (eql 'deflate)) input &rest keys) - #1#) - (:method (output (format (eql :zlib)) input &rest keys) - #1#) - (:method (output (format (eql 'zlib)) input &rest keys) - #1#) - (:method (output (format (eql :gzip)) input &rest keys) - #1#) - (:method (output (format (eql 'gzip)) input &rest keys) - #1#) - (:method (output (format (eql :bzip2)) input &rest keys) - #1#) - (:method (output (format (eql 'bzip2)) input &rest keys) - #1#)) + (%decompress output format input keys))) (defun %decompress (output format input keys) (let ((state (make-dstate format))) (multiple-value-prog1 (apply #'decompress output state input keys) (finish-dstate state)))) ;;; SUBSEQ is specified to always make a copy. But we don't want an ;;; exact copy of a freshly-consed vector; that'd be wasteful. (defun maybe-subseq (v end) (if (= end (length v)) v (subseq v 0 end))) (defun decompress-fun-for-state (state) (typecase state (inflate-state #'%inflate) (bzip2-state #'%bzip2-decompress))) (defun %decompress/null-vector (state input fun input-start input-end buffer-size) (declare (type function fun)) (loop with output = (make-array buffer-size :element-type '(unsigned-byte 8)) with output-start = 0 do (cond ((= output-start (length output)) ;; Reallocate the output buffer. (let ((new (make-array (* 2 (length output)) :element-type '(unsigned-byte 8)))) (setf output (replace new output)))) (t (multiple-value-bind (consumed produced) (funcall fun state input output :input-start input-start :input-end input-end :output-start output-start :output-end (length output)) (incf input-start consumed) (incf output-start produced) (when (or (dstate-done state) (and (or (>= input-start input-end) (zerop consumed)) (zerop produced))) (return-from %decompress/null-vector (maybe-subseq output output-start)))))))) (defmethod decompress ((output null) (state decompression-state) (input vector) &key (input-start 0) input-end buffer-size &allow-other-keys) (%decompress/null-vector state input (decompress-fun-for-state state) input-start (or input-end (length input)) (or buffer-size +default-buffer-size+))) (defun %decompress/null-stream (state input fun buffer-size) (declare (type function fun)) (let ((input-buffer (make-array 8192 :element-type '(unsigned-byte 8)))) (declare (dynamic-extent input-buffer)) (loop with input-start = 0 with input-end = 0 with output = (make-array buffer-size :element-type '(unsigned-byte 8)) with output-start = 0 initially (setf input-end (read-sequence input-buffer input)) do (cond ((= output-start (length output)) ;; Reallocate the output buffer. (let ((new (make-array (* 2 (length output)) :element-type '(unsigned-byte 8)))) (setf output (replace new output)))) (t (multiple-value-bind (consumed produced) (funcall fun state input-buffer output :input-start input-start :input-end input-end :output-start output-start) (incf input-start consumed) (incf output-start produced) (let ((input-consumed-p (>= input-start input-end))) ;; Get more input if possible. (when input-consumed-p (setf input-start 0 input-end (read-sequence input-buffer input))) (when (or (dstate-done state) (and (or (and input-consumed-p (zerop input-end)) (zerop consumed)) (zerop produced))) (return-from %decompress/null-stream (maybe-subseq output output-start)))))))))) (defmethod decompress ((output null) (state decompression-state) (input stream) &key buffer-size &allow-other-keys) (%decompress/null-stream state input (decompress-fun-for-state state) (or buffer-size +default-buffer-size+))) (defun %decompress/vector-vector (output state input fun input-start input-end output-start output-end) (declare (type simple-octet-vector input output)) (declare (type function fun)) (loop with n-bytes-consumed = 0 and n-bytes-produced = 0 do (multiple-value-bind (consumed produced) (funcall fun state input output :input-start input-start :input-end input-end :output-start output-start :output-end output-end) (incf input-start consumed) (incf output-start produced) (incf n-bytes-consumed consumed) (incf n-bytes-produced produced) (when (and (or (>= input-start input-end) (zerop consumed)) (or (>= output-start output-end) (zerop produced))) (return-from %decompress/vector-vector (values n-bytes-consumed n-bytes-produced)))))) (defmethod decompress ((output vector) (state decompression-state) (input vector) &key (input-start 0) input-end (output-start 0) output-end &allow-other-keys) (%decompress/vector-vector output state input (decompress-fun-for-state state) input-start (or input-end (length input)) output-start (or output-end (length output)))) (defun %decompress/stream-vector (output state input fun input-start input-end) (declare (type function fun)) (let ((buffer (make-array 8192 :element-type '(unsigned-byte 8)))) (declare (dynamic-extent buffer)) (loop (multiple-value-bind (consumed produced) (funcall fun state input buffer :input-start input-start :input-end input-end) (incf input-start consumed) (write-sequence buffer output :end produced) (when (or (dstate-done state) (and (or (>= input-start input-end) (zerop consumed)) (zerop produced))) (return-from %decompress/stream-vector output)))))) (defmethod decompress ((output stream) (state decompression-state) (input vector) &key (input-start 0) input-end &allow-other-keys) (%decompress/stream-vector output state input (decompress-fun-for-state state) input-start (or input-end (length input)))) (defun %decompress/stream-stream (output state input fun) (declare (type function fun)) (let ((input-buffer (make-array 8192 :element-type '(unsigned-byte 8))) (output-buffer (make-array 8192 :element-type '(unsigned-byte 8)))) (declare (dynamic-extent input-buffer output-buffer)) (loop with input-start = 0 with input-end = 0 initially (setf input-end (read-sequence input-buffer input)) do (multiple-value-bind (consumed produced) (funcall fun state input-buffer output-buffer :input-start input-start :input-end input-end) (incf input-start consumed) (write-sequence output-buffer output :end produced) (let ((input-consumed-p (>= input-start input-end))) (when input-consumed-p (setf input-start 0 input-end (read-sequence input-buffer input))) (when (or (dstate-done state) (and (or (and input-consumed-p (zerop input-end)) (zerop consumed)) (zerop produced))) (return-from %decompress/stream-stream output))))))) (defmethod decompress ((output stream) (state decompression-state) (input stream) &key &allow-other-keys) (%decompress/stream-stream output state input (decompress-fun-for-state state)))
validates-email-format-of/validates_email_format_of
aaf74d350f296d77edf41462ae6bab14a94bcb62
Version 1.8.2
diff --git a/CHANGELOG.md b/CHANGELOG.md index fd7fb6f..a27857f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,53 +1,59 @@ # CHANGELOG ## [Unreleased] -[Unreleased]: https://github.com/validates-email-format-of/validates_email_format_of/compare/v1.8.1...master +[Unreleased]: https://github.com/validates-email-format-of/validates_email_format_of/compare/v1.8.2...master + +## [1.8.2] + +* Improve German translations - https://github.com/validates-email-format-of/validates_email_format_of/pull/111 + +[1.8.2]: https://github.com/validates-email-format-of/validates_email_format_of/compare/v1.8.1...1.8.2 ## [1.8.1] * Fix IDN->Punycode conversion when domain names start with periods - https://github.com/validates-email-format-of/validates_email_format_of/issues/109 * Add jruby to test matrix - https://github.com/validates-email-format-of/validates_email_format_of/pull/108 -[Unreleased]: https://github.com/validates-email-format-of/validates_email_format_of/compare/v1.8.0...1.8.1 +[1.8.1]: https://github.com/validates-email-format-of/validates_email_format_of/compare/v1.8.0...1.8.1 ## [1.8.0] * Add Internationalized Domain Name support - https://github.com/validates-email-format-of/validates_email_format_of/pull/103 - thanks https://github.com/sbilharz ! * Add Turkish locale - https://github.com/validates-email-format-of/validates_email_format_of/pull/101 - thanks https://github.com/@krmbzds ! * Added Indonesian locale - https://github.com/validates-email-format-of/validates_email_format_of/commit/129ebfc3a3b432b4df0334bcbdd74b1d17d765e0 - thanks https://github.com/khoerodin ! * Fix inconsistent `generate_messages` behaviour - https://github.com/validates-email-format-of/validates_email_format_of/pull/105 * ⚠️ Deprecate `:with` option - https://github.com/validates-email-format-of/validates_email_format_of/issues/42 * Require i18n >= 0.8.0 in modern Ruby versions - https://github.com/advisories/GHSA-34hf-g744-jw64 -[1.8.0]: https://github.com/validates-email-format-of/validates_email_format_of/compare/v1.7.2...master +[1.8.0]: https://github.com/validates-email-format-of/validates_email_format_of/compare/v1.7.2...1.8.0 ## [1.7.2] * Fix regression that disallowed domains starting with number - https://github.com/validates-email-format-of/validates_email_format_of/issues/88 [1.7.2]: https://github.com/validates-email-format-of/validates_email_format_of/compare/v1.7.1...v1.7.2 ## [1.7.1] (3 Aug 2022) * Fix invalid symbols being allowed in the local part - https://github.com/validates-email-format-of/validates_email_format_of/issues/86 * Fix rspec_matcher when using a custom error message - https://github.com/validates-email-format-of/validates_email_format_of/pull/85 - thanks https://github.com/luuqnhu ! [1.7.1]: https://github.com/validates-email-format-of/validates_email_format_of/compare/v1.7.0...v1.7.1 ## [1.7.0] (29 July 2022) * Use Standard.rb for internal code formatting - https://github.com/validates-email-format-of/validates_email_format_of/commit/db1b0a86af58e478b7f9f2f269bf93bf48dc13c1 * Add support for comments in the local part and improve quoted character handling - https://github.com/validates-email-format-of/validates_email_format_of/issues/69 * Improve grammar for parsing domain part and validate domain part lengths - https://github.com/validates-email-format-of/validates_email_format_of/commit/2554b55e547c1fae6599d13b0c99296752888c91 * Do not strip spaces before validating - https://github.com/validates-email-format-of/validates_email_format_of/issues/61 and https://github.com/validates-email-format-of/validates_email_format_of/issues/72 * Allow setting check_mx_timeout and reduce the default timeout to 3 seconds - https://github.com/validates-email-format-of/validates_email_format_of/issues/66 * Fix regex duplicate character warning - https://github.com/validates-email-format-of/validates_email_format_of/pull/71 * Update CI to include Ruby 2.6 to 3.1 and Rails 4.2 to 7.0 [1.7.0]: https://github.com/validates-email-format-of/validates_email_format_of/compare/v1.6.1...v1.7.0 ## [1.6.1] (8 Sept 2014) * In a Rails context, this gem now uses ActiveModel's default logic for constructing I18n keys, to make it easier to override them on a model/attribute basis. [1.6.1]: https://github.com/validates-email-format-of/validates_email_format_of/compare/v1.6.0...v1.6.1 diff --git a/lib/validates_email_format_of/version.rb b/lib/validates_email_format_of/version.rb index 70ecbb9..c6ec4f1 100644 --- a/lib/validates_email_format_of/version.rb +++ b/lib/validates_email_format_of/version.rb @@ -1,3 +1,3 @@ module ValidatesEmailFormatOf - VERSION = "1.8.1" + VERSION = "1.8.2" end
validates-email-format-of/validates_email_format_of
997f519ecd894b983171ee59d41299d2d2b2f6e5
Fix German locale
diff --git a/config/locales/de.yml b/config/locales/de.yml index d35e068..ca794fa 100644 --- a/config/locales/de.yml +++ b/config/locales/de.yml @@ -1,8 +1,8 @@ de: activemodel: &errors errors: messages: - invalid_email_address: 'ist offensichtlich keine gültige EMail-Adresse' + invalid_email_address: 'ist anscheinend keine gültige E-Mail-Adresse' email_address_not_routable: 'kann nicht erreicht werden' activerecord: <<: *errors
validates-email-format-of/validates_email_format_of
51be4bcb97f7e7fbdf6580c943777e73bd348ccb
Version bump to 1.8.1
diff --git a/CHANGELOG.md b/CHANGELOG.md index cd076c1..fd7fb6f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,49 +1,53 @@ # CHANGELOG ## [Unreleased] +[Unreleased]: https://github.com/validates-email-format-of/validates_email_format_of/compare/v1.8.1...master + +## [1.8.1] + * Fix IDN->Punycode conversion when domain names start with periods - https://github.com/validates-email-format-of/validates_email_format_of/issues/109 * Add jruby to test matrix - https://github.com/validates-email-format-of/validates_email_format_of/pull/108 -[Unreleased]: https://github.com/validates-email-format-of/validates_email_format_of/compare/v1.8.0...master +[Unreleased]: https://github.com/validates-email-format-of/validates_email_format_of/compare/v1.8.0...1.8.1 ## [1.8.0] * Add Internationalized Domain Name support - https://github.com/validates-email-format-of/validates_email_format_of/pull/103 - thanks https://github.com/sbilharz ! * Add Turkish locale - https://github.com/validates-email-format-of/validates_email_format_of/pull/101 - thanks https://github.com/@krmbzds ! * Added Indonesian locale - https://github.com/validates-email-format-of/validates_email_format_of/commit/129ebfc3a3b432b4df0334bcbdd74b1d17d765e0 - thanks https://github.com/khoerodin ! * Fix inconsistent `generate_messages` behaviour - https://github.com/validates-email-format-of/validates_email_format_of/pull/105 * ⚠️ Deprecate `:with` option - https://github.com/validates-email-format-of/validates_email_format_of/issues/42 * Require i18n >= 0.8.0 in modern Ruby versions - https://github.com/advisories/GHSA-34hf-g744-jw64 [1.8.0]: https://github.com/validates-email-format-of/validates_email_format_of/compare/v1.7.2...master ## [1.7.2] * Fix regression that disallowed domains starting with number - https://github.com/validates-email-format-of/validates_email_format_of/issues/88 [1.7.2]: https://github.com/validates-email-format-of/validates_email_format_of/compare/v1.7.1...v1.7.2 ## [1.7.1] (3 Aug 2022) * Fix invalid symbols being allowed in the local part - https://github.com/validates-email-format-of/validates_email_format_of/issues/86 * Fix rspec_matcher when using a custom error message - https://github.com/validates-email-format-of/validates_email_format_of/pull/85 - thanks https://github.com/luuqnhu ! [1.7.1]: https://github.com/validates-email-format-of/validates_email_format_of/compare/v1.7.0...v1.7.1 ## [1.7.0] (29 July 2022) * Use Standard.rb for internal code formatting - https://github.com/validates-email-format-of/validates_email_format_of/commit/db1b0a86af58e478b7f9f2f269bf93bf48dc13c1 * Add support for comments in the local part and improve quoted character handling - https://github.com/validates-email-format-of/validates_email_format_of/issues/69 * Improve grammar for parsing domain part and validate domain part lengths - https://github.com/validates-email-format-of/validates_email_format_of/commit/2554b55e547c1fae6599d13b0c99296752888c91 * Do not strip spaces before validating - https://github.com/validates-email-format-of/validates_email_format_of/issues/61 and https://github.com/validates-email-format-of/validates_email_format_of/issues/72 * Allow setting check_mx_timeout and reduce the default timeout to 3 seconds - https://github.com/validates-email-format-of/validates_email_format_of/issues/66 * Fix regex duplicate character warning - https://github.com/validates-email-format-of/validates_email_format_of/pull/71 * Update CI to include Ruby 2.6 to 3.1 and Rails 4.2 to 7.0 [1.7.0]: https://github.com/validates-email-format-of/validates_email_format_of/compare/v1.6.1...v1.7.0 ## [1.6.1] (8 Sept 2014) * In a Rails context, this gem now uses ActiveModel's default logic for constructing I18n keys, to make it easier to override them on a model/attribute basis. [1.6.1]: https://github.com/validates-email-format-of/validates_email_format_of/compare/v1.6.0...v1.6.1 diff --git a/lib/validates_email_format_of/version.rb b/lib/validates_email_format_of/version.rb index 29d8cbf..70ecbb9 100644 --- a/lib/validates_email_format_of/version.rb +++ b/lib/validates_email_format_of/version.rb @@ -1,3 +1,3 @@ module ValidatesEmailFormatOf - VERSION = "1.8.0" + VERSION = "1.8.1" end
validates-email-format-of/validates_email_format_of
425251e16213b51ec3bd395a7d18e7928d0e1510
Split domain parts before punycode conversion
diff --git a/lib/validates_email_format_of.rb b/lib/validates_email_format_of.rb index 8f8a7b4..2e7e6f2 100644 --- a/lib/validates_email_format_of.rb +++ b/lib/validates_email_format_of.rb @@ -1,308 +1,308 @@ require "validates_email_format_of/version" require "simpleidn" module ValidatesEmailFormatOf def self.load_i18n_locales require "i18n" I18n.load_path += Dir.glob(File.expand_path(File.join(File.dirname(__FILE__), "..", "config", "locales", "*.yml"))) end require "resolv" # Characters that are allowed in to appear in the local part unquoted # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.3 # # An addr-spec is a specific Internet identifier that contains a # locally interpreted string followed by the at-sign character ("@", # ASCII value 64) followed by an Internet domain. The locally # interpreted string is either a quoted-string or a dot-atom. If the # string can be represented as a dot-atom (that is, it contains no # characters other than atext characters or "." surrounded by atext # characters), then the dot-atom form SHOULD be used and the quoted- # string form SHOULD NOT be used. Comments and folding white space # SHOULD NOT be used around the "@" in the addr-spec. # # atext = ALPHA / DIGIT / # "!" / "#" / "$" / "%" / "&" / "'" / "*" / # "+" / "-" / "/" / "=" / "?" / "^" / "_" / # "`" / "{" / "|" / "}" / "~" # dot-atom-text = 1*atext *("." 1*atext) # dot-atom = [CFWS] dot-atom-text [CFWS] ATEXT = /\A[A-Z0-9!\#$%&'*\-\/=?+\^_`{|}~]\z/i # Characters that are allowed to appear unquoted in comments # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.2 # # ctext = %d33-39 / %d42-91 / %d93-126 # ccontent = ctext / quoted-pair / comment # comment = "(" *([FWS] ccontent) [FWS] ")" # CFWS = (1*([FWS] comment) [FWS]) / FWS CTEXT = /\A[#{Regexp.escape([33..39, 42..91, 93..126].map { |ascii_range| ascii_range.map(&:chr) }.flatten.join)}\s]/i # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.4 # # Strings of characters that include characters other than those # allowed in atoms can be represented in a quoted string format, where # the characters are surrounded by quote (DQUOTE, ASCII value 34) # characters. # # qtext = %d33 / ; Printable US-ASCII # %d35-91 / ; characters not including # %d93-126 / ; "\" or the quote character # obs-qtext # # qcontent = qtext / quoted-pair # quoted-string = [CFWS] # DQUOTE *([FWS] qcontent) [FWS] DQUOTE # [CFWS] QTEXT = /\A[#{Regexp.escape([33..33, 35..91, 93..126].map { |ascii_range| ascii_range.map(&:chr) }.flatten.join)}\s]/i IP_OCTET = /\A[0-9]+\Z/ # From https://datatracker.ietf.org/doc/html/rfc1035#section-2.3.1 # # > The labels must follow the rules for ARPANET host names. They must # > start with a letter, end with a letter or digit, and have as interior # > characters only letters, digits, and hyphen. There are also some # > restrictions on the length. Labels must be 63 characters or less. # # <label> | <subdomain> "." <label> # <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ] # <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str> # <let-dig-hyp> ::= <let-dig> | "-" # <let-dig> ::= <letter> | <digit> # # Additionally, from https://datatracker.ietf.org/doc/html/rfc1123#section-2.1 # # > One aspect of host name syntax is hereby changed: the # > restriction on the first character is relaxed to allow either a # > letter or a digit. Host software MUST support this more liberal # > syntax. DOMAIN_PART_LABEL = /\A[A-Za-z0-9][A-Za-z0-9-]*[A-Za-z0-9]?\Z/ # From https://tools.ietf.org/id/draft-liman-tld-names-00.html#rfc.section.2 # # > A TLD label MUST be at least two characters long and MAY be as long as 63 characters - # > not counting any leading or trailing periods (.). It MUST consist of only ASCII characters # > from the groups "letters" (A-Z), "digits" (0-9) and "hyphen" (-), and it MUST start with an # > ASCII "letter", and it MUST NOT end with a "hyphen". Upper and lower case MAY be mixed at random, # > since DNS lookups are case-insensitive. # # tldlabel = ALPHA *61(ldh) ld # ldh = ld / "-" # ld = ALPHA / DIGIT # ALPHA = %x41-5A / %x61-7A ; A-Z / a-z # DIGIT = %x30-39 ; 0-9 DOMAIN_PART_TLD = /\A[A-Za-z][A-Za-z0-9-]*[A-Za-z0-9]\Z/ def self.validate_email_domain(email, idn: true, check_mx_timeout: 3) domain = email.to_s.downcase.match(/@(.+)/)[1] domain = SimpleIDN.to_ascii(domain) if idn Resolv::DNS.open do |dns| dns.timeouts = check_mx_timeout @mx = dns.getresources(domain, Resolv::DNS::Resource::IN::MX) + dns.getresources(domain, Resolv::DNS::Resource::IN::A) end @mx.size > 0 end DEFAULT_MESSAGE = "does not appear to be valid" DEFAULT_MX_MESSAGE = "is not routable" ERROR_MESSAGE_I18N_KEY = :invalid_email_address ERROR_MX_MESSAGE_I18N_KEY = :email_address_not_routable def self.default_message defined?(I18n) ? I18n.t(ERROR_MESSAGE_I18N_KEY, scope: [:activemodel, :errors, :messages], default: DEFAULT_MESSAGE) : DEFAULT_MESSAGE end # Validates whether the specified value is a valid email address. Returns nil if the value is valid, otherwise returns an array # containing one or more validation error messages. # # Configuration options: # * <tt>message</tt> - A custom error message (default is: "does not appear to be valid") # * <tt>check_mx</tt> - Check for MX records (default is false) # * <tt>check_mx_timeout</tt> - Timeout in seconds for checking MX records before a `ResolvTimeout` is raised (default is 3) # * <tt>idn</tt> - Enable or disable Internationalized Domain Names (default is true) # * <tt>mx_message</tt> - A custom error message when an MX record validation fails (default is: "is not routable.") # * <tt>local_length</tt> Maximum number of characters allowed in the local part (default is 64) # * <tt>domain_length</tt> Maximum number of characters allowed in the domain part (default is 255) # * <tt>generate_message</tt> Return the I18n key of the error message instead of the error message itself (default is false) def self.validate_email_format(email, options = {}) default_options = {message: options[:generate_message] ? ERROR_MESSAGE_I18N_KEY : default_message, check_mx: false, check_mx_timeout: 3, idn: true, mx_message: if options[:generate_message] ERROR_MX_MESSAGE_I18N_KEY else (defined?(I18n) ? I18n.t(ERROR_MX_MESSAGE_I18N_KEY, scope: [:activemodel, :errors, :messages], default: DEFAULT_MX_MESSAGE) : DEFAULT_MX_MESSAGE) end, domain_length: 255, local_length: 64, generate_message: false} opts = options.merge(default_options) { |key, old, new| old } # merge the default options into the specified options, retaining all specified options begin domain, local = email.reverse.split("@", 2) rescue return [opts[:message]] end # need local and domain parts return [opts[:message]] unless local && !local.empty? && domain && !domain.empty? # check lengths return [opts[:message]] unless domain.length <= opts[:domain_length] && local.length <= opts[:local_length] local.reverse! domain.reverse! if opts.has_key?(:with) # holdover from versions <= 1.4.7 deprecation_warn(":with option is deprecated and will be removed in the next version") return [opts[:message]] unless email&.match?(opts[:with]) else return [opts[:message]] unless validate_local_part_syntax(local) && validate_domain_part_syntax(domain, idn: opts[:idn]) end if opts[:check_mx] && !validate_email_domain(email, check_mx_timeout: opts[:check_mx_timeout], idn: opts[:idn]) return [opts[:mx_message]] end nil # represents no validation errors end def self.validate_local_part_syntax(local) in_quoted_pair = false in_quoted_string = false comment_depth = 0 # The local part is made up of dot-atom and quoted-string joined together by "." characters # # https://www.rfc-editor.org/rfc/rfc5322#section-3.4.1 # > local-part = dot-atom / quoted-string / obs-local-part # # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.3 # Both atom and dot-atom are interpreted as a single unit, comprising # > the string of characters that make it up. Semantically, the optional # > comments and FWS surrounding the rest of the characters are not part # > of the atom; the atom is only the run of atext characters in an atom, # > or the atext and "." characters in a dot-atom. joining_atoms = true (0..local.length - 1).each do |i| ord = local[i].ord # accept anything if it's got a backslash before it if in_quoted_pair in_quoted_pair = false next end # double quote delimits quoted strings if ord == 34 if in_quoted_string # leaving the quoted string in_quoted_string = false next elsif joining_atoms # are we allowed to enter a quoted string? in_quoted_string = true joining_atoms = false next else return false end end # period indicates we want to join atoms, e.g. `aaa.bbb."ccc"@example.com if ord == 46 return false if i.zero? return false if joining_atoms joining_atoms = true next end joining_atoms = false # quoted string logic must come before comment processing since a quoted string # may contain parens, e.g. `"name(a)"@example.com` if in_quoted_string next if QTEXT.match?(local[i]) end # opening paren to show we are going into a comment (CFWS) if ord == 40 comment_depth += 1 next end # closing paren if ord == 41 comment_depth -= 1 return false if comment_depth < 0 next end # backslash signifies the start of a quoted pair if ord == 92 # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.1 # > The only places in this specification where quoted-pair currently appears are # > ccontent, qcontent, and in obs-dtext in section 4. return false unless in_quoted_string || comment_depth > 0 in_quoted_pair = true next end if comment_depth > 0 next if CTEXT.match?(local[i]) elsif ATEXT.match?(local[i, 1]) next end return false end return false if in_quoted_pair # unbalanced quoted pair return false if in_quoted_string # unbalanced quotes return false unless comment_depth.zero? # unbalanced comment parens return false if joining_atoms # the last char we encountered was a period true end def self.validate_domain_part_syntax(domain, idn: true) - domain = SimpleIDN.to_ascii(domain) if idn parts = domain.downcase.split(".", -1) + parts.map! { |part| SimpleIDN.to_ascii(part) } if idn return false if parts.length <= 1 # Only one domain part # ipv4 return true if parts.length == 4 && parts.all? { |part| part =~ IP_OCTET && part.to_i.between?(0, 255) } # From https://datatracker.ietf.org/doc/html/rfc3696#section-2 this is the recommended, pragmatic way to validate a domain name: # # > It is likely that the better strategy has now become to make the "at least one period" test, # > to verify LDH conformance (including verification that the apparent TLD name is not all-numeric), # > and then to use the DNS to determine domain name validity, rather than trying to maintain # > a local list of valid TLD names. # # We do a little bit more but not too much and validate the tokens but do not check against a list of valid TLDs. parts.each do |part| return false if part.nil? || part.empty? return false if part.length > 63 return false unless DOMAIN_PART_LABEL.match?(part) end return false unless DOMAIN_PART_TLD.match?(parts[-1]) true end def self.deprecation_warn(msg) if defined?(ActiveSupport::Deprecation) ActiveSupport::Deprecation.warn(msg) else warn(msg) end end end require "validates_email_format_of/active_model" if defined?(::ActiveModel) && !(ActiveModel::VERSION::MAJOR < 2 || (ActiveModel::VERSION::MAJOR == 2 && ActiveModel::VERSION::MINOR < 1)) require "validates_email_format_of/railtie" if defined?(::Rails::Railtie) diff --git a/spec/validates_email_format_of_spec.rb b/spec/validates_email_format_of_spec.rb index 236ea81..ceda53a 100644 --- a/spec/validates_email_format_of_spec.rb +++ b/spec/validates_email_format_of_spec.rb @@ -1,395 +1,397 @@ require "#{__dir__}/spec_helper" require "validates_email_format_of" RSpec.configure do |config| config.before(:suite) do ValidatesEmailFormatOf.load_i18n_locales I18n.enforce_available_locales = false end end describe ValidatesEmailFormatOf do subject do |example| user = Class.new do def initialize(email) @email = email.freeze end attr_reader :email include ActiveModel::Validations validates_email_format_of :email, example.example_group_instance.options def self.model_name ActiveModel::Name.new(self, nil, "User") end end user.new(example.example_group_instance.email).tap(&:valid?) end let(:options) { {} } let(:email) { |example| example.example_group.description } shared_examples_for :all_specs do [ "valid@example.com", "Valid@test.example.com", "valid+valid123@test.example.com", "valid_valid123@test.example.com", "valid-valid+123@test.example.co.uk", "valid-valid+1.23@test.example.com.au", "valid@1example.com", "valid@example.co.uk", "v@example.com", "valid@example.ca", "valid_@example.com", "valid123.456@example.org", "valid123.456@example.travel", "valid123.456@example.museum", "valid@example.mobi", "valid@example.info", "valid-@example.com", "fake@p-t.k12.ok.us", # allow single character domain parts "valid@mail.x.example.com", "valid@x.com", "valid@example.w-dash.sch.uk", # from RFC 3696, page 6 "customer/department=shipping@example.com", "$A12345@example.com", "!def!xyz%abc@example.com", "_somename@example.com", # apostrophes "test'test@example.com", # punycode domain names "test@xn--bcher-kva.ch", "test@example.xn--0zwm56d", # IDN domains, "test@exämple.com", "test@пример.рф", "test@почта.бел", "test@192.192.192.1", # Allow quoted characters. Valid according to http://www.rfc-editor.org/errata_search.php?rfc=3696 '"Abc\@def"@example.com', "\"quote\".dotatom.\"otherquote\"@example.com", '"Quote(Only".Chars@wier.de', "\"much.more unusual\"@example.com", "\"very.unusual.@.unusual.com\"@example.com", '"very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual"@strange.example.com', '"()<>[]:,;@\"!#$%&*+-/=?^_`{}| ~ ? ^_`{}|~.a"@example.org', '"Fred\ Bloggs"@example.com', '"Joe.\\Blow"@example.com', # Balanced quoted characters %("example\\\\\\""@example.com), %("example\\\\"@example.com), "(leading comment)email@example.com", "(nested (comment))email@example.com", "email(trailing comment)@example.com" ].each do |address| describe address do it { should_not have_errors_on_email } end end [ "no_at_symbol", "multiple@at@symbols.com", "invalid@example-com", # period can not start local part ".invalid@example.com", # period can not end local part "invalid.@example.com", # period can not appear twice consecutively in local part "invali..d@example.com", # should not allow underscores in domain names "invalid@ex_mple.com", "invalid@e..example.com", "invalid@p-t..example.com", "invalid@example.com.", "invalid@example.com_", "invalid@example.com-", "invalid-example.com", "invalid@example.b#r.com", "just\"not\"right@example.com", "invalid@example.c", "invali d@example.com", # TLD can not be only numeric "invalid@example.123", # unclosed quote "\"a-17180061943-10618354-1993365053@example.com", # too many special chars used to cause the regexp to hang "-+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++@foo", "invalidexample.com", # should not allow special chars after a period in the domain "local@sub.)domain.com", "local@sub.#domain.com", # one at a time "foo@example.com\nexample@gmail.com", "invalid@example.", "\"foo\\\\\"\"@bar.com", "foo@mail.com\r\nfoo@mail.com", "@example.com", "foo@", "foo", "Iñtërnâtiônàlizætiøn@hasnt.happened.to.email", # Escaped characters with quotes. From http://tools.ietf.org/html/rfc3696, page 5. Corrected in http://www.rfc-editor.org/errata_search.php?rfc=3696 'Fred\ Bloggs_@example.com', 'Abc\@def+@example.com', 'Joe.\\Blow@example.com', # Unbalanced quoted characters %("example\\\\""example.com), "\nnewline@example.com", " spacesbefore@example.com", "spacesafter@example.com ", - "(unbalancedcomment@example.com" + "(unbalancedcomment@example.com", + "help@.example.co.uk" # TLD can not start with a period ].each do |address| describe address do it { should have_errors_on_email.because("does not appear to be a valid email address") } end end describe do shared_examples_for :local_length_limit do |limit| describe "#{"a" * limit}@example.com" do it { should_not have_errors_on_email } end describe "#{"a" * (limit + 1)}@example.com" do it { should have_errors_on_email.because("does not appear to be a valid email address") } end end describe "when using default" do it_should_behave_like :local_length_limit, 64 end describe "when overriding defaults" do let(:options) { {local_length: 20} } it_should_behave_like :local_length_limit, 20 end end describe do shared_examples_for :domain_length_limit do |limit| describe "user@#{"a." * (limit / 2 - 3)}com" do it { should_not have_errors_on_email } end describe "user@#{"a." * (limit / 2 + 1)}com" do it { should have_errors_on_email.because("does not appear to be a valid email address") } end end describe "when using default" do it_should_behave_like :domain_length_limit, 255 end describe "when overriding defaults" do let(:options) { {domain_length: 100} } it_should_behave_like :domain_length_limit, 100 end end describe "custom error messages" do describe "invalid@example." do let(:options) { {message: "just because I don't like you"} } it { should have_errors_on_email.because("just because I don't like you") } end end describe "when idn support is disabled" do before(:each) do allow(SimpleIDN).to receive(:to_ascii).never end let(:options) { {idn: false} } describe "test@exämple.com" do it { should have_errors_on_email.because("does not appear to be a valid email address") } end end describe "when idn support is enabled" do before(:each) do - allow(SimpleIDN).to receive(:to_ascii).once.with("exämple.com").and_return("xn--exmple-cua.com") + expect(SimpleIDN).to receive(:to_ascii).with("exämple").and_return("xn--exmple-cua") + expect(SimpleIDN).to receive(:to_ascii).with("com").and_return("com") end let(:options) { {idn: true} } describe "test@exämple.com" do it { should_not have_errors_on_email } end end describe "mx record" do domain = "example.com" email = "valid@#{domain}" describe "when testing" do let(:dns) { double(Resolv::DNS) } let(:mx_record) { [double] } let(:a_record) { [double] } before(:each) do allow(Resolv::DNS).to receive(:open).and_yield(dns) allow(dns).to receive(:"timeouts=").with(3).once allow(dns).to receive(:getresources).with(domain, Resolv::DNS::Resource::IN::MX).once.and_return(mx_record) allow(dns).to receive(:getresources).with(domain, Resolv::DNS::Resource::IN::A).once.and_return(a_record) end let(:options) { {check_mx: true, check_mx_timeout: 3} } describe "and only an mx record is found" do let(:a_record) { [] } describe email do it { should_not have_errors_on_email } end end describe "and only an a record is found" do let(:mx_record) { [] } describe email do it { should_not have_errors_on_email } end end describe "and both an mx record and an a record are found" do describe email do it { should_not have_errors_on_email } end end describe "and neither an mx record nor an a record is found" do let(:a_record) { [] } let(:mx_record) { [] } describe email do it { should have_errors_on_email.because("is not routable") } it "adds the i18n key" do subject.errors.added?(:email, ValidatesEmailFormatOf::ERROR_MX_MESSAGE_I18N_KEY) end end describe "with a custom error message" do let(:options) { {check_mx: true, mx_message: "There ain't no such domain!"} } describe email do it { should have_errors_on_email.because("There ain't no such domain!") } end end describe "i18n" do before(:each) do allow(I18n.config).to receive(:locale).and_return(locale) end describe "present locale" do let(:locale) { :pl } describe email do it { should have_errors_on_email.because("jest nieosiągalny") } end end end end end describe "when not testing" do before(:each) { allow(Resolv::DNS).to receive(:open).never } describe "by default" do describe email do it { should_not have_errors_on_email } end end describe "explicitly" do describe email do let(:options) { {check_mx: false} } it { should_not have_errors_on_email } end end end describe "without mocks" do describe email do let(:options) { {check_mx: true} } it { should_not have_errors_on_email } end end end describe "mx record for internationalized domain" do domain = "пример.рф" email = "valid@#{domain}" describe "when idn support is enabled" do let(:dns) { double(Resolv::DNS) } let(:options) { {check_mx: true, idn: true} } before(:each) do allow(Resolv::DNS).to receive(:open).and_yield(dns) allow(dns).to receive(:"timeouts=").with(3).once allow(dns).to receive(:getresources).with(SimpleIDN.to_ascii(domain), Resolv::DNS::Resource::IN::A).once.and_return([double]) allow(dns).to receive(:getresources).with(SimpleIDN.to_ascii(domain), Resolv::DNS::Resource::IN::MX).once.and_return([double]) end describe email do it { should_not have_errors_on_email } end end describe "when idn support is disabled" do let(:options) { {check_mx: true, idn: false} } describe "test@пример.рф" do let(:domain) { "exämple.com" } it { should have_errors_on_email.because("does not appear to be a valid email address") } end end end describe "custom regex" do let(:options) { {with: /[0-9]+@[0-9]+/} } describe "012345@789" do it { should_not have_errors_on_email } end describe "valid@example.com" do it { should have_errors_on_email.because("does not appear to be a valid email address") } end end describe "i18n" do before(:each) do allow(I18n.config).to receive(:locale).and_return(locale) end describe "present locale" do let(:locale) { :pl } describe "invalid@exmaple." do it { should have_errors_on_email.because("nieprawidłowy adres email") } end end end end it_should_behave_like :all_specs describe "validation without ActiveModel" do subject do ValidatesEmailFormatOf.validate_email_format(email.freeze, options) end describe "valid@example.com" do it { should be_nil } end describe "custom error messages" do describe "invalid@example." do let(:options) { {message: "just because I don't like you"} } it { should match_array(["just because I don't like you"]) } end end describe "without i18n" do before(:each) { hide_const("I18n") } describe "invalid@exmaple." do it { should match_array(["does not appear to be valid"]) } end end end describe "shorthand ActiveModel validation" do subject do |example| user = Class.new do def initialize(email) @email = email.freeze end attr_reader :email include ActiveModel::Validations validates :email, email_format: example.example_group_instance.options def self.model_name ActiveModel::Name.new(self, nil, "User") end end user.new(example.example_group_instance.email).tap(&:valid?) end it_should_behave_like :all_specs end end
validates-email-format-of/validates_email_format_of
0306e4c3cc4f298993b760ec16d7cf3352039eff
Fix deprecation warnings without Rails
diff --git a/lib/validates_email_format_of.rb b/lib/validates_email_format_of.rb index f742e32..8f8a7b4 100644 --- a/lib/validates_email_format_of.rb +++ b/lib/validates_email_format_of.rb @@ -1,308 +1,308 @@ require "validates_email_format_of/version" require "simpleidn" module ValidatesEmailFormatOf def self.load_i18n_locales require "i18n" I18n.load_path += Dir.glob(File.expand_path(File.join(File.dirname(__FILE__), "..", "config", "locales", "*.yml"))) end require "resolv" # Characters that are allowed in to appear in the local part unquoted # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.3 # # An addr-spec is a specific Internet identifier that contains a # locally interpreted string followed by the at-sign character ("@", # ASCII value 64) followed by an Internet domain. The locally # interpreted string is either a quoted-string or a dot-atom. If the # string can be represented as a dot-atom (that is, it contains no # characters other than atext characters or "." surrounded by atext # characters), then the dot-atom form SHOULD be used and the quoted- # string form SHOULD NOT be used. Comments and folding white space # SHOULD NOT be used around the "@" in the addr-spec. # # atext = ALPHA / DIGIT / # "!" / "#" / "$" / "%" / "&" / "'" / "*" / # "+" / "-" / "/" / "=" / "?" / "^" / "_" / # "`" / "{" / "|" / "}" / "~" # dot-atom-text = 1*atext *("." 1*atext) # dot-atom = [CFWS] dot-atom-text [CFWS] ATEXT = /\A[A-Z0-9!\#$%&'*\-\/=?+\^_`{|}~]\z/i # Characters that are allowed to appear unquoted in comments # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.2 # # ctext = %d33-39 / %d42-91 / %d93-126 # ccontent = ctext / quoted-pair / comment # comment = "(" *([FWS] ccontent) [FWS] ")" # CFWS = (1*([FWS] comment) [FWS]) / FWS CTEXT = /\A[#{Regexp.escape([33..39, 42..91, 93..126].map { |ascii_range| ascii_range.map(&:chr) }.flatten.join)}\s]/i # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.4 # # Strings of characters that include characters other than those # allowed in atoms can be represented in a quoted string format, where # the characters are surrounded by quote (DQUOTE, ASCII value 34) # characters. # # qtext = %d33 / ; Printable US-ASCII # %d35-91 / ; characters not including # %d93-126 / ; "\" or the quote character # obs-qtext # # qcontent = qtext / quoted-pair # quoted-string = [CFWS] # DQUOTE *([FWS] qcontent) [FWS] DQUOTE # [CFWS] QTEXT = /\A[#{Regexp.escape([33..33, 35..91, 93..126].map { |ascii_range| ascii_range.map(&:chr) }.flatten.join)}\s]/i IP_OCTET = /\A[0-9]+\Z/ # From https://datatracker.ietf.org/doc/html/rfc1035#section-2.3.1 # # > The labels must follow the rules for ARPANET host names. They must # > start with a letter, end with a letter or digit, and have as interior # > characters only letters, digits, and hyphen. There are also some # > restrictions on the length. Labels must be 63 characters or less. # # <label> | <subdomain> "." <label> # <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ] # <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str> # <let-dig-hyp> ::= <let-dig> | "-" # <let-dig> ::= <letter> | <digit> # # Additionally, from https://datatracker.ietf.org/doc/html/rfc1123#section-2.1 # # > One aspect of host name syntax is hereby changed: the # > restriction on the first character is relaxed to allow either a # > letter or a digit. Host software MUST support this more liberal # > syntax. DOMAIN_PART_LABEL = /\A[A-Za-z0-9][A-Za-z0-9-]*[A-Za-z0-9]?\Z/ # From https://tools.ietf.org/id/draft-liman-tld-names-00.html#rfc.section.2 # # > A TLD label MUST be at least two characters long and MAY be as long as 63 characters - # > not counting any leading or trailing periods (.). It MUST consist of only ASCII characters # > from the groups "letters" (A-Z), "digits" (0-9) and "hyphen" (-), and it MUST start with an # > ASCII "letter", and it MUST NOT end with a "hyphen". Upper and lower case MAY be mixed at random, # > since DNS lookups are case-insensitive. # # tldlabel = ALPHA *61(ldh) ld # ldh = ld / "-" # ld = ALPHA / DIGIT # ALPHA = %x41-5A / %x61-7A ; A-Z / a-z # DIGIT = %x30-39 ; 0-9 DOMAIN_PART_TLD = /\A[A-Za-z][A-Za-z0-9-]*[A-Za-z0-9]\Z/ def self.validate_email_domain(email, idn: true, check_mx_timeout: 3) domain = email.to_s.downcase.match(/@(.+)/)[1] domain = SimpleIDN.to_ascii(domain) if idn Resolv::DNS.open do |dns| dns.timeouts = check_mx_timeout @mx = dns.getresources(domain, Resolv::DNS::Resource::IN::MX) + dns.getresources(domain, Resolv::DNS::Resource::IN::A) end @mx.size > 0 end DEFAULT_MESSAGE = "does not appear to be valid" DEFAULT_MX_MESSAGE = "is not routable" ERROR_MESSAGE_I18N_KEY = :invalid_email_address ERROR_MX_MESSAGE_I18N_KEY = :email_address_not_routable def self.default_message defined?(I18n) ? I18n.t(ERROR_MESSAGE_I18N_KEY, scope: [:activemodel, :errors, :messages], default: DEFAULT_MESSAGE) : DEFAULT_MESSAGE end # Validates whether the specified value is a valid email address. Returns nil if the value is valid, otherwise returns an array # containing one or more validation error messages. # # Configuration options: # * <tt>message</tt> - A custom error message (default is: "does not appear to be valid") # * <tt>check_mx</tt> - Check for MX records (default is false) # * <tt>check_mx_timeout</tt> - Timeout in seconds for checking MX records before a `ResolvTimeout` is raised (default is 3) # * <tt>idn</tt> - Enable or disable Internationalized Domain Names (default is true) # * <tt>mx_message</tt> - A custom error message when an MX record validation fails (default is: "is not routable.") # * <tt>local_length</tt> Maximum number of characters allowed in the local part (default is 64) # * <tt>domain_length</tt> Maximum number of characters allowed in the domain part (default is 255) # * <tt>generate_message</tt> Return the I18n key of the error message instead of the error message itself (default is false) def self.validate_email_format(email, options = {}) default_options = {message: options[:generate_message] ? ERROR_MESSAGE_I18N_KEY : default_message, check_mx: false, check_mx_timeout: 3, idn: true, mx_message: if options[:generate_message] ERROR_MX_MESSAGE_I18N_KEY else (defined?(I18n) ? I18n.t(ERROR_MX_MESSAGE_I18N_KEY, scope: [:activemodel, :errors, :messages], default: DEFAULT_MX_MESSAGE) : DEFAULT_MX_MESSAGE) end, domain_length: 255, local_length: 64, generate_message: false} opts = options.merge(default_options) { |key, old, new| old } # merge the default options into the specified options, retaining all specified options begin domain, local = email.reverse.split("@", 2) rescue return [opts[:message]] end # need local and domain parts return [opts[:message]] unless local && !local.empty? && domain && !domain.empty? # check lengths return [opts[:message]] unless domain.length <= opts[:domain_length] && local.length <= opts[:local_length] local.reverse! domain.reverse! if opts.has_key?(:with) # holdover from versions <= 1.4.7 deprecation_warn(":with option is deprecated and will be removed in the next version") return [opts[:message]] unless email&.match?(opts[:with]) else return [opts[:message]] unless validate_local_part_syntax(local) && validate_domain_part_syntax(domain, idn: opts[:idn]) end if opts[:check_mx] && !validate_email_domain(email, check_mx_timeout: opts[:check_mx_timeout], idn: opts[:idn]) return [opts[:mx_message]] end nil # represents no validation errors end def self.validate_local_part_syntax(local) in_quoted_pair = false in_quoted_string = false comment_depth = 0 # The local part is made up of dot-atom and quoted-string joined together by "." characters # # https://www.rfc-editor.org/rfc/rfc5322#section-3.4.1 # > local-part = dot-atom / quoted-string / obs-local-part # # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.3 # Both atom and dot-atom are interpreted as a single unit, comprising # > the string of characters that make it up. Semantically, the optional # > comments and FWS surrounding the rest of the characters are not part # > of the atom; the atom is only the run of atext characters in an atom, # > or the atext and "." characters in a dot-atom. joining_atoms = true (0..local.length - 1).each do |i| ord = local[i].ord # accept anything if it's got a backslash before it if in_quoted_pair in_quoted_pair = false next end # double quote delimits quoted strings if ord == 34 if in_quoted_string # leaving the quoted string in_quoted_string = false next elsif joining_atoms # are we allowed to enter a quoted string? in_quoted_string = true joining_atoms = false next else return false end end # period indicates we want to join atoms, e.g. `aaa.bbb."ccc"@example.com if ord == 46 return false if i.zero? return false if joining_atoms joining_atoms = true next end joining_atoms = false # quoted string logic must come before comment processing since a quoted string # may contain parens, e.g. `"name(a)"@example.com` if in_quoted_string next if QTEXT.match?(local[i]) end # opening paren to show we are going into a comment (CFWS) if ord == 40 comment_depth += 1 next end # closing paren if ord == 41 comment_depth -= 1 return false if comment_depth < 0 next end # backslash signifies the start of a quoted pair if ord == 92 # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.1 # > The only places in this specification where quoted-pair currently appears are # > ccontent, qcontent, and in obs-dtext in section 4. return false unless in_quoted_string || comment_depth > 0 in_quoted_pair = true next end if comment_depth > 0 next if CTEXT.match?(local[i]) elsif ATEXT.match?(local[i, 1]) next end return false end return false if in_quoted_pair # unbalanced quoted pair return false if in_quoted_string # unbalanced quotes return false unless comment_depth.zero? # unbalanced comment parens return false if joining_atoms # the last char we encountered was a period true end def self.validate_domain_part_syntax(domain, idn: true) domain = SimpleIDN.to_ascii(domain) if idn parts = domain.downcase.split(".", -1) return false if parts.length <= 1 # Only one domain part # ipv4 return true if parts.length == 4 && parts.all? { |part| part =~ IP_OCTET && part.to_i.between?(0, 255) } # From https://datatracker.ietf.org/doc/html/rfc3696#section-2 this is the recommended, pragmatic way to validate a domain name: # # > It is likely that the better strategy has now become to make the "at least one period" test, # > to verify LDH conformance (including verification that the apparent TLD name is not all-numeric), # > and then to use the DNS to determine domain name validity, rather than trying to maintain # > a local list of valid TLD names. # # We do a little bit more but not too much and validate the tokens but do not check against a list of valid TLDs. parts.each do |part| return false if part.nil? || part.empty? return false if part.length > 63 return false unless DOMAIN_PART_LABEL.match?(part) end return false unless DOMAIN_PART_TLD.match?(parts[-1]) true end def self.deprecation_warn(msg) if defined?(ActiveSupport::Deprecation) ActiveSupport::Deprecation.warn(msg) else - warn + warn(msg) end end end require "validates_email_format_of/active_model" if defined?(::ActiveModel) && !(ActiveModel::VERSION::MAJOR < 2 || (ActiveModel::VERSION::MAJOR == 2 && ActiveModel::VERSION::MINOR < 1)) require "validates_email_format_of/railtie" if defined?(::Rails::Railtie)
validates-email-format-of/validates_email_format_of
c03314012f7e7ce466a17d01b206f6974bbe2a32
Remove debugger entirely
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index ea5b44c..bfd05e4 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,26 +1,25 @@ require "active_model" require "active_support" -require "debug" RSpec::Matchers.define :have_errors_on_email do match do |user| actual = user.errors.full_messages expect(user.errors.added?(:email, ValidatesEmailFormatOf::ERROR_MESSAGE_I18N_KEY)) expect(actual).not_to be_nil, "#{actual} should not be nil" expect(actual).not_to be_empty, "#{actual} should not be empty" expect(actual.size).to eq(@reasons.size), "#{actual} should have #{@reasons.size} elements" @reasons.each do |reason| reason = "Email #{reason}" expect(actual).to include(reason), "#{actual} should contain #{reason}" end end chain :because do |reason| (@reasons ||= []) << reason end chain :and_because do |reason| (@reasons ||= []) << reason end match_when_negated do |user| expect(user.errors).to(be_empty) end end diff --git a/validates_email_format_of.gemspec b/validates_email_format_of.gemspec index 033ae91..c66b3f7 100644 --- a/validates_email_format_of.gemspec +++ b/validates_email_format_of.gemspec @@ -1,29 +1,28 @@ $:.unshift File.expand_path("../lib", __FILE__) require "validates_email_format_of/version" Gem::Specification.new do |s| s.name = "validates_email_format_of" s.version = ValidatesEmailFormatOf::VERSION s.summary = "Validate email addresses against RFC 2822 and RFC 3696." s.description = s.summary s.authors = ["Alex Dunae", "Isaac Betesh"] s.email = ["code@dunae.ca", "iybetesh@gmail.com"] s.homepage = "https://github.com/validates-email-format-of/validates_email_format_of" s.license = "MIT" s.files = `git ls-files`.split($/) s.require_paths = ["lib"] if RUBY_VERSION < "1.9.3" s.add_dependency "i18n", "< 0.7.0" else s.add_dependency "i18n", ">= 0.8.0" end s.add_dependency "simpleidn" s.add_development_dependency "activemodel" s.add_development_dependency "bundler" s.add_development_dependency "rspec" s.add_development_dependency "standard" s.add_development_dependency "appraisal" - s.add_development_dependency "byebug", ">= 1.0.0" end
validates-email-format-of/validates_email_format_of
f403300edbcf30db9391312037e71ae1d7021ca9
Switch from byebug to debug.rb
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 8b96462..ea5b44c 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,27 +1,26 @@ require "active_model" require "active_support" -require "pry" -require "byebug" +require "debug" RSpec::Matchers.define :have_errors_on_email do match do |user| actual = user.errors.full_messages expect(user.errors.added?(:email, ValidatesEmailFormatOf::ERROR_MESSAGE_I18N_KEY)) expect(actual).not_to be_nil, "#{actual} should not be nil" expect(actual).not_to be_empty, "#{actual} should not be empty" expect(actual.size).to eq(@reasons.size), "#{actual} should have #{@reasons.size} elements" @reasons.each do |reason| reason = "Email #{reason}" expect(actual).to include(reason), "#{actual} should contain #{reason}" end end chain :because do |reason| (@reasons ||= []) << reason end chain :and_because do |reason| (@reasons ||= []) << reason end match_when_negated do |user| expect(user.errors).to(be_empty) end end diff --git a/validates_email_format_of.gemspec b/validates_email_format_of.gemspec index 6cf5094..033ae91 100644 --- a/validates_email_format_of.gemspec +++ b/validates_email_format_of.gemspec @@ -1,29 +1,29 @@ $:.unshift File.expand_path("../lib", __FILE__) require "validates_email_format_of/version" Gem::Specification.new do |s| s.name = "validates_email_format_of" s.version = ValidatesEmailFormatOf::VERSION s.summary = "Validate email addresses against RFC 2822 and RFC 3696." s.description = s.summary s.authors = ["Alex Dunae", "Isaac Betesh"] s.email = ["code@dunae.ca", "iybetesh@gmail.com"] s.homepage = "https://github.com/validates-email-format-of/validates_email_format_of" s.license = "MIT" s.files = `git ls-files`.split($/) s.require_paths = ["lib"] if RUBY_VERSION < "1.9.3" s.add_dependency "i18n", "< 0.7.0" else s.add_dependency "i18n", ">= 0.8.0" end s.add_dependency "simpleidn" s.add_development_dependency "activemodel" s.add_development_dependency "bundler" s.add_development_dependency "rspec" s.add_development_dependency "standard" s.add_development_dependency "appraisal" - s.add_development_dependency "pry-byebug" + s.add_development_dependency "byebug", ">= 1.0.0" end
validates-email-format-of/validates_email_format_of
ba31c388f41eae951220dce1c77b4acf660c68fb
Only run CI on PRs instead of every push
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 258130e..0d4ac55 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,98 +1,97 @@ name: CI on: - - push - pull_request permissions: contents: read jobs: test: name: "Ruby ${{ matrix.ruby }}, Rails ${{ matrix.gemfile }}" runs-on: ubuntu-latest strategy: matrix: ruby: ["2.6", "2.7", "3.0", "3.1", "3.2", "3.3"] gemfile: ["4.2", "5.0", "5.1", "5.2", "6.0", "6.1", "7.0", "7.1"] exclude: - gemfile: "4.2" ruby: "3.0" - gemfile: "4.2" ruby: "3.1" - gemfile: "4.2" ruby: "3.2" - gemfile: "4.2" ruby: "3.3" - gemfile: "5.0" ruby: "3.0" - gemfile: "5.0" ruby: "3.1" - gemfile: "5.0" ruby: "3.2" - gemfile: "5.0" ruby: "3.3" - gemfile: "5.1" ruby: "3.0" - gemfile: "5.1" ruby: "3.1" - gemfile: "5.1" ruby: "3.2" - gemfile: "5.1" ruby: "3.3" - gemfile: "5.2" ruby: "3.0" - gemfile: "5.2" ruby: "3.1" - gemfile: "5.2" ruby: "3.2" - gemfile: "5.2" ruby: "3.3" - gemfile: "6.0" ruby: "3.2" - gemfile: "6.0" ruby: "3.3" - gemfile: "6.1" ruby: "3.2" - gemfile: "6.1" ruby: "3.3" - gemfile: "7.0" ruby: "2.5" - gemfile: "7.0" ruby: "2.6" - gemfile: "7.0" ruby: "2.7" - gemfile: "7.1" ruby: "2.5" - gemfile: "7.1" ruby: "2.6" - gemfile: "7.1" ruby: "2.7" env: BUNDLE_GEMFILE: gemfiles/rails_${{ matrix.gemfile }}.gemfile RAILS_ENV: test steps: - uses: actions/checkout@v4 - name: "Install Ruby ${{ matrix.ruby }}" # To automatically get bug fixes and new Ruby versions for ruby/setup-ruby, # change this to (see https://github.com/ruby/setup-ruby#versioning): # uses: ruby/setup-ruby@v1 uses: ruby/setup-ruby@v1 with: bundler: 1 ruby-version: ${{ matrix.ruby }} bundler-cache: true # runs 'bundle install' and caches installed gems automatically - name: Run specs run: bundle exec rspec - name: Run standard.rb run: bundle exec rake standard if: ${{ ! startsWith(matrix.ruby, '2.') }}
validates-email-format-of/validates_email_format_of
7dc14c739bd24d4d1ef1fdaa7e57e99b1ddc363c
Add jruby-head to CI
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 258130e..bde2425 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,98 +1,106 @@ name: CI on: - push - pull_request permissions: contents: read jobs: test: name: "Ruby ${{ matrix.ruby }}, Rails ${{ matrix.gemfile }}" runs-on: ubuntu-latest strategy: matrix: - ruby: ["2.6", "2.7", "3.0", "3.1", "3.2", "3.3"] + ruby: ["2.6", "2.7", "3.0", "3.1", "3.2", "3.3", "jruby-head"] gemfile: ["4.2", "5.0", "5.1", "5.2", "6.0", "6.1", "7.0", "7.1"] exclude: - gemfile: "4.2" ruby: "3.0" - gemfile: "4.2" ruby: "3.1" - gemfile: "4.2" ruby: "3.2" - gemfile: "4.2" ruby: "3.3" + - gemfile: "4.2" + ruby: "jruby-head" - gemfile: "5.0" ruby: "3.0" - gemfile: "5.0" ruby: "3.1" - gemfile: "5.0" ruby: "3.2" - gemfile: "5.0" ruby: "3.3" + - gemfile: "5.0" + ruby: "jruby-head" - gemfile: "5.1" ruby: "3.0" - gemfile: "5.1" ruby: "3.1" - gemfile: "5.1" ruby: "3.2" - gemfile: "5.1" ruby: "3.3" + - gemfile: "5.1" + ruby: "jruby-head" - gemfile: "5.2" ruby: "3.0" - gemfile: "5.2" ruby: "3.1" - gemfile: "5.2" ruby: "3.2" - gemfile: "5.2" ruby: "3.3" + - gemfile: "5.2" + ruby: "jruby-head" - gemfile: "6.0" ruby: "3.2" - gemfile: "6.0" ruby: "3.3" - gemfile: "6.1" ruby: "3.2" - gemfile: "6.1" ruby: "3.3" - gemfile: "7.0" ruby: "2.5" - gemfile: "7.0" ruby: "2.6" - gemfile: "7.0" ruby: "2.7" - gemfile: "7.1" ruby: "2.5" - gemfile: "7.1" ruby: "2.6" - gemfile: "7.1" ruby: "2.7" env: BUNDLE_GEMFILE: gemfiles/rails_${{ matrix.gemfile }}.gemfile RAILS_ENV: test steps: - uses: actions/checkout@v4 - name: "Install Ruby ${{ matrix.ruby }}" # To automatically get bug fixes and new Ruby versions for ruby/setup-ruby, # change this to (see https://github.com/ruby/setup-ruby#versioning): # uses: ruby/setup-ruby@v1 uses: ruby/setup-ruby@v1 with: bundler: 1 ruby-version: ${{ matrix.ruby }} bundler-cache: true # runs 'bundle install' and caches installed gems automatically - name: Run specs run: bundle exec rspec - name: Run standard.rb run: bundle exec rake standard if: ${{ ! startsWith(matrix.ruby, '2.') }}
validates-email-format-of/validates_email_format_of
333f466e738a67bedc0983df51876d31e5ed3250
Bump version
diff --git a/lib/validates_email_format_of/version.rb b/lib/validates_email_format_of/version.rb index 858d528..29d8cbf 100644 --- a/lib/validates_email_format_of/version.rb +++ b/lib/validates_email_format_of/version.rb @@ -1,3 +1,3 @@ module ValidatesEmailFormatOf - VERSION = "1.7.2" + VERSION = "1.8.0" end
validates-email-format-of/validates_email_format_of
bab26b0fe817643bd8bf7c2b57b12d182688e850
Add Ruby 3.3 and Rails 7.1
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 90b0a2a..258130e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,66 +1,98 @@ name: CI on: - push - pull_request permissions: contents: read jobs: test: name: "Ruby ${{ matrix.ruby }}, Rails ${{ matrix.gemfile }}" runs-on: ubuntu-latest strategy: matrix: - ruby: ["2.6", "2.7", "3.0", "3.1"] - gemfile: ["4.2", "5.0", "5.1", "5.2", "6.0", "6.1", "7.0"] + ruby: ["2.6", "2.7", "3.0", "3.1", "3.2", "3.3"] + gemfile: ["4.2", "5.0", "5.1", "5.2", "6.0", "6.1", "7.0", "7.1"] + exclude: - gemfile: "4.2" ruby: "3.0" - gemfile: "4.2" ruby: "3.1" + - gemfile: "4.2" + ruby: "3.2" + - gemfile: "4.2" + ruby: "3.3" - gemfile: "5.0" ruby: "3.0" - gemfile: "5.0" ruby: "3.1" + - gemfile: "5.0" + ruby: "3.2" + - gemfile: "5.0" + ruby: "3.3" - gemfile: "5.1" ruby: "3.0" - gemfile: "5.1" ruby: "3.1" + - gemfile: "5.1" + ruby: "3.2" + - gemfile: "5.1" + ruby: "3.3" - gemfile: "5.2" ruby: "3.0" - gemfile: "5.2" ruby: "3.1" + - gemfile: "5.2" + ruby: "3.2" + - gemfile: "5.2" + ruby: "3.3" + - gemfile: "6.0" + ruby: "3.2" + - gemfile: "6.0" + ruby: "3.3" + - gemfile: "6.1" + ruby: "3.2" + - gemfile: "6.1" + ruby: "3.3" - gemfile: "7.0" ruby: "2.5" - gemfile: "7.0" ruby: "2.6" - gemfile: "7.0" ruby: "2.7" + - gemfile: "7.1" + ruby: "2.5" + - gemfile: "7.1" + ruby: "2.6" + - gemfile: "7.1" + ruby: "2.7" + env: BUNDLE_GEMFILE: gemfiles/rails_${{ matrix.gemfile }}.gemfile RAILS_ENV: test steps: - uses: actions/checkout@v4 - name: "Install Ruby ${{ matrix.ruby }}" # To automatically get bug fixes and new Ruby versions for ruby/setup-ruby, # change this to (see https://github.com/ruby/setup-ruby#versioning): # uses: ruby/setup-ruby@v1 uses: ruby/setup-ruby@v1 with: bundler: 1 ruby-version: ${{ matrix.ruby }} bundler-cache: true # runs 'bundle install' and caches installed gems automatically - name: Run specs run: bundle exec rspec - name: Run standard.rb run: bundle exec rake standard if: ${{ ! startsWith(matrix.ruby, '2.') }} diff --git a/Appraisals b/Appraisals index 51ed0d6..ea72315 100644 --- a/Appraisals +++ b/Appraisals @@ -1,32 +1,36 @@ # run `bundle exec appraisal install` after making changes here +appraise "rails-7.1" do + gem "rails", "~> 7.1" +end + appraise "rails-7.0" do gem "rails", "~> 7.0" end appraise "rails-6.1" do gem "rails", "~> 6.1.0" end appraise "rails-6.0" do gem "rails", "~> 6.0.3", ">= 6.0.3.2" end appraise "rails-5.2" do gem "rails", "~> 5.2.4", ">= 5.2.4.3" gem "i18n", "< 1" end appraise "rails-5.1" do gem "rails", "~> 5.1.7" gem "i18n", "< 1" end appraise "rails-5.0" do gem "rails", "~> 5.0.7", ">= 5.0.7.2" gem "i18n", "< 1" end appraise "rails-4.2" do gem "rails", "~> 4.2.0" gem "i18n", "< 1" end diff --git a/gemfiles/rails_7.1.gemfile b/gemfiles/rails_7.1.gemfile new file mode 100644 index 0000000..9f02e96 --- /dev/null +++ b/gemfiles/rails_7.1.gemfile @@ -0,0 +1,7 @@ +# This file was generated by Appraisal + +source "http://rubygems.org" + +gem "rails", "~> 7.1" + +gemspec path: "../"
validates-email-format-of/validates_email_format_of
5392e64dac5e8c1f50f3a69090ccf71ea159e263
Fix overriding generate_message option in validate_each
diff --git a/lib/validates_email_format_of/active_model.rb b/lib/validates_email_format_of/active_model.rb index fcb289c..430401c 100644 --- a/lib/validates_email_format_of/active_model.rb +++ b/lib/validates_email_format_of/active_model.rb @@ -1,24 +1,24 @@ require "validates_email_format_of" require "active_model" if ActiveModel::VERSION::MAJOR < 2 || (ActiveModel::VERSION::MAJOR == 2 && ActiveModel::VERSION::MINOR < 1) puts "WARNING: ActiveModel validation helper methods in validates_email_format_of gem are not compatible with ActiveModel < 2.1.0. Please use ValidatesEmailFormatOf::validate_email_format(email, options) or upgrade ActiveModel" end module ActiveModel module Validations class EmailFormatValidator < EachValidator def validate_each(record, attribute, value) - (ValidatesEmailFormatOf.validate_email_format(value, options.merge(generate_message: true)) || []).each do |error| + (ValidatesEmailFormatOf.validate_email_format(value, options) || []).each do |error| record.errors.add(attribute, error) end end end module HelperMethods def validates_email_format_of(*attr_names) validates_with EmailFormatValidator, _merge_attributes(attr_names) end end end end
validates-email-format-of/validates_email_format_of
0467b3fb131d21c58605e83ba8ab1fc0f99ee141
Improve specs to allow inspecting the subject model
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index d6cc154..8b96462 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,25 +1,27 @@ require "active_model" require "active_support" require "pry" require "byebug" RSpec::Matchers.define :have_errors_on_email do - match do |actual| + match do |user| + actual = user.errors.full_messages + expect(user.errors.added?(:email, ValidatesEmailFormatOf::ERROR_MESSAGE_I18N_KEY)) expect(actual).not_to be_nil, "#{actual} should not be nil" expect(actual).not_to be_empty, "#{actual} should not be empty" expect(actual.size).to eq(@reasons.size), "#{actual} should have #{@reasons.size} elements" @reasons.each do |reason| reason = "Email #{reason}" expect(actual).to include(reason), "#{actual} should contain #{reason}" end end chain :because do |reason| (@reasons ||= []) << reason end chain :and_because do |reason| (@reasons ||= []) << reason end - match_when_negated do |actual| - expect(actual).to(be_empty) + match_when_negated do |user| + expect(user.errors).to(be_empty) end end diff --git a/spec/validates_email_format_of_spec.rb b/spec/validates_email_format_of_spec.rb index 9da610f..236ea81 100644 --- a/spec/validates_email_format_of_spec.rb +++ b/spec/validates_email_format_of_spec.rb @@ -1,391 +1,395 @@ require "#{__dir__}/spec_helper" require "validates_email_format_of" RSpec.configure do |config| config.before(:suite) do ValidatesEmailFormatOf.load_i18n_locales I18n.enforce_available_locales = false end end describe ValidatesEmailFormatOf do subject do |example| user = Class.new do def initialize(email) @email = email.freeze end attr_reader :email include ActiveModel::Validations validates_email_format_of :email, example.example_group_instance.options def self.model_name ActiveModel::Name.new(self, nil, "User") end end - user.new(example.example_group_instance.email).tap(&:valid?).errors.full_messages + user.new(example.example_group_instance.email).tap(&:valid?) end let(:options) { {} } let(:email) { |example| example.example_group.description } shared_examples_for :all_specs do [ "valid@example.com", "Valid@test.example.com", "valid+valid123@test.example.com", "valid_valid123@test.example.com", "valid-valid+123@test.example.co.uk", "valid-valid+1.23@test.example.com.au", "valid@1example.com", "valid@example.co.uk", "v@example.com", "valid@example.ca", "valid_@example.com", "valid123.456@example.org", "valid123.456@example.travel", "valid123.456@example.museum", "valid@example.mobi", "valid@example.info", "valid-@example.com", "fake@p-t.k12.ok.us", # allow single character domain parts "valid@mail.x.example.com", "valid@x.com", "valid@example.w-dash.sch.uk", # from RFC 3696, page 6 "customer/department=shipping@example.com", "$A12345@example.com", "!def!xyz%abc@example.com", "_somename@example.com", # apostrophes "test'test@example.com", # punycode domain names "test@xn--bcher-kva.ch", "test@example.xn--0zwm56d", # IDN domains, "test@exämple.com", "test@пример.рф", "test@почта.бел", "test@192.192.192.1", # Allow quoted characters. Valid according to http://www.rfc-editor.org/errata_search.php?rfc=3696 '"Abc\@def"@example.com', "\"quote\".dotatom.\"otherquote\"@example.com", '"Quote(Only".Chars@wier.de', "\"much.more unusual\"@example.com", "\"very.unusual.@.unusual.com\"@example.com", '"very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual"@strange.example.com', '"()<>[]:,;@\"!#$%&*+-/=?^_`{}| ~ ? ^_`{}|~.a"@example.org', '"Fred\ Bloggs"@example.com', '"Joe.\\Blow"@example.com', # Balanced quoted characters %("example\\\\\\""@example.com), %("example\\\\"@example.com), "(leading comment)email@example.com", "(nested (comment))email@example.com", "email(trailing comment)@example.com" ].each do |address| describe address do it { should_not have_errors_on_email } end end [ "no_at_symbol", "multiple@at@symbols.com", "invalid@example-com", # period can not start local part ".invalid@example.com", # period can not end local part "invalid.@example.com", # period can not appear twice consecutively in local part "invali..d@example.com", # should not allow underscores in domain names "invalid@ex_mple.com", "invalid@e..example.com", "invalid@p-t..example.com", "invalid@example.com.", "invalid@example.com_", "invalid@example.com-", "invalid-example.com", "invalid@example.b#r.com", "just\"not\"right@example.com", "invalid@example.c", "invali d@example.com", # TLD can not be only numeric "invalid@example.123", # unclosed quote "\"a-17180061943-10618354-1993365053@example.com", # too many special chars used to cause the regexp to hang "-+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++@foo", "invalidexample.com", # should not allow special chars after a period in the domain "local@sub.)domain.com", "local@sub.#domain.com", # one at a time "foo@example.com\nexample@gmail.com", "invalid@example.", "\"foo\\\\\"\"@bar.com", "foo@mail.com\r\nfoo@mail.com", "@example.com", "foo@", "foo", "Iñtërnâtiônàlizætiøn@hasnt.happened.to.email", # Escaped characters with quotes. From http://tools.ietf.org/html/rfc3696, page 5. Corrected in http://www.rfc-editor.org/errata_search.php?rfc=3696 'Fred\ Bloggs_@example.com', 'Abc\@def+@example.com', 'Joe.\\Blow@example.com', # Unbalanced quoted characters %("example\\\\""example.com), "\nnewline@example.com", " spacesbefore@example.com", "spacesafter@example.com ", "(unbalancedcomment@example.com" ].each do |address| describe address do it { should have_errors_on_email.because("does not appear to be a valid email address") } end end describe do shared_examples_for :local_length_limit do |limit| describe "#{"a" * limit}@example.com" do it { should_not have_errors_on_email } end describe "#{"a" * (limit + 1)}@example.com" do it { should have_errors_on_email.because("does not appear to be a valid email address") } end end describe "when using default" do it_should_behave_like :local_length_limit, 64 end describe "when overriding defaults" do let(:options) { {local_length: 20} } it_should_behave_like :local_length_limit, 20 end end describe do shared_examples_for :domain_length_limit do |limit| describe "user@#{"a." * (limit / 2 - 3)}com" do it { should_not have_errors_on_email } end describe "user@#{"a." * (limit / 2 + 1)}com" do it { should have_errors_on_email.because("does not appear to be a valid email address") } end end describe "when using default" do it_should_behave_like :domain_length_limit, 255 end describe "when overriding defaults" do let(:options) { {domain_length: 100} } it_should_behave_like :domain_length_limit, 100 end end describe "custom error messages" do describe "invalid@example." do let(:options) { {message: "just because I don't like you"} } it { should have_errors_on_email.because("just because I don't like you") } end end describe "when idn support is disabled" do before(:each) do allow(SimpleIDN).to receive(:to_ascii).never end let(:options) { {idn: false} } describe "test@exämple.com" do it { should have_errors_on_email.because("does not appear to be a valid email address") } end end describe "when idn support is enabled" do before(:each) do allow(SimpleIDN).to receive(:to_ascii).once.with("exämple.com").and_return("xn--exmple-cua.com") end let(:options) { {idn: true} } describe "test@exämple.com" do it { should_not have_errors_on_email } end end describe "mx record" do domain = "example.com" email = "valid@#{domain}" describe "when testing" do let(:dns) { double(Resolv::DNS) } let(:mx_record) { [double] } let(:a_record) { [double] } before(:each) do allow(Resolv::DNS).to receive(:open).and_yield(dns) allow(dns).to receive(:"timeouts=").with(3).once allow(dns).to receive(:getresources).with(domain, Resolv::DNS::Resource::IN::MX).once.and_return(mx_record) allow(dns).to receive(:getresources).with(domain, Resolv::DNS::Resource::IN::A).once.and_return(a_record) end let(:options) { {check_mx: true, check_mx_timeout: 3} } describe "and only an mx record is found" do let(:a_record) { [] } describe email do it { should_not have_errors_on_email } end end describe "and only an a record is found" do let(:mx_record) { [] } describe email do it { should_not have_errors_on_email } end end describe "and both an mx record and an a record are found" do describe email do it { should_not have_errors_on_email } end end describe "and neither an mx record nor an a record is found" do let(:a_record) { [] } let(:mx_record) { [] } describe email do it { should have_errors_on_email.because("is not routable") } + it "adds the i18n key" do + subject.errors.added?(:email, ValidatesEmailFormatOf::ERROR_MX_MESSAGE_I18N_KEY) + end end describe "with a custom error message" do let(:options) { {check_mx: true, mx_message: "There ain't no such domain!"} } describe email do it { should have_errors_on_email.because("There ain't no such domain!") } end end + describe "i18n" do before(:each) do allow(I18n.config).to receive(:locale).and_return(locale) end describe "present locale" do let(:locale) { :pl } describe email do it { should have_errors_on_email.because("jest nieosiągalny") } end end end end end describe "when not testing" do before(:each) { allow(Resolv::DNS).to receive(:open).never } describe "by default" do describe email do it { should_not have_errors_on_email } end end describe "explicitly" do describe email do let(:options) { {check_mx: false} } it { should_not have_errors_on_email } end end end describe "without mocks" do describe email do let(:options) { {check_mx: true} } it { should_not have_errors_on_email } end end end describe "mx record for internationalized domain" do domain = "пример.рф" email = "valid@#{domain}" describe "when idn support is enabled" do let(:dns) { double(Resolv::DNS) } let(:options) { {check_mx: true, idn: true} } before(:each) do allow(Resolv::DNS).to receive(:open).and_yield(dns) allow(dns).to receive(:"timeouts=").with(3).once allow(dns).to receive(:getresources).with(SimpleIDN.to_ascii(domain), Resolv::DNS::Resource::IN::A).once.and_return([double]) allow(dns).to receive(:getresources).with(SimpleIDN.to_ascii(domain), Resolv::DNS::Resource::IN::MX).once.and_return([double]) end describe email do it { should_not have_errors_on_email } end end describe "when idn support is disabled" do let(:options) { {check_mx: true, idn: false} } describe "test@пример.рф" do let(:domain) { "exämple.com" } it { should have_errors_on_email.because("does not appear to be a valid email address") } end end end describe "custom regex" do let(:options) { {with: /[0-9]+@[0-9]+/} } describe "012345@789" do it { should_not have_errors_on_email } end describe "valid@example.com" do it { should have_errors_on_email.because("does not appear to be a valid email address") } end end describe "i18n" do before(:each) do allow(I18n.config).to receive(:locale).and_return(locale) end describe "present locale" do let(:locale) { :pl } describe "invalid@exmaple." do it { should have_errors_on_email.because("nieprawidłowy adres email") } end end end end it_should_behave_like :all_specs describe "validation without ActiveModel" do subject do ValidatesEmailFormatOf.validate_email_format(email.freeze, options) end describe "valid@example.com" do it { should be_nil } end describe "custom error messages" do describe "invalid@example." do let(:options) { {message: "just because I don't like you"} } it { should match_array(["just because I don't like you"]) } end end describe "without i18n" do before(:each) { hide_const("I18n") } describe "invalid@exmaple." do it { should match_array(["does not appear to be valid"]) } end end end describe "shorthand ActiveModel validation" do subject do |example| user = Class.new do def initialize(email) @email = email.freeze end attr_reader :email include ActiveModel::Validations validates :email, email_format: example.example_group_instance.options def self.model_name ActiveModel::Name.new(self, nil, "User") end end - user.new(example.example_group_instance.email).tap(&:valid?).errors.full_messages + user.new(example.example_group_instance.email).tap(&:valid?) end it_should_behave_like :all_specs end end
validates-email-format-of/validates_email_format_of
6d57b47de9a9b455052e745e0128cf2fea126da9
Bump actions/checkout from 3 to 4
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 94bcf0e..90b0a2a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,66 +1,66 @@ name: CI on: - push - pull_request permissions: contents: read jobs: test: name: "Ruby ${{ matrix.ruby }}, Rails ${{ matrix.gemfile }}" runs-on: ubuntu-latest strategy: matrix: ruby: ["2.6", "2.7", "3.0", "3.1"] gemfile: ["4.2", "5.0", "5.1", "5.2", "6.0", "6.1", "7.0"] exclude: - gemfile: "4.2" ruby: "3.0" - gemfile: "4.2" ruby: "3.1" - gemfile: "5.0" ruby: "3.0" - gemfile: "5.0" ruby: "3.1" - gemfile: "5.1" ruby: "3.0" - gemfile: "5.1" ruby: "3.1" - gemfile: "5.2" ruby: "3.0" - gemfile: "5.2" ruby: "3.1" - gemfile: "7.0" ruby: "2.5" - gemfile: "7.0" ruby: "2.6" - gemfile: "7.0" ruby: "2.7" env: BUNDLE_GEMFILE: gemfiles/rails_${{ matrix.gemfile }}.gemfile RAILS_ENV: test steps: - - uses: actions/checkout@v3 + - uses: actions/checkout@v4 - name: "Install Ruby ${{ matrix.ruby }}" # To automatically get bug fixes and new Ruby versions for ruby/setup-ruby, # change this to (see https://github.com/ruby/setup-ruby#versioning): # uses: ruby/setup-ruby@v1 uses: ruby/setup-ruby@v1 with: bundler: 1 ruby-version: ${{ matrix.ruby }} bundler-cache: true # runs 'bundle install' and caches installed gems automatically - name: Run specs run: bundle exec rspec - name: Run standard.rb run: bundle exec rake standard if: ${{ ! startsWith(matrix.ruby, '2.') }}
validates-email-format-of/validates_email_format_of
bce4ca9151f34b1ec567eaca87e6b53ad1bdf4e3
Reduce dependabot frequency
diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 5ace460..8ac6b8c 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -1,6 +1,6 @@ version: 2 updates: - package-ecosystem: "github-actions" directory: "/" schedule: - interval: "weekly" + interval: "monthly"
validates-email-format-of/validates_email_format_of
03ed2f8a8d529c3230548a84974cb91f5e3c40a7
Remove redundant regexp escapes
diff --git a/lib/validates_email_format_of.rb b/lib/validates_email_format_of.rb index f207855..f742e32 100644 --- a/lib/validates_email_format_of.rb +++ b/lib/validates_email_format_of.rb @@ -1,308 +1,308 @@ require "validates_email_format_of/version" require "simpleidn" module ValidatesEmailFormatOf def self.load_i18n_locales require "i18n" I18n.load_path += Dir.glob(File.expand_path(File.join(File.dirname(__FILE__), "..", "config", "locales", "*.yml"))) end require "resolv" # Characters that are allowed in to appear in the local part unquoted # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.3 # # An addr-spec is a specific Internet identifier that contains a # locally interpreted string followed by the at-sign character ("@", # ASCII value 64) followed by an Internet domain. The locally # interpreted string is either a quoted-string or a dot-atom. If the # string can be represented as a dot-atom (that is, it contains no # characters other than atext characters or "." surrounded by atext # characters), then the dot-atom form SHOULD be used and the quoted- # string form SHOULD NOT be used. Comments and folding white space # SHOULD NOT be used around the "@" in the addr-spec. # # atext = ALPHA / DIGIT / # "!" / "#" / "$" / "%" / "&" / "'" / "*" / # "+" / "-" / "/" / "=" / "?" / "^" / "_" / # "`" / "{" / "|" / "}" / "~" # dot-atom-text = 1*atext *("." 1*atext) # dot-atom = [CFWS] dot-atom-text [CFWS] ATEXT = /\A[A-Z0-9!\#$%&'*\-\/=?+\^_`{|}~]\z/i # Characters that are allowed to appear unquoted in comments # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.2 # # ctext = %d33-39 / %d42-91 / %d93-126 # ccontent = ctext / quoted-pair / comment # comment = "(" *([FWS] ccontent) [FWS] ")" # CFWS = (1*([FWS] comment) [FWS]) / FWS CTEXT = /\A[#{Regexp.escape([33..39, 42..91, 93..126].map { |ascii_range| ascii_range.map(&:chr) }.flatten.join)}\s]/i # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.4 # # Strings of characters that include characters other than those # allowed in atoms can be represented in a quoted string format, where # the characters are surrounded by quote (DQUOTE, ASCII value 34) # characters. # # qtext = %d33 / ; Printable US-ASCII # %d35-91 / ; characters not including # %d93-126 / ; "\" or the quote character # obs-qtext # # qcontent = qtext / quoted-pair # quoted-string = [CFWS] # DQUOTE *([FWS] qcontent) [FWS] DQUOTE # [CFWS] QTEXT = /\A[#{Regexp.escape([33..33, 35..91, 93..126].map { |ascii_range| ascii_range.map(&:chr) }.flatten.join)}\s]/i IP_OCTET = /\A[0-9]+\Z/ # From https://datatracker.ietf.org/doc/html/rfc1035#section-2.3.1 # # > The labels must follow the rules for ARPANET host names. They must # > start with a letter, end with a letter or digit, and have as interior # > characters only letters, digits, and hyphen. There are also some # > restrictions on the length. Labels must be 63 characters or less. # # <label> | <subdomain> "." <label> # <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ] # <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str> # <let-dig-hyp> ::= <let-dig> | "-" # <let-dig> ::= <letter> | <digit> # # Additionally, from https://datatracker.ietf.org/doc/html/rfc1123#section-2.1 # # > One aspect of host name syntax is hereby changed: the # > restriction on the first character is relaxed to allow either a # > letter or a digit. Host software MUST support this more liberal # > syntax. - DOMAIN_PART_LABEL = /\A[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9]?\Z/ + DOMAIN_PART_LABEL = /\A[A-Za-z0-9][A-Za-z0-9-]*[A-Za-z0-9]?\Z/ # From https://tools.ietf.org/id/draft-liman-tld-names-00.html#rfc.section.2 # # > A TLD label MUST be at least two characters long and MAY be as long as 63 characters - # > not counting any leading or trailing periods (.). It MUST consist of only ASCII characters # > from the groups "letters" (A-Z), "digits" (0-9) and "hyphen" (-), and it MUST start with an # > ASCII "letter", and it MUST NOT end with a "hyphen". Upper and lower case MAY be mixed at random, # > since DNS lookups are case-insensitive. # # tldlabel = ALPHA *61(ldh) ld # ldh = ld / "-" # ld = ALPHA / DIGIT # ALPHA = %x41-5A / %x61-7A ; A-Z / a-z # DIGIT = %x30-39 ; 0-9 - DOMAIN_PART_TLD = /\A[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9]\Z/ + DOMAIN_PART_TLD = /\A[A-Za-z][A-Za-z0-9-]*[A-Za-z0-9]\Z/ def self.validate_email_domain(email, idn: true, check_mx_timeout: 3) domain = email.to_s.downcase.match(/@(.+)/)[1] domain = SimpleIDN.to_ascii(domain) if idn Resolv::DNS.open do |dns| dns.timeouts = check_mx_timeout @mx = dns.getresources(domain, Resolv::DNS::Resource::IN::MX) + dns.getresources(domain, Resolv::DNS::Resource::IN::A) end @mx.size > 0 end DEFAULT_MESSAGE = "does not appear to be valid" DEFAULT_MX_MESSAGE = "is not routable" ERROR_MESSAGE_I18N_KEY = :invalid_email_address ERROR_MX_MESSAGE_I18N_KEY = :email_address_not_routable def self.default_message defined?(I18n) ? I18n.t(ERROR_MESSAGE_I18N_KEY, scope: [:activemodel, :errors, :messages], default: DEFAULT_MESSAGE) : DEFAULT_MESSAGE end # Validates whether the specified value is a valid email address. Returns nil if the value is valid, otherwise returns an array # containing one or more validation error messages. # # Configuration options: # * <tt>message</tt> - A custom error message (default is: "does not appear to be valid") # * <tt>check_mx</tt> - Check for MX records (default is false) # * <tt>check_mx_timeout</tt> - Timeout in seconds for checking MX records before a `ResolvTimeout` is raised (default is 3) # * <tt>idn</tt> - Enable or disable Internationalized Domain Names (default is true) # * <tt>mx_message</tt> - A custom error message when an MX record validation fails (default is: "is not routable.") # * <tt>local_length</tt> Maximum number of characters allowed in the local part (default is 64) # * <tt>domain_length</tt> Maximum number of characters allowed in the domain part (default is 255) # * <tt>generate_message</tt> Return the I18n key of the error message instead of the error message itself (default is false) def self.validate_email_format(email, options = {}) default_options = {message: options[:generate_message] ? ERROR_MESSAGE_I18N_KEY : default_message, check_mx: false, check_mx_timeout: 3, idn: true, mx_message: if options[:generate_message] ERROR_MX_MESSAGE_I18N_KEY else (defined?(I18n) ? I18n.t(ERROR_MX_MESSAGE_I18N_KEY, scope: [:activemodel, :errors, :messages], default: DEFAULT_MX_MESSAGE) : DEFAULT_MX_MESSAGE) end, domain_length: 255, local_length: 64, generate_message: false} opts = options.merge(default_options) { |key, old, new| old } # merge the default options into the specified options, retaining all specified options begin domain, local = email.reverse.split("@", 2) rescue return [opts[:message]] end # need local and domain parts return [opts[:message]] unless local && !local.empty? && domain && !domain.empty? # check lengths return [opts[:message]] unless domain.length <= opts[:domain_length] && local.length <= opts[:local_length] local.reverse! domain.reverse! if opts.has_key?(:with) # holdover from versions <= 1.4.7 deprecation_warn(":with option is deprecated and will be removed in the next version") return [opts[:message]] unless email&.match?(opts[:with]) else return [opts[:message]] unless validate_local_part_syntax(local) && validate_domain_part_syntax(domain, idn: opts[:idn]) end if opts[:check_mx] && !validate_email_domain(email, check_mx_timeout: opts[:check_mx_timeout], idn: opts[:idn]) return [opts[:mx_message]] end nil # represents no validation errors end def self.validate_local_part_syntax(local) in_quoted_pair = false in_quoted_string = false comment_depth = 0 # The local part is made up of dot-atom and quoted-string joined together by "." characters # # https://www.rfc-editor.org/rfc/rfc5322#section-3.4.1 # > local-part = dot-atom / quoted-string / obs-local-part # # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.3 # Both atom and dot-atom are interpreted as a single unit, comprising # > the string of characters that make it up. Semantically, the optional # > comments and FWS surrounding the rest of the characters are not part # > of the atom; the atom is only the run of atext characters in an atom, # > or the atext and "." characters in a dot-atom. joining_atoms = true (0..local.length - 1).each do |i| ord = local[i].ord # accept anything if it's got a backslash before it if in_quoted_pair in_quoted_pair = false next end # double quote delimits quoted strings if ord == 34 if in_quoted_string # leaving the quoted string in_quoted_string = false next elsif joining_atoms # are we allowed to enter a quoted string? in_quoted_string = true joining_atoms = false next else return false end end # period indicates we want to join atoms, e.g. `aaa.bbb."ccc"@example.com if ord == 46 return false if i.zero? return false if joining_atoms joining_atoms = true next end joining_atoms = false # quoted string logic must come before comment processing since a quoted string # may contain parens, e.g. `"name(a)"@example.com` if in_quoted_string next if QTEXT.match?(local[i]) end # opening paren to show we are going into a comment (CFWS) if ord == 40 comment_depth += 1 next end # closing paren if ord == 41 comment_depth -= 1 return false if comment_depth < 0 next end # backslash signifies the start of a quoted pair if ord == 92 # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.1 # > The only places in this specification where quoted-pair currently appears are # > ccontent, qcontent, and in obs-dtext in section 4. return false unless in_quoted_string || comment_depth > 0 in_quoted_pair = true next end if comment_depth > 0 next if CTEXT.match?(local[i]) elsif ATEXT.match?(local[i, 1]) next end return false end return false if in_quoted_pair # unbalanced quoted pair return false if in_quoted_string # unbalanced quotes return false unless comment_depth.zero? # unbalanced comment parens return false if joining_atoms # the last char we encountered was a period true end def self.validate_domain_part_syntax(domain, idn: true) domain = SimpleIDN.to_ascii(domain) if idn parts = domain.downcase.split(".", -1) return false if parts.length <= 1 # Only one domain part # ipv4 return true if parts.length == 4 && parts.all? { |part| part =~ IP_OCTET && part.to_i.between?(0, 255) } # From https://datatracker.ietf.org/doc/html/rfc3696#section-2 this is the recommended, pragmatic way to validate a domain name: # # > It is likely that the better strategy has now become to make the "at least one period" test, # > to verify LDH conformance (including verification that the apparent TLD name is not all-numeric), # > and then to use the DNS to determine domain name validity, rather than trying to maintain # > a local list of valid TLD names. # # We do a little bit more but not too much and validate the tokens but do not check against a list of valid TLDs. parts.each do |part| return false if part.nil? || part.empty? return false if part.length > 63 return false unless DOMAIN_PART_LABEL.match?(part) end return false unless DOMAIN_PART_TLD.match?(parts[-1]) true end def self.deprecation_warn(msg) if defined?(ActiveSupport::Deprecation) ActiveSupport::Deprecation.warn(msg) else warn end end end require "validates_email_format_of/active_model" if defined?(::ActiveModel) && !(ActiveModel::VERSION::MAJOR < 2 || (ActiveModel::VERSION::MAJOR == 2 && ActiveModel::VERSION::MINOR < 1)) require "validates_email_format_of/railtie" if defined?(::Rails::Railtie)
validates-email-format-of/validates_email_format_of
c71f6266026265cbf85fb16cf5a9b396a4dca492
Make IDN support configurable
diff --git a/README.md b/README.md index 364e63d..5ae8096 100644 --- a/README.md +++ b/README.md @@ -1,110 +1,111 @@ # validates_email_format_of [![Build Status](https://github.com/validates-email-format-of/validates_email_format_of/actions/workflows/ci.yml/badge.svg)]( https://github.com/validates-email-format-of/validates_email_format_of/actions/workflows/ci.yml?query=branch%3Amaster) A Ruby gem to validate email addresses against RFC 2822 and RFC 5322. ## Why this email validator? This gem is the O.G. email validation gem for Rails. It was started back in 2006. Why use this validator? Instead of trying to validate email addresses with one giant regular expression, this library parses addresses character by character. This lets us handle weird cases like [nested comments](https://www.rfc-editor.org/rfc/rfc5322#appendix-A.5). Gross but technically allowed. In reality, most email validating scripts will get you where you need to go. This library just aims to go all the way. ## Installation Add the gem to your Gemfile with: ```sh gem 'validates_email_format_of' ``` ### Usage in a Rails app ```ruby class Person < ActiveRecord::Base validates :email, :email_format => { :message => "is not looking good" } # OR validates_email_format_of :email, :message => "is not looking good" end ``` You can use the included `rspec` matcher as well: ```ruby require "validates_email_format_of/rspec_matcher" describe Person do it { should validate_email_format_of(:email).with_message("is not looking good") } end ``` ### Usage without Rails ```ruby # Optional, if you want error messages to be in your language ValidatesEmailFormatOf::load_i18n_locales I18n.locale = :pl ValidatesEmailFormatOf::validate_email_format("example@mydomain.com") # => nil ValidatesEmailFormatOf::validate_email_format("invalid@") # => ["does not appear to be a valid email address"] ``` ## Options | Option | Type | Description | | --- | --- | --- | | `:message` | String | A custom error message when the email format is invalid (default is: "does not appear to be a valid email address") | | `:check_mx` | Boolean | Check domain for a valid MX record (default is false) | | `:check_mx_timeout` | Integer | Timeout in seconds for checking MX records before a `ResolvTimeout` is raised (default is 3). | +| `:idn` | Boolean | Allowed internationalized domain names like `test@exämple.com` and `test@пример.рф`. Otherwise only domains that have already been converted to [Punycode](https://en.wikipedia.org/wiki/Punycode) are supported. (default is true) | | `:mx_message` | String | A custom error message when the domain does not match a valid MX record (default is: "is not routable"). Ignored unless :check_mx option is true. | | `:local_length` |Integer | Maximum number of characters allowed in the local part (everything before the '@') (default is 64) | | `:domain_length` | Integer | Maximum number of characters allowed in the domain part (everything after the '@') (default is 255) | | `:generate_message` | Boolean | Return the I18n key of the error message instead of the error message itself (default is false) | The standard ActiveModel validation options (`:on`, `:if`, `:unless`, `:allow_nil`, `:allow_blank`, etc...) all work as well when using the gem as part of a Rails application. ## Testing You can see our [current Ruby and Rails test matrix here](.github/workflows/ci.yml). To execute the unit tests against [all the Rails versions we support run](gemfiles/) <tt>bundle exec appraisal rspec</tt> or run against an individual version with <tt>bundle exec appraisal rails-6.0 rspec</tt>. ## Contributing If you think we're letting some rules about valid email formats slip through the cracks, don't just update the parser. Instead, add a failing test and demonstrate that the described email address should be treated differently. A link to an appropriate RFC is the best way to do this. Then change the gem code to make the test pass. ```ruby describe "i_think_this_is_not_a_v@lid_email_addre.ss" do # According to http://..., this email address IS NOT valid. it { should have_errors_on_email.because("does not appear to be valid") } end describe "i_think_this_is_a_v@lid_email_addre.ss" do # According to http://..., this email address IS valid. it { should_not have_errors_on_email } end ``` Yes, our Rspec syntax is that simple! ## Homepage * https://github.com/validates-email-format-of/validates_email_format_of ## Credits Written by Alex Dunae (dunae.ca), 2006-22. Many thanks to the plugin's recent contributors: https://github.com/alexdunae/validates_email_format_of/contributors Thanks to Francis Hwang (http://fhwang.net/) at Diversion Media for creating the 1.1 update. Thanks to Travis Sinnott for creating the 1.3 update. Thanks to Denis Ahearn at Riverock Technologies (http://www.riverocktech.com/) for creating the 1.4 update. Thanks to George Anderson (http://github.com/george) and 'history' (http://github.com/history) for creating the 1.4.1 update. Thanks to Isaac Betesh (https://github.com/betesh) for converting tests to Rspec and refactoring for version 1.6.0. diff --git a/lib/validates_email_format_of.rb b/lib/validates_email_format_of.rb index a1821bc..f207855 100644 --- a/lib/validates_email_format_of.rb +++ b/lib/validates_email_format_of.rb @@ -1,305 +1,308 @@ -# encoding: utf-8 require "validates_email_format_of/version" require "simpleidn" module ValidatesEmailFormatOf def self.load_i18n_locales require "i18n" I18n.load_path += Dir.glob(File.expand_path(File.join(File.dirname(__FILE__), "..", "config", "locales", "*.yml"))) end require "resolv" # Characters that are allowed in to appear in the local part unquoted # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.3 # # An addr-spec is a specific Internet identifier that contains a # locally interpreted string followed by the at-sign character ("@", # ASCII value 64) followed by an Internet domain. The locally # interpreted string is either a quoted-string or a dot-atom. If the # string can be represented as a dot-atom (that is, it contains no # characters other than atext characters or "." surrounded by atext # characters), then the dot-atom form SHOULD be used and the quoted- # string form SHOULD NOT be used. Comments and folding white space # SHOULD NOT be used around the "@" in the addr-spec. # # atext = ALPHA / DIGIT / # "!" / "#" / "$" / "%" / "&" / "'" / "*" / # "+" / "-" / "/" / "=" / "?" / "^" / "_" / # "`" / "{" / "|" / "}" / "~" # dot-atom-text = 1*atext *("." 1*atext) # dot-atom = [CFWS] dot-atom-text [CFWS] ATEXT = /\A[A-Z0-9!\#$%&'*\-\/=?+\^_`{|}~]\z/i # Characters that are allowed to appear unquoted in comments # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.2 # # ctext = %d33-39 / %d42-91 / %d93-126 # ccontent = ctext / quoted-pair / comment # comment = "(" *([FWS] ccontent) [FWS] ")" # CFWS = (1*([FWS] comment) [FWS]) / FWS CTEXT = /\A[#{Regexp.escape([33..39, 42..91, 93..126].map { |ascii_range| ascii_range.map(&:chr) }.flatten.join)}\s]/i # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.4 # # Strings of characters that include characters other than those # allowed in atoms can be represented in a quoted string format, where # the characters are surrounded by quote (DQUOTE, ASCII value 34) # characters. # # qtext = %d33 / ; Printable US-ASCII # %d35-91 / ; characters not including # %d93-126 / ; "\" or the quote character # obs-qtext # # qcontent = qtext / quoted-pair # quoted-string = [CFWS] # DQUOTE *([FWS] qcontent) [FWS] DQUOTE # [CFWS] QTEXT = /\A[#{Regexp.escape([33..33, 35..91, 93..126].map { |ascii_range| ascii_range.map(&:chr) }.flatten.join)}\s]/i IP_OCTET = /\A[0-9]+\Z/ # From https://datatracker.ietf.org/doc/html/rfc1035#section-2.3.1 # # > The labels must follow the rules for ARPANET host names. They must # > start with a letter, end with a letter or digit, and have as interior # > characters only letters, digits, and hyphen. There are also some # > restrictions on the length. Labels must be 63 characters or less. # # <label> | <subdomain> "." <label> # <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ] # <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str> # <let-dig-hyp> ::= <let-dig> | "-" # <let-dig> ::= <letter> | <digit> # # Additionally, from https://datatracker.ietf.org/doc/html/rfc1123#section-2.1 # # > One aspect of host name syntax is hereby changed: the # > restriction on the first character is relaxed to allow either a # > letter or a digit. Host software MUST support this more liberal # > syntax. DOMAIN_PART_LABEL = /\A[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9]?\Z/ # From https://tools.ietf.org/id/draft-liman-tld-names-00.html#rfc.section.2 # # > A TLD label MUST be at least two characters long and MAY be as long as 63 characters - # > not counting any leading or trailing periods (.). It MUST consist of only ASCII characters # > from the groups "letters" (A-Z), "digits" (0-9) and "hyphen" (-), and it MUST start with an # > ASCII "letter", and it MUST NOT end with a "hyphen". Upper and lower case MAY be mixed at random, # > since DNS lookups are case-insensitive. # # tldlabel = ALPHA *61(ldh) ld # ldh = ld / "-" # ld = ALPHA / DIGIT # ALPHA = %x41-5A / %x61-7A ; A-Z / a-z # DIGIT = %x30-39 ; 0-9 DOMAIN_PART_TLD = /\A[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9]\Z/ - def self.validate_email_domain(email, check_mx_timeout: 3) - domain = SimpleIDN.to_ascii(email.to_s.downcase.match(/@(.+)/)[1]) + def self.validate_email_domain(email, idn: true, check_mx_timeout: 3) + domain = email.to_s.downcase.match(/@(.+)/)[1] + domain = SimpleIDN.to_ascii(domain) if idn Resolv::DNS.open do |dns| dns.timeouts = check_mx_timeout @mx = dns.getresources(domain, Resolv::DNS::Resource::IN::MX) + dns.getresources(domain, Resolv::DNS::Resource::IN::A) end @mx.size > 0 end DEFAULT_MESSAGE = "does not appear to be valid" DEFAULT_MX_MESSAGE = "is not routable" ERROR_MESSAGE_I18N_KEY = :invalid_email_address ERROR_MX_MESSAGE_I18N_KEY = :email_address_not_routable def self.default_message defined?(I18n) ? I18n.t(ERROR_MESSAGE_I18N_KEY, scope: [:activemodel, :errors, :messages], default: DEFAULT_MESSAGE) : DEFAULT_MESSAGE end # Validates whether the specified value is a valid email address. Returns nil if the value is valid, otherwise returns an array # containing one or more validation error messages. # # Configuration options: # * <tt>message</tt> - A custom error message (default is: "does not appear to be valid") # * <tt>check_mx</tt> - Check for MX records (default is false) # * <tt>check_mx_timeout</tt> - Timeout in seconds for checking MX records before a `ResolvTimeout` is raised (default is 3) + # * <tt>idn</tt> - Enable or disable Internationalized Domain Names (default is true) # * <tt>mx_message</tt> - A custom error message when an MX record validation fails (default is: "is not routable.") # * <tt>local_length</tt> Maximum number of characters allowed in the local part (default is 64) # * <tt>domain_length</tt> Maximum number of characters allowed in the domain part (default is 255) # * <tt>generate_message</tt> Return the I18n key of the error message instead of the error message itself (default is false) def self.validate_email_format(email, options = {}) default_options = {message: options[:generate_message] ? ERROR_MESSAGE_I18N_KEY : default_message, check_mx: false, check_mx_timeout: 3, + idn: true, mx_message: if options[:generate_message] ERROR_MX_MESSAGE_I18N_KEY else (defined?(I18n) ? I18n.t(ERROR_MX_MESSAGE_I18N_KEY, scope: [:activemodel, :errors, :messages], default: DEFAULT_MX_MESSAGE) : DEFAULT_MX_MESSAGE) end, domain_length: 255, local_length: 64, generate_message: false} opts = options.merge(default_options) { |key, old, new| old } # merge the default options into the specified options, retaining all specified options begin domain, local = email.reverse.split("@", 2) rescue return [opts[:message]] end # need local and domain parts return [opts[:message]] unless local && !local.empty? && domain && !domain.empty? # check lengths return [opts[:message]] unless domain.length <= opts[:domain_length] && local.length <= opts[:local_length] local.reverse! domain.reverse! if opts.has_key?(:with) # holdover from versions <= 1.4.7 deprecation_warn(":with option is deprecated and will be removed in the next version") return [opts[:message]] unless email&.match?(opts[:with]) else - return [opts[:message]] unless validate_local_part_syntax(local) && validate_domain_part_syntax(domain) + return [opts[:message]] unless validate_local_part_syntax(local) && validate_domain_part_syntax(domain, idn: opts[:idn]) end - if opts[:check_mx] && !validate_email_domain(email, check_mx_timeout: opts[:check_mx_timeout]) + if opts[:check_mx] && !validate_email_domain(email, check_mx_timeout: opts[:check_mx_timeout], idn: opts[:idn]) return [opts[:mx_message]] end nil # represents no validation errors end def self.validate_local_part_syntax(local) in_quoted_pair = false in_quoted_string = false comment_depth = 0 # The local part is made up of dot-atom and quoted-string joined together by "." characters # # https://www.rfc-editor.org/rfc/rfc5322#section-3.4.1 # > local-part = dot-atom / quoted-string / obs-local-part # # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.3 # Both atom and dot-atom are interpreted as a single unit, comprising # > the string of characters that make it up. Semantically, the optional # > comments and FWS surrounding the rest of the characters are not part # > of the atom; the atom is only the run of atext characters in an atom, # > or the atext and "." characters in a dot-atom. joining_atoms = true (0..local.length - 1).each do |i| ord = local[i].ord # accept anything if it's got a backslash before it if in_quoted_pair in_quoted_pair = false next end # double quote delimits quoted strings if ord == 34 if in_quoted_string # leaving the quoted string in_quoted_string = false next elsif joining_atoms # are we allowed to enter a quoted string? in_quoted_string = true joining_atoms = false next else return false end end # period indicates we want to join atoms, e.g. `aaa.bbb."ccc"@example.com if ord == 46 return false if i.zero? return false if joining_atoms joining_atoms = true next end joining_atoms = false # quoted string logic must come before comment processing since a quoted string # may contain parens, e.g. `"name(a)"@example.com` if in_quoted_string next if QTEXT.match?(local[i]) end # opening paren to show we are going into a comment (CFWS) if ord == 40 comment_depth += 1 next end # closing paren if ord == 41 comment_depth -= 1 return false if comment_depth < 0 next end # backslash signifies the start of a quoted pair if ord == 92 # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.1 # > The only places in this specification where quoted-pair currently appears are # > ccontent, qcontent, and in obs-dtext in section 4. return false unless in_quoted_string || comment_depth > 0 in_quoted_pair = true next end if comment_depth > 0 next if CTEXT.match?(local[i]) elsif ATEXT.match?(local[i, 1]) next end return false end return false if in_quoted_pair # unbalanced quoted pair return false if in_quoted_string # unbalanced quotes return false unless comment_depth.zero? # unbalanced comment parens return false if joining_atoms # the last char we encountered was a period true end - def self.validate_domain_part_syntax(domain) + def self.validate_domain_part_syntax(domain, idn: true) + domain = SimpleIDN.to_ascii(domain) if idn parts = domain.downcase.split(".", -1) return false if parts.length <= 1 # Only one domain part # ipv4 return true if parts.length == 4 && parts.all? { |part| part =~ IP_OCTET && part.to_i.between?(0, 255) } # From https://datatracker.ietf.org/doc/html/rfc3696#section-2 this is the recommended, pragmatic way to validate a domain name: # # > It is likely that the better strategy has now become to make the "at least one period" test, # > to verify LDH conformance (including verification that the apparent TLD name is not all-numeric), # > and then to use the DNS to determine domain name validity, rather than trying to maintain # > a local list of valid TLD names. # # We do a little bit more but not too much and validate the tokens but do not check against a list of valid TLDs. parts.each do |part| return false if part.nil? || part.empty? return false if part.length > 63 return false unless DOMAIN_PART_LABEL.match?(part) end return false unless DOMAIN_PART_TLD.match?(parts[-1]) true end def self.deprecation_warn(msg) if defined?(ActiveSupport::Deprecation) ActiveSupport::Deprecation.warn(msg) else warn end end end require "validates_email_format_of/active_model" if defined?(::ActiveModel) && !(ActiveModel::VERSION::MAJOR < 2 || (ActiveModel::VERSION::MAJOR == 2 && ActiveModel::VERSION::MINOR < 1)) require "validates_email_format_of/railtie" if defined?(::Rails::Railtie) diff --git a/spec/validates_email_format_of_spec.rb b/spec/validates_email_format_of_spec.rb index fc9912b..9da610f 100644 --- a/spec/validates_email_format_of_spec.rb +++ b/spec/validates_email_format_of_spec.rb @@ -1,334 +1,391 @@ require "#{__dir__}/spec_helper" require "validates_email_format_of" RSpec.configure do |config| config.before(:suite) do ValidatesEmailFormatOf.load_i18n_locales I18n.enforce_available_locales = false end end describe ValidatesEmailFormatOf do subject do |example| user = Class.new do def initialize(email) @email = email.freeze end attr_reader :email include ActiveModel::Validations validates_email_format_of :email, example.example_group_instance.options def self.model_name ActiveModel::Name.new(self, nil, "User") end end user.new(example.example_group_instance.email).tap(&:valid?).errors.full_messages end let(:options) { {} } let(:email) { |example| example.example_group.description } shared_examples_for :all_specs do [ "valid@example.com", "Valid@test.example.com", "valid+valid123@test.example.com", "valid_valid123@test.example.com", "valid-valid+123@test.example.co.uk", "valid-valid+1.23@test.example.com.au", "valid@1example.com", "valid@example.co.uk", "v@example.com", "valid@example.ca", "valid_@example.com", "valid123.456@example.org", "valid123.456@example.travel", "valid123.456@example.museum", "valid@example.mobi", "valid@example.info", "valid-@example.com", "fake@p-t.k12.ok.us", # allow single character domain parts "valid@mail.x.example.com", "valid@x.com", "valid@example.w-dash.sch.uk", # from RFC 3696, page 6 "customer/department=shipping@example.com", "$A12345@example.com", "!def!xyz%abc@example.com", "_somename@example.com", # apostrophes "test'test@example.com", - # international domain names + # punycode domain names "test@xn--bcher-kva.ch", "test@example.xn--0zwm56d", + + # IDN domains, + "test@exämple.com", + "test@пример.рф", + "test@почта.бел", + "test@192.192.192.1", # Allow quoted characters. Valid according to http://www.rfc-editor.org/errata_search.php?rfc=3696 '"Abc\@def"@example.com', "\"quote\".dotatom.\"otherquote\"@example.com", '"Quote(Only".Chars@wier.de', "\"much.more unusual\"@example.com", "\"very.unusual.@.unusual.com\"@example.com", '"very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual"@strange.example.com', '"()<>[]:,;@\"!#$%&*+-/=?^_`{}| ~ ? ^_`{}|~.a"@example.org', '"Fred\ Bloggs"@example.com', '"Joe.\\Blow"@example.com', # Balanced quoted characters %("example\\\\\\""@example.com), %("example\\\\"@example.com), "(leading comment)email@example.com", "(nested (comment))email@example.com", "email(trailing comment)@example.com" ].each do |address| describe address do it { should_not have_errors_on_email } end end [ "no_at_symbol", "multiple@at@symbols.com", "invalid@example-com", # period can not start local part ".invalid@example.com", # period can not end local part "invalid.@example.com", # period can not appear twice consecutively in local part "invali..d@example.com", # should not allow underscores in domain names "invalid@ex_mple.com", "invalid@e..example.com", "invalid@p-t..example.com", "invalid@example.com.", "invalid@example.com_", "invalid@example.com-", "invalid-example.com", "invalid@example.b#r.com", "just\"not\"right@example.com", "invalid@example.c", "invali d@example.com", # TLD can not be only numeric "invalid@example.123", # unclosed quote "\"a-17180061943-10618354-1993365053@example.com", # too many special chars used to cause the regexp to hang "-+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++@foo", "invalidexample.com", # should not allow special chars after a period in the domain "local@sub.)domain.com", "local@sub.#domain.com", # one at a time "foo@example.com\nexample@gmail.com", "invalid@example.", "\"foo\\\\\"\"@bar.com", "foo@mail.com\r\nfoo@mail.com", "@example.com", "foo@", "foo", "Iñtërnâtiônàlizætiøn@hasnt.happened.to.email", # Escaped characters with quotes. From http://tools.ietf.org/html/rfc3696, page 5. Corrected in http://www.rfc-editor.org/errata_search.php?rfc=3696 'Fred\ Bloggs_@example.com', 'Abc\@def+@example.com', 'Joe.\\Blow@example.com', # Unbalanced quoted characters %("example\\\\""example.com), "\nnewline@example.com", " spacesbefore@example.com", "spacesafter@example.com ", "(unbalancedcomment@example.com" ].each do |address| describe address do it { should have_errors_on_email.because("does not appear to be a valid email address") } end end describe do shared_examples_for :local_length_limit do |limit| describe "#{"a" * limit}@example.com" do it { should_not have_errors_on_email } end describe "#{"a" * (limit + 1)}@example.com" do it { should have_errors_on_email.because("does not appear to be a valid email address") } end end describe "when using default" do it_should_behave_like :local_length_limit, 64 end describe "when overriding defaults" do let(:options) { {local_length: 20} } it_should_behave_like :local_length_limit, 20 end end describe do shared_examples_for :domain_length_limit do |limit| describe "user@#{"a." * (limit / 2 - 3)}com" do it { should_not have_errors_on_email } end describe "user@#{"a." * (limit / 2 + 1)}com" do it { should have_errors_on_email.because("does not appear to be a valid email address") } end end describe "when using default" do it_should_behave_like :domain_length_limit, 255 end describe "when overriding defaults" do let(:options) { {domain_length: 100} } it_should_behave_like :domain_length_limit, 100 end end describe "custom error messages" do describe "invalid@example." do let(:options) { {message: "just because I don't like you"} } it { should have_errors_on_email.because("just because I don't like you") } end end + describe "when idn support is disabled" do + before(:each) do + allow(SimpleIDN).to receive(:to_ascii).never + end + let(:options) { {idn: false} } + describe "test@exämple.com" do + it { should have_errors_on_email.because("does not appear to be a valid email address") } + end + end + + describe "when idn support is enabled" do + before(:each) do + allow(SimpleIDN).to receive(:to_ascii).once.with("exämple.com").and_return("xn--exmple-cua.com") + end + let(:options) { {idn: true} } + describe "test@exämple.com" do + it { should_not have_errors_on_email } + end + end + describe "mx record" do domain = "example.com" email = "valid@#{domain}" describe "when testing" do let(:dns) { double(Resolv::DNS) } let(:mx_record) { [double] } let(:a_record) { [double] } before(:each) do allow(Resolv::DNS).to receive(:open).and_yield(dns) allow(dns).to receive(:"timeouts=").with(3).once allow(dns).to receive(:getresources).with(domain, Resolv::DNS::Resource::IN::MX).once.and_return(mx_record) allow(dns).to receive(:getresources).with(domain, Resolv::DNS::Resource::IN::A).once.and_return(a_record) end let(:options) { {check_mx: true, check_mx_timeout: 3} } describe "and only an mx record is found" do let(:a_record) { [] } describe email do it { should_not have_errors_on_email } end end describe "and only an a record is found" do let(:mx_record) { [] } describe email do it { should_not have_errors_on_email } end end describe "and both an mx record and an a record are found" do describe email do it { should_not have_errors_on_email } end end describe "and neither an mx record nor an a record is found" do let(:a_record) { [] } let(:mx_record) { [] } describe email do it { should have_errors_on_email.because("is not routable") } end describe "with a custom error message" do let(:options) { {check_mx: true, mx_message: "There ain't no such domain!"} } describe email do it { should have_errors_on_email.because("There ain't no such domain!") } end end describe "i18n" do before(:each) do allow(I18n.config).to receive(:locale).and_return(locale) end describe "present locale" do let(:locale) { :pl } describe email do it { should have_errors_on_email.because("jest nieosiągalny") } end end end end end + describe "when not testing" do before(:each) { allow(Resolv::DNS).to receive(:open).never } describe "by default" do describe email do it { should_not have_errors_on_email } end end describe "explicitly" do describe email do let(:options) { {check_mx: false} } it { should_not have_errors_on_email } end end end describe "without mocks" do describe email do let(:options) { {check_mx: true} } it { should_not have_errors_on_email } end end end + describe "mx record for internationalized domain" do + domain = "пример.рф" + email = "valid@#{domain}" + + describe "when idn support is enabled" do + let(:dns) { double(Resolv::DNS) } + let(:options) { {check_mx: true, idn: true} } + + before(:each) do + allow(Resolv::DNS).to receive(:open).and_yield(dns) + allow(dns).to receive(:"timeouts=").with(3).once + allow(dns).to receive(:getresources).with(SimpleIDN.to_ascii(domain), Resolv::DNS::Resource::IN::A).once.and_return([double]) + allow(dns).to receive(:getresources).with(SimpleIDN.to_ascii(domain), Resolv::DNS::Resource::IN::MX).once.and_return([double]) + end + + describe email do + it { should_not have_errors_on_email } + end + end + + describe "when idn support is disabled" do + let(:options) { {check_mx: true, idn: false} } + + describe "test@пример.рф" do + let(:domain) { "exämple.com" } + it { should have_errors_on_email.because("does not appear to be a valid email address") } + end + end + end + describe "custom regex" do let(:options) { {with: /[0-9]+@[0-9]+/} } describe "012345@789" do it { should_not have_errors_on_email } end describe "valid@example.com" do it { should have_errors_on_email.because("does not appear to be a valid email address") } end end describe "i18n" do before(:each) do allow(I18n.config).to receive(:locale).and_return(locale) end describe "present locale" do let(:locale) { :pl } describe "invalid@exmaple." do it { should have_errors_on_email.because("nieprawidłowy adres email") } end end end end it_should_behave_like :all_specs describe "validation without ActiveModel" do subject do ValidatesEmailFormatOf.validate_email_format(email.freeze, options) end describe "valid@example.com" do it { should be_nil } end describe "custom error messages" do describe "invalid@example." do let(:options) { {message: "just because I don't like you"} } it { should match_array(["just because I don't like you"]) } end end describe "without i18n" do before(:each) { hide_const("I18n") } describe "invalid@exmaple." do it { should match_array(["does not appear to be valid"]) } end end end describe "shorthand ActiveModel validation" do subject do |example| user = Class.new do def initialize(email) @email = email.freeze end attr_reader :email include ActiveModel::Validations validates :email, email_format: example.example_group_instance.options def self.model_name ActiveModel::Name.new(self, nil, "User") end end user.new(example.example_group_instance.email).tap(&:valid?).errors.full_messages end it_should_behave_like :all_specs end end
validates-email-format-of/validates_email_format_of
3f0de9073206fbfeeb91323159dae706ec66e442
CI: Skip StandardRb on EOL Ruby versions
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0e12f27..94bcf0e 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,65 +1,66 @@ name: CI on: - push - pull_request permissions: contents: read jobs: test: name: "Ruby ${{ matrix.ruby }}, Rails ${{ matrix.gemfile }}" runs-on: ubuntu-latest strategy: matrix: ruby: ["2.6", "2.7", "3.0", "3.1"] gemfile: ["4.2", "5.0", "5.1", "5.2", "6.0", "6.1", "7.0"] exclude: - gemfile: "4.2" ruby: "3.0" - gemfile: "4.2" ruby: "3.1" - gemfile: "5.0" ruby: "3.0" - gemfile: "5.0" ruby: "3.1" - gemfile: "5.1" ruby: "3.0" - gemfile: "5.1" ruby: "3.1" - gemfile: "5.2" ruby: "3.0" - gemfile: "5.2" ruby: "3.1" - gemfile: "7.0" ruby: "2.5" - gemfile: "7.0" ruby: "2.6" - gemfile: "7.0" ruby: "2.7" env: BUNDLE_GEMFILE: gemfiles/rails_${{ matrix.gemfile }}.gemfile RAILS_ENV: test steps: - uses: actions/checkout@v3 - name: "Install Ruby ${{ matrix.ruby }}" # To automatically get bug fixes and new Ruby versions for ruby/setup-ruby, # change this to (see https://github.com/ruby/setup-ruby#versioning): # uses: ruby/setup-ruby@v1 uses: ruby/setup-ruby@v1 with: bundler: 1 ruby-version: ${{ matrix.ruby }} bundler-cache: true # runs 'bundle install' and caches installed gems automatically - name: Run specs run: bundle exec rspec - name: Run standard.rb run: bundle exec rake standard + if: ${{ ! startsWith(matrix.ruby, '2.') }}
validates-email-format-of/validates_email_format_of
9999da992a715a4d5f921868b5c9de6b1d66fbb1
CI: tell dependabot to update GH Actions
diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..5ace460 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,6 @@ +version: 2 +updates: + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "weekly"
validates-email-format-of/validates_email_format_of
089ab75c3359f7d0543fb178aacefb77ea117c94
Fix Turkish locale
diff --git a/config/locales/tr.yml b/config/locales/tr.yml index 12e2949..5e68171 100644 --- a/config/locales/tr.yml +++ b/config/locales/tr.yml @@ -1,8 +1,8 @@ -en: +tr: activemodel: &errors errors: messages: invalid_email_address: 'geçerli bir eposta adresi değil' email_address_not_routable: 'ulaşılabilir değil' activerecord: <<: *errors
validates-email-format-of/validates_email_format_of
608d90362e1fedd612936acc7ade3dc65ddcb043
Fix a couple of typos in README.md
diff --git a/README.md b/README.md index 6998da3..364e63d 100644 --- a/README.md +++ b/README.md @@ -1,110 +1,110 @@ # validates_email_format_of [![Build Status](https://github.com/validates-email-format-of/validates_email_format_of/actions/workflows/ci.yml/badge.svg)]( https://github.com/validates-email-format-of/validates_email_format_of/actions/workflows/ci.yml?query=branch%3Amaster) A Ruby gem to validate email addresses against RFC 2822 and RFC 5322. ## Why this email validator? This gem is the O.G. email validation gem for Rails. It was started back in 2006. -Why use this validator? Instead of trying to validate email addresses with one giant regular expression, this library parses addresses character by character. This lets us handle weird cases likes [nested comments](https://www.rfc-editor.org/rfc/rfc5322#appendix-A.5). Gross but technically allowed. +Why use this validator? Instead of trying to validate email addresses with one giant regular expression, this library parses addresses character by character. This lets us handle weird cases like [nested comments](https://www.rfc-editor.org/rfc/rfc5322#appendix-A.5). Gross but technically allowed. In reality, most email validating scripts will get you where you need to go. This library just aims to go all the way. ## Installation Add the gem to your Gemfile with: ```sh gem 'validates_email_format_of' ``` ### Usage in a Rails app ```ruby class Person < ActiveRecord::Base validates :email, :email_format => { :message => "is not looking good" } # OR validates_email_format_of :email, :message => "is not looking good" end ``` You can use the included `rspec` matcher as well: ```ruby require "validates_email_format_of/rspec_matcher" describe Person do it { should validate_email_format_of(:email).with_message("is not looking good") } end ``` -### Useage without Rails +### Usage without Rails ```ruby # Optional, if you want error messages to be in your language ValidatesEmailFormatOf::load_i18n_locales I18n.locale = :pl ValidatesEmailFormatOf::validate_email_format("example@mydomain.com") # => nil ValidatesEmailFormatOf::validate_email_format("invalid@") # => ["does not appear to be a valid email address"] ``` ## Options | Option | Type | Description | | --- | --- | --- | | `:message` | String | A custom error message when the email format is invalid (default is: "does not appear to be a valid email address") | | `:check_mx` | Boolean | Check domain for a valid MX record (default is false) | | `:check_mx_timeout` | Integer | Timeout in seconds for checking MX records before a `ResolvTimeout` is raised (default is 3). | | `:mx_message` | String | A custom error message when the domain does not match a valid MX record (default is: "is not routable"). Ignored unless :check_mx option is true. | | `:local_length` |Integer | Maximum number of characters allowed in the local part (everything before the '@') (default is 64) | | `:domain_length` | Integer | Maximum number of characters allowed in the domain part (everything after the '@') (default is 255) | | `:generate_message` | Boolean | Return the I18n key of the error message instead of the error message itself (default is false) | The standard ActiveModel validation options (`:on`, `:if`, `:unless`, `:allow_nil`, `:allow_blank`, etc...) all work as well when using the gem as part of a Rails application. ## Testing You can see our [current Ruby and Rails test matrix here](.github/workflows/ci.yml). To execute the unit tests against [all the Rails versions we support run](gemfiles/) <tt>bundle exec appraisal rspec</tt> or run against an individual version with <tt>bundle exec appraisal rails-6.0 rspec</tt>. ## Contributing If you think we're letting some rules about valid email formats slip through the cracks, don't just update the parser. Instead, add a failing test and demonstrate that the described email address should be treated differently. A link to an appropriate RFC is the best way to do this. Then change the gem code to make the test pass. ```ruby describe "i_think_this_is_not_a_v@lid_email_addre.ss" do # According to http://..., this email address IS NOT valid. it { should have_errors_on_email.because("does not appear to be valid") } end describe "i_think_this_is_a_v@lid_email_addre.ss" do # According to http://..., this email address IS valid. it { should_not have_errors_on_email } end ``` Yes, our Rspec syntax is that simple! ## Homepage * https://github.com/validates-email-format-of/validates_email_format_of ## Credits Written by Alex Dunae (dunae.ca), 2006-22. Many thanks to the plugin's recent contributors: https://github.com/alexdunae/validates_email_format_of/contributors Thanks to Francis Hwang (http://fhwang.net/) at Diversion Media for creating the 1.1 update. Thanks to Travis Sinnott for creating the 1.3 update. Thanks to Denis Ahearn at Riverock Technologies (http://www.riverocktech.com/) for creating the 1.4 update. Thanks to George Anderson (http://github.com/george) and 'history' (http://github.com/history) for creating the 1.4.1 update. Thanks to Isaac Betesh (https://github.com/betesh) for converting tests to Rspec and refactoring for version 1.6.0.
validates-email-format-of/validates_email_format_of
2224dfbf841d4d959ed2686b200f6c404b0a5c4e
Add Turkish locale
diff --git a/config/locales/tr.yml b/config/locales/tr.yml new file mode 100644 index 0000000..12e2949 --- /dev/null +++ b/config/locales/tr.yml @@ -0,0 +1,8 @@ +en: + activemodel: &errors + errors: + messages: + invalid_email_address: 'geçerli bir eposta adresi değil' + email_address_not_routable: 'ulaşılabilir değil' + activerecord: + <<: *errors
validates-email-format-of/validates_email_format_of
3972f3b9f0f8b09900c1debf6060cc352ec4e36e
Fix typo in README: useage -> usage
diff --git a/README.md b/README.md index 6998da3..9570a13 100644 --- a/README.md +++ b/README.md @@ -1,110 +1,110 @@ # validates_email_format_of [![Build Status](https://github.com/validates-email-format-of/validates_email_format_of/actions/workflows/ci.yml/badge.svg)]( https://github.com/validates-email-format-of/validates_email_format_of/actions/workflows/ci.yml?query=branch%3Amaster) A Ruby gem to validate email addresses against RFC 2822 and RFC 5322. ## Why this email validator? This gem is the O.G. email validation gem for Rails. It was started back in 2006. Why use this validator? Instead of trying to validate email addresses with one giant regular expression, this library parses addresses character by character. This lets us handle weird cases likes [nested comments](https://www.rfc-editor.org/rfc/rfc5322#appendix-A.5). Gross but technically allowed. In reality, most email validating scripts will get you where you need to go. This library just aims to go all the way. ## Installation Add the gem to your Gemfile with: ```sh gem 'validates_email_format_of' ``` ### Usage in a Rails app ```ruby class Person < ActiveRecord::Base validates :email, :email_format => { :message => "is not looking good" } # OR validates_email_format_of :email, :message => "is not looking good" end ``` You can use the included `rspec` matcher as well: ```ruby require "validates_email_format_of/rspec_matcher" describe Person do it { should validate_email_format_of(:email).with_message("is not looking good") } end ``` -### Useage without Rails +### Usage without Rails ```ruby # Optional, if you want error messages to be in your language ValidatesEmailFormatOf::load_i18n_locales I18n.locale = :pl ValidatesEmailFormatOf::validate_email_format("example@mydomain.com") # => nil ValidatesEmailFormatOf::validate_email_format("invalid@") # => ["does not appear to be a valid email address"] ``` ## Options | Option | Type | Description | | --- | --- | --- | | `:message` | String | A custom error message when the email format is invalid (default is: "does not appear to be a valid email address") | | `:check_mx` | Boolean | Check domain for a valid MX record (default is false) | | `:check_mx_timeout` | Integer | Timeout in seconds for checking MX records before a `ResolvTimeout` is raised (default is 3). | | `:mx_message` | String | A custom error message when the domain does not match a valid MX record (default is: "is not routable"). Ignored unless :check_mx option is true. | | `:local_length` |Integer | Maximum number of characters allowed in the local part (everything before the '@') (default is 64) | | `:domain_length` | Integer | Maximum number of characters allowed in the domain part (everything after the '@') (default is 255) | | `:generate_message` | Boolean | Return the I18n key of the error message instead of the error message itself (default is false) | The standard ActiveModel validation options (`:on`, `:if`, `:unless`, `:allow_nil`, `:allow_blank`, etc...) all work as well when using the gem as part of a Rails application. ## Testing You can see our [current Ruby and Rails test matrix here](.github/workflows/ci.yml). To execute the unit tests against [all the Rails versions we support run](gemfiles/) <tt>bundle exec appraisal rspec</tt> or run against an individual version with <tt>bundle exec appraisal rails-6.0 rspec</tt>. ## Contributing If you think we're letting some rules about valid email formats slip through the cracks, don't just update the parser. Instead, add a failing test and demonstrate that the described email address should be treated differently. A link to an appropriate RFC is the best way to do this. Then change the gem code to make the test pass. ```ruby describe "i_think_this_is_not_a_v@lid_email_addre.ss" do # According to http://..., this email address IS NOT valid. it { should have_errors_on_email.because("does not appear to be valid") } end describe "i_think_this_is_a_v@lid_email_addre.ss" do # According to http://..., this email address IS valid. it { should_not have_errors_on_email } end ``` Yes, our Rspec syntax is that simple! ## Homepage * https://github.com/validates-email-format-of/validates_email_format_of ## Credits Written by Alex Dunae (dunae.ca), 2006-22. Many thanks to the plugin's recent contributors: https://github.com/alexdunae/validates_email_format_of/contributors Thanks to Francis Hwang (http://fhwang.net/) at Diversion Media for creating the 1.1 update. Thanks to Travis Sinnott for creating the 1.3 update. Thanks to Denis Ahearn at Riverock Technologies (http://www.riverocktech.com/) for creating the 1.4 update. Thanks to George Anderson (http://github.com/george) and 'history' (http://github.com/history) for creating the 1.4.1 update. Thanks to Isaac Betesh (https://github.com/betesh) for converting tests to Rspec and refactoring for version 1.6.0.
validates-email-format-of/validates_email_format_of
129ebfc3a3b432b4df0334bcbdd74b1d17d765e0
Add Indonesian locale
diff --git a/config/locales/id.yml b/config/locales/id.yml new file mode 100644 index 0000000..c41f487 --- /dev/null +++ b/config/locales/id.yml @@ -0,0 +1,8 @@ +id: + activemodel: &errors + errors: + messages: + invalid_email_address: 'tampaknya bukan alamat email yang valid' + email_address_not_routable: 'tidak dapat dirutekan' + activerecord: + <<: *errors
validates-email-format-of/validates_email_format_of
0f8a1c3305f39e84c55f01c6c59ec47997d2e744
Run GitHub actions on all push and pull_requests events
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b68b3e8..0e12f27 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,67 +1,65 @@ name: CI on: - push: - branches: [master] - pull_request: - branches: [master] + - push + - pull_request permissions: contents: read jobs: test: name: "Ruby ${{ matrix.ruby }}, Rails ${{ matrix.gemfile }}" runs-on: ubuntu-latest strategy: matrix: ruby: ["2.6", "2.7", "3.0", "3.1"] gemfile: ["4.2", "5.0", "5.1", "5.2", "6.0", "6.1", "7.0"] exclude: - gemfile: "4.2" ruby: "3.0" - gemfile: "4.2" ruby: "3.1" - gemfile: "5.0" ruby: "3.0" - gemfile: "5.0" ruby: "3.1" - gemfile: "5.1" ruby: "3.0" - gemfile: "5.1" ruby: "3.1" - gemfile: "5.2" ruby: "3.0" - gemfile: "5.2" ruby: "3.1" - gemfile: "7.0" ruby: "2.5" - gemfile: "7.0" ruby: "2.6" - gemfile: "7.0" ruby: "2.7" env: BUNDLE_GEMFILE: gemfiles/rails_${{ matrix.gemfile }}.gemfile RAILS_ENV: test steps: - uses: actions/checkout@v3 - name: "Install Ruby ${{ matrix.ruby }}" # To automatically get bug fixes and new Ruby versions for ruby/setup-ruby, # change this to (see https://github.com/ruby/setup-ruby#versioning): # uses: ruby/setup-ruby@v1 uses: ruby/setup-ruby@v1 with: bundler: 1 ruby-version: ${{ matrix.ruby }} bundler-cache: true # runs 'bundle install' and caches installed gems automatically - name: Run specs run: bundle exec rspec - name: Run standard.rb run: bundle exec rake standard
validates-email-format-of/validates_email_format_of
42e65a56158b06cae6d751aba6dbe13d600abe0b
Enforce i18n >= 0.8.0 in modern Ruby versions
diff --git a/CHANGELOG.md b/CHANGELOG.md index d05da99..36b6d15 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,37 +1,38 @@ # CHANGELOG ## [Unreleased] * ⚠️ Deprecate `:with` option - https://github.com/validates-email-format-of/validates_email_format_of/issues/42 +* Require i18n >= 0.8.0 in modern Ruby versions - https://github.com/advisories/GHSA-34hf-g744-jw64 [Unreleased]: https://github.com/validates-email-format-of/validates_email_format_of/compare/v1.7.2...master ## [1.7.2] * Fix regression that disallowed domains starting with number - https://github.com/validates-email-format-of/validates_email_format_of/issues/88 [Unreleased]: https://github.com/validates-email-format-of/validates_email_format_of/compare/v1.7.1...v1.7.2 ## [1.7.1] (3 Aug 2022) * Fix invalid symbols being allowed in the local part - https://github.com/validates-email-format-of/validates_email_format_of/issues/86 * Fix rspec_matcher when using a custom error message - https://github.com/validates-email-format-of/validates_email_format_of/pull/85 - thanks https://github.com/luuqnhu ! [1.7.1]: https://github.com/validates-email-format-of/validates_email_format_of/compare/v1.7.0...v1.7.1 ## [1.7.0] (29 July 2022) * Use Standard.rb for internal code formatting - https://github.com/validates-email-format-of/validates_email_format_of/commit/db1b0a86af58e478b7f9f2f269bf93bf48dc13c1 * Add support for comments in the local part and improve quoted character handling - https://github.com/validates-email-format-of/validates_email_format_of/issues/69 * Improve grammar for parsing domain part and validate domain part lengths - https://github.com/validates-email-format-of/validates_email_format_of/commit/2554b55e547c1fae6599d13b0c99296752888c91 * Do not strip spaces before validating - https://github.com/validates-email-format-of/validates_email_format_of/issues/61 and https://github.com/validates-email-format-of/validates_email_format_of/issues/72 * Allow setting check_mx_timeout and reduce the default timeout to 3 seconds - https://github.com/validates-email-format-of/validates_email_format_of/issues/66 * Fix regex duplicate character warning - https://github.com/validates-email-format-of/validates_email_format_of/pull/71 * Update CI to include Ruby 2.6 to 3.1 and Rails 4.2 to 7.0 [1.7.0]: https://github.com/validates-email-format-of/validates_email_format_of/compare/v1.6.1...v1.7.0 ## [1.6.1] (8 Sept 2014) * In a Rails context, this gem now uses ActiveModel's default logic for constructing I18n keys, to make it easier to override them on a model/attribute basis. [1.6.1]: https://github.com/validates-email-format-of/validates_email_format_of/compare/v1.6.0...v1.6.1 diff --git a/validates_email_format_of.gemspec b/validates_email_format_of.gemspec index bb7c031..c781e92 100644 --- a/validates_email_format_of.gemspec +++ b/validates_email_format_of.gemspec @@ -1,28 +1,28 @@ $:.unshift File.expand_path("../lib", __FILE__) require "validates_email_format_of/version" Gem::Specification.new do |s| s.name = "validates_email_format_of" s.version = ValidatesEmailFormatOf::VERSION s.summary = "Validate e-mail addresses against RFC 2822 and RFC 3696." s.description = s.summary s.authors = ["Alex Dunae", "Isaac Betesh"] s.email = ["code@dunae.ca", "iybetesh@gmail.com"] s.homepage = "https://github.com/validates-email-format-of/validates_email_format_of" s.license = "MIT" s.files = `git ls-files`.split($/) s.require_paths = ["lib"] if RUBY_VERSION < "1.9.3" s.add_dependency "i18n", "< 0.7.0" else - s.add_dependency "i18n" + s.add_dependency "i18n", ">= 0.8.0" end s.add_development_dependency "activemodel" s.add_development_dependency "bundler" s.add_development_dependency "rspec" s.add_development_dependency "standard" s.add_development_dependency "appraisal" s.add_development_dependency "pry-byebug" end
validates-email-format-of/validates_email_format_of
279c23504b9b79c046de45c43b95f82d7fb9ead9
Improve handling of quoted local parts
diff --git a/lib/validates_email_format_of.rb b/lib/validates_email_format_of.rb index 876b1bf..9505f18 100644 --- a/lib/validates_email_format_of.rb +++ b/lib/validates_email_format_of.rb @@ -1,270 +1,302 @@ require "validates_email_format_of/version" module ValidatesEmailFormatOf def self.load_i18n_locales require "i18n" I18n.load_path += Dir.glob(File.expand_path(File.join(File.dirname(__FILE__), "..", "config", "locales", "*.yml"))) end require "resolv" # Characters that are allowed in to appear in the local part unquoted # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.3 # # An addr-spec is a specific Internet identifier that contains a # locally interpreted string followed by the at-sign character ("@", # ASCII value 64) followed by an Internet domain. The locally # interpreted string is either a quoted-string or a dot-atom. If the # string can be represented as a dot-atom (that is, it contains no # characters other than atext characters or "." surrounded by atext # characters), then the dot-atom form SHOULD be used and the quoted- # string form SHOULD NOT be used. Comments and folding white space # SHOULD NOT be used around the "@" in the addr-spec. # # atext = ALPHA / DIGIT / # "!" / "#" / "$" / "%" / "&" / "'" / "*" / # "+" / "-" / "/" / "=" / "?" / "^" / "_" / # "`" / "{" / "|" / "}" / "~" # dot-atom-text = 1*atext *("." 1*atext) # dot-atom = [CFWS] dot-atom-text [CFWS] ATEXT = /\A[A-Z0-9!\#$%&'*\-\/=?+\^_`{|}~]\z/i # Characters that are allowed to appear unquoted in comments # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.2 # # ctext = %d33-39 / %d42-91 / %d93-126 # ccontent = ctext / quoted-pair / comment # comment = "(" *([FWS] ccontent) [FWS] ")" # CFWS = (1*([FWS] comment) [FWS]) / FWS CTEXT = /\A[#{Regexp.escape([33..39, 42..91, 93..126].map { |ascii_range| ascii_range.map(&:chr) }.flatten.join)}\s]/i # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.4 # # Strings of characters that include characters other than those # allowed in atoms can be represented in a quoted string format, where # the characters are surrounded by quote (DQUOTE, ASCII value 34) # characters. # # qtext = %d33 / ; Printable US-ASCII # %d35-91 / ; characters not including # %d93-126 / ; "\" or the quote character # obs-qtext # # qcontent = qtext / quoted-pair # quoted-string = [CFWS] # DQUOTE *([FWS] qcontent) [FWS] DQUOTE # [CFWS] QTEXT = /\A[#{Regexp.escape([33..33, 35..91, 93..126].map { |ascii_range| ascii_range.map(&:chr) }.flatten.join)}\s]/i IP_OCTET = /\A[0-9]+\Z/ # From https://datatracker.ietf.org/doc/html/rfc1035#section-2.3.1 # # > The labels must follow the rules for ARPANET host names. They must # > start with a letter, end with a letter or digit, and have as interior # > characters only letters, digits, and hyphen. There are also some # > restrictions on the length. Labels must be 63 characters or less. # # <label> | <subdomain> "." <label> # <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ] # <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str> # <let-dig-hyp> ::= <let-dig> | "-" # <let-dig> ::= <letter> | <digit> # # Additionally, from https://datatracker.ietf.org/doc/html/rfc1123#section-2.1 # # > One aspect of host name syntax is hereby changed: the # > restriction on the first character is relaxed to allow either a # > letter or a digit. Host software MUST support this more liberal # > syntax. DOMAIN_PART_LABEL = /\A[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9]?\Z/ # From https://tools.ietf.org/id/draft-liman-tld-names-00.html#rfc.section.2 # # > A TLD label MUST be at least two characters long and MAY be as long as 63 characters - # > not counting any leading or trailing periods (.). It MUST consist of only ASCII characters # > from the groups "letters" (A-Z), "digits" (0-9) and "hyphen" (-), and it MUST start with an # > ASCII "letter", and it MUST NOT end with a "hyphen". Upper and lower case MAY be mixed at random, # > since DNS lookups are case-insensitive. # # tldlabel = ALPHA *61(ldh) ld # ldh = ld / "-" # ld = ALPHA / DIGIT # ALPHA = %x41-5A / %x61-7A ; A-Z / a-z # DIGIT = %x30-39 ; 0-9 DOMAIN_PART_TLD = /\A[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9]\Z/ def self.validate_email_domain(email, check_mx_timeout: 3) domain = email.to_s.downcase.match(/@(.+)/)[1] Resolv::DNS.open do |dns| dns.timeouts = check_mx_timeout @mx = dns.getresources(domain, Resolv::DNS::Resource::IN::MX) + dns.getresources(domain, Resolv::DNS::Resource::IN::A) end @mx.size > 0 end DEFAULT_MESSAGE = "does not appear to be valid" DEFAULT_MX_MESSAGE = "is not routable" ERROR_MESSAGE_I18N_KEY = :invalid_email_address ERROR_MX_MESSAGE_I18N_KEY = :email_address_not_routable def self.default_message defined?(I18n) ? I18n.t(ERROR_MESSAGE_I18N_KEY, scope: [:activemodel, :errors, :messages], default: DEFAULT_MESSAGE) : DEFAULT_MESSAGE end # Validates whether the specified value is a valid email address. Returns nil if the value is valid, otherwise returns an array # containing one or more validation error messages. # # Configuration options: # * <tt>message</tt> - A custom error message (default is: "does not appear to be valid") # * <tt>check_mx</tt> - Check for MX records (default is false) # * <tt>check_mx_timeout</tt> - Timeout in seconds for checking MX records before a `ResolvTimeout` is raised (default is 3) # * <tt>mx_message</tt> - A custom error message when an MX record validation fails (default is: "is not routable.") # * <tt>local_length</tt> Maximum number of characters allowed in the local part (default is 64) # * <tt>domain_length</tt> Maximum number of characters allowed in the domain part (default is 255) # * <tt>generate_message</tt> Return the I18n key of the error message instead of the error message itself (default is false) def self.validate_email_format(email, options = {}) default_options = {message: options[:generate_message] ? ERROR_MESSAGE_I18N_KEY : default_message, check_mx: false, check_mx_timeout: 3, mx_message: if options[:generate_message] ERROR_MX_MESSAGE_I18N_KEY else (defined?(I18n) ? I18n.t(ERROR_MX_MESSAGE_I18N_KEY, scope: [:activemodel, :errors, :messages], default: DEFAULT_MX_MESSAGE) : DEFAULT_MX_MESSAGE) end, domain_length: 255, local_length: 64, generate_message: false} opts = options.merge(default_options) { |key, old, new| old } # merge the default options into the specified options, retaining all specified options begin domain, local = email.reverse.split("@", 2) rescue return [opts[:message]] end # need local and domain parts return [opts[:message]] unless local && !local.empty? && domain && !domain.empty? # check lengths return [opts[:message]] unless domain.length <= opts[:domain_length] && local.length <= opts[:local_length] local.reverse! domain.reverse! if opts.has_key?(:with) # holdover from versions <= 1.4.7 deprecation_warn(":with option is deprecated and will be removed in the next version") return [opts[:message]] unless email&.match?(opts[:with]) else return [opts[:message]] unless validate_local_part_syntax(local) && validate_domain_part_syntax(domain) end if opts[:check_mx] && !validate_email_domain(email, check_mx_timeout: opts[:check_mx_timeout]) return [opts[:mx_message]] end nil # represents no validation errors end def self.validate_local_part_syntax(local) in_quoted_pair = false in_quoted_string = false comment_depth = 0 + # The local part is made up of dot-atom and quoted-string joined together by "." characters + # + # https://www.rfc-editor.org/rfc/rfc5322#section-3.4.1 + # > local-part = dot-atom / quoted-string / obs-local-part + # + # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.3 + # Both atom and dot-atom are interpreted as a single unit, comprising + # > the string of characters that make it up. Semantically, the optional + # > comments and FWS surrounding the rest of the characters are not part + # > of the atom; the atom is only the run of atext characters in an atom, + # > or the atext and "." characters in a dot-atom. + joining_atoms = true + (0..local.length - 1).each do |i| ord = local[i].ord # accept anything if it's got a backslash before it if in_quoted_pair in_quoted_pair = false next end + # double quote delimits quoted strings + if ord == 34 + if in_quoted_string # leaving the quoted string + in_quoted_string = false + next + elsif joining_atoms # are we allowed to enter a quoted string? + in_quoted_string = true + joining_atoms = false + next + else + return false + end + end + + # period indicates we want to join atoms, e.g. `aaa.bbb."ccc"@example.com + if ord == 46 + return false if i.zero? + return false if joining_atoms + joining_atoms = true + next + end + + joining_atoms = false + + # quoted string logic must come before comment processing since a quoted string + # may contain parens, e.g. `"name(a)"@example.com` if in_quoted_string next if QTEXT.match?(local[i]) end # opening paren to show we are going into a comment (CFWS) if ord == 40 comment_depth += 1 next end # closing paren if ord == 41 comment_depth -= 1 return false if comment_depth < 0 next end # backslash signifies the start of a quoted pair - if ord == 92 && i < local.length - 1 - return false if !in_quoted_string # must be in quoted string per http://www.rfc-editor.org/errata_search.php?rfc=3696 + if ord == 92 + # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.1 + # > The only places in this specification where quoted-pair currently appears are + # > ccontent, qcontent, and in obs-dtext in section 4. + return false unless in_quoted_string || comment_depth > 0 in_quoted_pair = true next end - # double quote delimits quoted strings - if ord == 34 - in_quoted_string = !in_quoted_string - next - end - if comment_depth > 0 next if CTEXT.match?(local[i]) elsif ATEXT.match?(local[i, 1]) next end - # period must be followed by something - if ord == 46 - return false if i == 0 || i == local.length - 1 # can't be first or last char - next unless local[i + 1].ord == 46 # can't be followed by a period - end - return false end + return false if in_quoted_pair # unbalanced quoted pair return false if in_quoted_string # unbalanced quotes return false unless comment_depth.zero? # unbalanced comment parens + return false if joining_atoms # the last char we encountered was a period true end def self.validate_domain_part_syntax(domain) parts = domain.downcase.split(".", -1) return false if parts.length <= 1 # Only one domain part # ipv4 return true if parts.length == 4 && parts.all? { |part| part =~ IP_OCTET && part.to_i.between?(0, 255) } # From https://datatracker.ietf.org/doc/html/rfc3696#section-2 this is the recommended, pragmatic way to validate a domain name: # # > It is likely that the better strategy has now become to make the "at least one period" test, # > to verify LDH conformance (including verification that the apparent TLD name is not all-numeric), # > and then to use the DNS to determine domain name validity, rather than trying to maintain # > a local list of valid TLD names. # # We do a little bit more but not too much and validate the tokens but do not check against a list of valid TLDs. parts.each do |part| return false if part.nil? || part.empty? return false if part.length > 63 return false unless DOMAIN_PART_LABEL.match?(part) end return false unless DOMAIN_PART_TLD.match?(parts[-1]) true end def self.deprecation_warn(msg) if defined?(ActiveSupport::Deprecation) ActiveSupport::Deprecation.warn(msg) else warn end end end require "validates_email_format_of/active_model" if defined?(::ActiveModel) && !(ActiveModel::VERSION::MAJOR < 2 || (ActiveModel::VERSION::MAJOR == 2 && ActiveModel::VERSION::MINOR < 1)) require "validates_email_format_of/railtie" if defined?(::Rails::Railtie) diff --git a/spec/validates_email_format_of_spec.rb b/spec/validates_email_format_of_spec.rb index 51d3085..a7a0f5b 100644 --- a/spec/validates_email_format_of_spec.rb +++ b/spec/validates_email_format_of_spec.rb @@ -1,328 +1,334 @@ require "#{__dir__}/spec_helper" require "validates_email_format_of" RSpec.configure do |config| config.before(:suite) do ValidatesEmailFormatOf.load_i18n_locales I18n.enforce_available_locales = false end end describe ValidatesEmailFormatOf do subject do |example| user = Class.new do def initialize(email) @email = email.freeze end attr_reader :email include ActiveModel::Validations validates_email_format_of :email, example.example_group_instance.options def self.model_name ActiveModel::Name.new(self, nil, "User") end end user.new(example.example_group_instance.email).tap(&:valid?).errors.full_messages end let(:options) { {} } let(:email) { |example| example.example_group.description } shared_examples_for :all_specs do [ "valid@example.com", "Valid@test.example.com", "valid+valid123@test.example.com", "valid_valid123@test.example.com", "valid-valid+123@test.example.co.uk", "valid-valid+1.23@test.example.com.au", "valid@1example.com", "valid@example.co.uk", "v@example.com", "valid@example.ca", "valid_@example.com", "valid123.456@example.org", "valid123.456@example.travel", "valid123.456@example.museum", "valid@example.mobi", "valid@example.info", "valid-@example.com", "fake@p-t.k12.ok.us", # allow single character domain parts "valid@mail.x.example.com", "valid@x.com", "valid@example.w-dash.sch.uk", # from RFC 3696, page 6 "customer/department=shipping@example.com", "$A12345@example.com", "!def!xyz%abc@example.com", "_somename@example.com", # apostrophes "test'test@example.com", # international domain names "test@xn--bcher-kva.ch", "test@example.xn--0zwm56d", "test@192.192.192.1", # Allow quoted characters. Valid according to http://www.rfc-editor.org/errata_search.php?rfc=3696 '"Abc\@def"@example.com', + "\"quote\".dotatom.\"otherquote\"@example.com", '"Quote(Only".Chars@wier.de', + "\"much.more unusual\"@example.com", + "\"very.unusual.@.unusual.com\"@example.com", + '"very.(),:;<>[]\".VERY.\"very@\\ \"very\".unusual"@strange.example.com', + '"()<>[]:,;@\"!#$%&*+-/=?^_`{}| ~ ? ^_`{}|~.a"@example.org', '"Fred\ Bloggs"@example.com', '"Joe.\\Blow"@example.com', # Balanced quoted characters %("example\\\\\\""@example.com), %("example\\\\"@example.com), "(leading comment)email@example.com", "(nested (comment))email@example.com", "email(trailing comment)@example.com" ].each do |address| describe address do it { should_not have_errors_on_email } end end [ "no_at_symbol", "multiple@at@symbols.com", "invalid@example-com", # period can not start local part ".invalid@example.com", # period can not end local part "invalid.@example.com", # period can not appear twice consecutively in local part "invali..d@example.com", # should not allow underscores in domain names "invalid@ex_mple.com", "invalid@e..example.com", "invalid@p-t..example.com", "invalid@example.com.", "invalid@example.com_", "invalid@example.com-", "invalid-example.com", "invalid@example.b#r.com", + "just\"not\"right@example.com", "invalid@example.c", "invali d@example.com", # TLD can not be only numeric "invalid@example.123", # unclosed quote "\"a-17180061943-10618354-1993365053@example.com", # too many special chars used to cause the regexp to hang "-+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++@foo", "invalidexample.com", # should not allow special chars after a period in the domain "local@sub.)domain.com", "local@sub.#domain.com", # one at a time "foo@example.com\nexample@gmail.com", "invalid@example.", "\"foo\\\\\"\"@bar.com", "foo@mail.com\r\nfoo@mail.com", "@example.com", "foo@", "foo", "Iñtërnâtiônàlizætiøn@hasnt.happened.to.email", # Escaped characters with quotes. From http://tools.ietf.org/html/rfc3696, page 5. Corrected in http://www.rfc-editor.org/errata_search.php?rfc=3696 'Fred\ Bloggs_@example.com', 'Abc\@def+@example.com', 'Joe.\\Blow@example.com', # Unbalanced quoted characters %("example\\\\""example.com), "\nnewline@example.com", " spacesbefore@example.com", "spacesafter@example.com ", "(unbalancedcomment@example.com" ].each do |address| describe address do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe do shared_examples_for :local_length_limit do |limit| describe "#{"a" * limit}@example.com" do it { should_not have_errors_on_email } end describe "#{"a" * (limit + 1)}@example.com" do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "when using default" do it_should_behave_like :local_length_limit, 64 end describe "when overriding defaults" do let(:options) { {local_length: 20} } it_should_behave_like :local_length_limit, 20 end end describe do shared_examples_for :domain_length_limit do |limit| describe "user@#{"a." * (limit / 2 - 3)}com" do it { should_not have_errors_on_email } end describe "user@#{"a." * (limit / 2 + 1)}com" do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "when using default" do it_should_behave_like :domain_length_limit, 255 end describe "when overriding defaults" do let(:options) { {domain_length: 100} } it_should_behave_like :domain_length_limit, 100 end end describe "custom error messages" do describe "invalid@example." do let(:options) { {message: "just because I don't like you"} } it { should have_errors_on_email.because("just because I don't like you") } end end describe "mx record" do domain = "example.com" email = "valid@#{domain}" describe "when testing" do let(:dns) { double(Resolv::DNS) } let(:mx_record) { [double] } let(:a_record) { [double] } before(:each) do allow(Resolv::DNS).to receive(:open).and_yield(dns) allow(dns).to receive(:"timeouts=").with(3).once allow(dns).to receive(:getresources).with(domain, Resolv::DNS::Resource::IN::MX).once.and_return(mx_record) allow(dns).to receive(:getresources).with(domain, Resolv::DNS::Resource::IN::A).once.and_return(a_record) end let(:options) { {check_mx: true, check_mx_timeout: 3} } describe "and only an mx record is found" do let(:a_record) { [] } describe email do it { should_not have_errors_on_email } end end describe "and only an a record is found" do let(:mx_record) { [] } describe email do it { should_not have_errors_on_email } end end describe "and both an mx record and an a record are found" do describe email do it { should_not have_errors_on_email } end end describe "and neither an mx record nor an a record is found" do let(:a_record) { [] } let(:mx_record) { [] } describe email do it { should have_errors_on_email.because("is not routable") } end describe "with a custom error message" do let(:options) { {check_mx: true, mx_message: "There ain't no such domain!"} } describe email do it { should have_errors_on_email.because("There ain't no such domain!") } end end describe "i18n" do before(:each) do allow(I18n.config).to receive(:locale).and_return(locale) end describe "present locale" do let(:locale) { :pl } describe email do it { should have_errors_on_email.because("jest nieosiągalny") } end end end end end describe "when not testing" do before(:each) { allow(Resolv::DNS).to receive(:open).never } describe "by default" do describe email do it { should_not have_errors_on_email } end end describe "explicitly" do describe email do let(:options) { {check_mx: false} } it { should_not have_errors_on_email } end end end describe "without mocks" do describe email do let(:options) { {check_mx: true} } it { should_not have_errors_on_email } end end end describe "custom regex" do let(:options) { {with: /[0-9]+@[0-9]+/} } describe "012345@789" do it { should_not have_errors_on_email } end describe "valid@example.com" do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "i18n" do before(:each) do allow(I18n.config).to receive(:locale).and_return(locale) end describe "present locale" do let(:locale) { :pl } describe "invalid@exmaple." do it { should have_errors_on_email.because("nieprawidłowy adres e-mail") } end end end end it_should_behave_like :all_specs describe "validation without ActiveModel" do subject do ValidatesEmailFormatOf.validate_email_format(email.freeze, options) end describe "valid@example.com" do it { should be_nil } end describe "custom error messages" do describe "invalid@example." do let(:options) { {message: "just because I don't like you"} } it { should match_array(["just because I don't like you"]) } end end describe "without i18n" do before(:each) { hide_const("I18n") } describe "invalid@exmaple." do it { should match_array(["does not appear to be valid"]) } end end end describe "shorthand ActiveModel validation" do subject do |example| user = Class.new do def initialize(email) @email = email.freeze end attr_reader :email include ActiveModel::Validations validates :email, email_format: example.example_group_instance.options def self.model_name ActiveModel::Name.new(self, nil, "User") end end user.new(example.example_group_instance.email).tap(&:valid?).errors.full_messages end it_should_behave_like :all_specs end end
validates-email-format-of/validates_email_format_of
669f1bf773eb29514509b978998a625da5c19883
Fix RFC names in the README
diff --git a/README.md b/README.md index 320a61d..003e5e9 100644 --- a/README.md +++ b/README.md @@ -1,110 +1,110 @@ # validates_email_format_of [![Build Status](https://github.com/validates-email-format-of/validates_email_format_of/actions/workflows/ci.yml/badge.svg)]( https://github.com/validates-email-format-of/validates_email_format_of/actions/workflows/ci.yml?query=branch%3Amaster) -A Ruby gem to validate e-mail addresses against RFC 2822 and RFC 3696. +A Ruby gem to validate e-mail addresses against RFC 2822 and RFC 5322. ## Why this email validator? This gem is the O.G. email validation gem for Rails. It was started back in 2006. Why use this validator? Instead of trying to validate email addresses with one giant regular expression, this library parses addresses character by character. This lets us handle weird cases likes [nested comments](https://www.rfc-editor.org/rfc/rfc5322#appendix-A.5). Gross but technically allowed. In reality, most email validating scripts will get you where you need to go. This library just aims to go all the way. ## Installation Add the gem to your Gemfile with: ```sh gem 'validates_email_format_of' ``` ### Usage in a Rails app ```ruby class Person < ActiveRecord::Base validates :email, :email_format => { :message => "is not looking good" } # OR validates_email_format_of :email, :message => "is not looking good" end ``` You can use the included `rspec` matcher as well: ```ruby require "validates_email_format_of/rspec_matcher" describe Person do it { should validate_email_format_of(:email).with_message("is not looking good") } end ``` ### Useage without Rails ```ruby # Optional, if you want error messages to be in your language ValidatesEmailFormatOf::load_i18n_locales I18n.locale = :pl ValidatesEmailFormatOf::validate_email_format("example@mydomain.com") # => nil ValidatesEmailFormatOf::validate_email_format("invalid@") # => ["does not appear to be a valid e-mail address"] ``` ## Options | Option | Type | Description | | --- | --- | --- | | `:message` | String | A custom error message when the email format is invalid (default is: "does not appear to be a valid e-mail address") | | `:check_mx` | Boolean | Check domain for a valid MX record (default is false) | | `:check_mx_timeout` | Integer | Timeout in seconds for checking MX records before a `ResolvTimeout` is raised (default is 3). | | `:mx_message` | String | A custom error message when the domain does not match a valid MX record (default is: "is not routable"). Ignored unless :check_mx option is true. | | `:local_length` |Integer | Maximum number of characters allowed in the local part (everything before the '@') (default is 64) | | `:domain_length` | Integer | Maximum number of characters allowed in the domain part (everything after the '@') (default is 255) | | `:generate_message` | Boolean | Return the I18n key of the error message instead of the error message itself (default is false) | The standard ActiveModel validation options (`:on`, `:if`, `:unless`, `:allow_nil`, `:allow_blank`, etc...) all work as well when using the gem as part of a Rails application. ## Testing You can see our [current Ruby and Rails test matrix here](.github/workflows/ci.yml). To execute the unit tests against [all the Rails versions we support run](gemfiles/) <tt>bundle exec appraisal rspec</tt> or run against an individual version with <tt>bundle exec appraisal rails-6.0 rspec</tt>. ## Contributing If you think we're letting some rules about valid email formats slip through the cracks, don't just update the parser. Instead, add a failing test and demonstrate that the described email address should be treated differently. A link to an appropriate RFC is the best way to do this. Then change the gem code to make the test pass. ```ruby describe "i_think_this_is_not_a_v@lid_email_addre.ss" do # According to http://..., this email address IS NOT valid. it { should have_errors_on_email.because("does not appear to be valid") } end describe "i_think_this_is_a_v@lid_email_addre.ss" do # According to http://..., this email address IS valid. it { should_not have_errors_on_email } end ``` Yes, our Rspec syntax is that simple! ## Homepage * https://github.com/validates-email-format-of/validates_email_format_of ## Credits Written by Alex Dunae (dunae.ca), 2006-22. Many thanks to the plugin's recent contributors: https://github.com/alexdunae/validates_email_format_of/contributors Thanks to Francis Hwang (http://fhwang.net/) at Diversion Media for creating the 1.1 update. Thanks to Travis Sinnott for creating the 1.3 update. Thanks to Denis Ahearn at Riverock Technologies (http://www.riverocktech.com/) for creating the 1.4 update. Thanks to George Anderson (http://github.com/george) and 'history' (http://github.com/history) for creating the 1.4.1 update. Thanks to Isaac Betesh (https://github.com/betesh) for converting tests to Rspec and refactoring for version 1.6.0.
validates-email-format-of/validates_email_format_of
7b9600272cfc59491acb7d1219fe122243dbe76b
Deprecate `:with` option
diff --git a/CHANGELOG.md b/CHANGELOG.md index 4fdc199..d05da99 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,35 +1,37 @@ # CHANGELOG ## [Unreleased] +* ⚠️ Deprecate `:with` option - https://github.com/validates-email-format-of/validates_email_format_of/issues/42 + [Unreleased]: https://github.com/validates-email-format-of/validates_email_format_of/compare/v1.7.2...master ## [1.7.2] * Fix regression that disallowed domains starting with number - https://github.com/validates-email-format-of/validates_email_format_of/issues/88 [Unreleased]: https://github.com/validates-email-format-of/validates_email_format_of/compare/v1.7.1...v1.7.2 ## [1.7.1] (3 Aug 2022) * Fix invalid symbols being allowed in the local part - https://github.com/validates-email-format-of/validates_email_format_of/issues/86 * Fix rspec_matcher when using a custom error message - https://github.com/validates-email-format-of/validates_email_format_of/pull/85 - thanks https://github.com/luuqnhu ! [1.7.1]: https://github.com/validates-email-format-of/validates_email_format_of/compare/v1.7.0...v1.7.1 ## [1.7.0] (29 July 2022) * Use Standard.rb for internal code formatting - https://github.com/validates-email-format-of/validates_email_format_of/commit/db1b0a86af58e478b7f9f2f269bf93bf48dc13c1 * Add support for comments in the local part and improve quoted character handling - https://github.com/validates-email-format-of/validates_email_format_of/issues/69 * Improve grammar for parsing domain part and validate domain part lengths - https://github.com/validates-email-format-of/validates_email_format_of/commit/2554b55e547c1fae6599d13b0c99296752888c91 * Do not strip spaces before validating - https://github.com/validates-email-format-of/validates_email_format_of/issues/61 and https://github.com/validates-email-format-of/validates_email_format_of/issues/72 * Allow setting check_mx_timeout and reduce the default timeout to 3 seconds - https://github.com/validates-email-format-of/validates_email_format_of/issues/66 * Fix regex duplicate character warning - https://github.com/validates-email-format-of/validates_email_format_of/pull/71 * Update CI to include Ruby 2.6 to 3.1 and Rails 4.2 to 7.0 [1.7.0]: https://github.com/validates-email-format-of/validates_email_format_of/compare/v1.6.1...v1.7.0 ## [1.6.1] (8 Sept 2014) * In a Rails context, this gem now uses ActiveModel's default logic for constructing I18n keys, to make it easier to override them on a model/attribute basis. [1.6.1]: https://github.com/validates-email-format-of/validates_email_format_of/compare/v1.6.0...v1.6.1 diff --git a/README.md b/README.md index 0651a17..320a61d 100644 --- a/README.md +++ b/README.md @@ -1,111 +1,110 @@ # validates_email_format_of [![Build Status](https://github.com/validates-email-format-of/validates_email_format_of/actions/workflows/ci.yml/badge.svg)]( https://github.com/validates-email-format-of/validates_email_format_of/actions/workflows/ci.yml?query=branch%3Amaster) A Ruby gem to validate e-mail addresses against RFC 2822 and RFC 3696. ## Why this email validator? This gem is the O.G. email validation gem for Rails. It was started back in 2006. Why use this validator? Instead of trying to validate email addresses with one giant regular expression, this library parses addresses character by character. This lets us handle weird cases likes [nested comments](https://www.rfc-editor.org/rfc/rfc5322#appendix-A.5). Gross but technically allowed. In reality, most email validating scripts will get you where you need to go. This library just aims to go all the way. ## Installation Add the gem to your Gemfile with: ```sh gem 'validates_email_format_of' ``` ### Usage in a Rails app ```ruby class Person < ActiveRecord::Base validates :email, :email_format => { :message => "is not looking good" } # OR validates_email_format_of :email, :message => "is not looking good" end ``` You can use the included `rspec` matcher as well: ```ruby require "validates_email_format_of/rspec_matcher" describe Person do it { should validate_email_format_of(:email).with_message("is not looking good") } end ``` ### Useage without Rails ```ruby # Optional, if you want error messages to be in your language ValidatesEmailFormatOf::load_i18n_locales I18n.locale = :pl ValidatesEmailFormatOf::validate_email_format("example@mydomain.com") # => nil ValidatesEmailFormatOf::validate_email_format("invalid@") # => ["does not appear to be a valid e-mail address"] ``` ## Options | Option | Type | Description | | --- | --- | --- | | `:message` | String | A custom error message when the email format is invalid (default is: "does not appear to be a valid e-mail address") | | `:check_mx` | Boolean | Check domain for a valid MX record (default is false) | | `:check_mx_timeout` | Integer | Timeout in seconds for checking MX records before a `ResolvTimeout` is raised (default is 3). | | `:mx_message` | String | A custom error message when the domain does not match a valid MX record (default is: "is not routable"). Ignored unless :check_mx option is true. | | `:local_length` |Integer | Maximum number of characters allowed in the local part (everything before the '@') (default is 64) | | `:domain_length` | Integer | Maximum number of characters allowed in the domain part (everything after the '@') (default is 255) | | `:generate_message` | Boolean | Return the I18n key of the error message instead of the error message itself (default is false) | -| `:with` | Regex | Specify a custom Regex as the valid email format. | The standard ActiveModel validation options (`:on`, `:if`, `:unless`, `:allow_nil`, `:allow_blank`, etc...) all work as well when using the gem as part of a Rails application. ## Testing You can see our [current Ruby and Rails test matrix here](.github/workflows/ci.yml). To execute the unit tests against [all the Rails versions we support run](gemfiles/) <tt>bundle exec appraisal rspec</tt> or run against an individual version with <tt>bundle exec appraisal rails-6.0 rspec</tt>. ## Contributing If you think we're letting some rules about valid email formats slip through the cracks, don't just update the parser. Instead, add a failing test and demonstrate that the described email address should be treated differently. A link to an appropriate RFC is the best way to do this. Then change the gem code to make the test pass. ```ruby describe "i_think_this_is_not_a_v@lid_email_addre.ss" do # According to http://..., this email address IS NOT valid. it { should have_errors_on_email.because("does not appear to be valid") } end describe "i_think_this_is_a_v@lid_email_addre.ss" do # According to http://..., this email address IS valid. it { should_not have_errors_on_email } end ``` Yes, our Rspec syntax is that simple! ## Homepage * https://github.com/validates-email-format-of/validates_email_format_of ## Credits Written by Alex Dunae (dunae.ca), 2006-22. Many thanks to the plugin's recent contributors: https://github.com/alexdunae/validates_email_format_of/contributors Thanks to Francis Hwang (http://fhwang.net/) at Diversion Media for creating the 1.1 update. Thanks to Travis Sinnott for creating the 1.3 update. Thanks to Denis Ahearn at Riverock Technologies (http://www.riverocktech.com/) for creating the 1.4 update. Thanks to George Anderson (http://github.com/george) and 'history' (http://github.com/history) for creating the 1.4.1 update. Thanks to Isaac Betesh (https://github.com/betesh) for converting tests to Rspec and refactoring for version 1.6.0. diff --git a/lib/validates_email_format_of.rb b/lib/validates_email_format_of.rb index 2b472a2..876b1bf 100644 --- a/lib/validates_email_format_of.rb +++ b/lib/validates_email_format_of.rb @@ -1,262 +1,270 @@ require "validates_email_format_of/version" module ValidatesEmailFormatOf def self.load_i18n_locales require "i18n" I18n.load_path += Dir.glob(File.expand_path(File.join(File.dirname(__FILE__), "..", "config", "locales", "*.yml"))) end require "resolv" # Characters that are allowed in to appear in the local part unquoted # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.3 # # An addr-spec is a specific Internet identifier that contains a # locally interpreted string followed by the at-sign character ("@", # ASCII value 64) followed by an Internet domain. The locally # interpreted string is either a quoted-string or a dot-atom. If the # string can be represented as a dot-atom (that is, it contains no # characters other than atext characters or "." surrounded by atext # characters), then the dot-atom form SHOULD be used and the quoted- # string form SHOULD NOT be used. Comments and folding white space # SHOULD NOT be used around the "@" in the addr-spec. # # atext = ALPHA / DIGIT / # "!" / "#" / "$" / "%" / "&" / "'" / "*" / # "+" / "-" / "/" / "=" / "?" / "^" / "_" / # "`" / "{" / "|" / "}" / "~" # dot-atom-text = 1*atext *("." 1*atext) # dot-atom = [CFWS] dot-atom-text [CFWS] ATEXT = /\A[A-Z0-9!\#$%&'*\-\/=?+\^_`{|}~]\z/i # Characters that are allowed to appear unquoted in comments # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.2 # # ctext = %d33-39 / %d42-91 / %d93-126 # ccontent = ctext / quoted-pair / comment # comment = "(" *([FWS] ccontent) [FWS] ")" # CFWS = (1*([FWS] comment) [FWS]) / FWS CTEXT = /\A[#{Regexp.escape([33..39, 42..91, 93..126].map { |ascii_range| ascii_range.map(&:chr) }.flatten.join)}\s]/i # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.4 # # Strings of characters that include characters other than those # allowed in atoms can be represented in a quoted string format, where # the characters are surrounded by quote (DQUOTE, ASCII value 34) # characters. # # qtext = %d33 / ; Printable US-ASCII # %d35-91 / ; characters not including # %d93-126 / ; "\" or the quote character # obs-qtext # # qcontent = qtext / quoted-pair # quoted-string = [CFWS] # DQUOTE *([FWS] qcontent) [FWS] DQUOTE # [CFWS] QTEXT = /\A[#{Regexp.escape([33..33, 35..91, 93..126].map { |ascii_range| ascii_range.map(&:chr) }.flatten.join)}\s]/i IP_OCTET = /\A[0-9]+\Z/ # From https://datatracker.ietf.org/doc/html/rfc1035#section-2.3.1 # # > The labels must follow the rules for ARPANET host names. They must # > start with a letter, end with a letter or digit, and have as interior # > characters only letters, digits, and hyphen. There are also some # > restrictions on the length. Labels must be 63 characters or less. # # <label> | <subdomain> "." <label> # <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ] # <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str> # <let-dig-hyp> ::= <let-dig> | "-" # <let-dig> ::= <letter> | <digit> # # Additionally, from https://datatracker.ietf.org/doc/html/rfc1123#section-2.1 # # > One aspect of host name syntax is hereby changed: the # > restriction on the first character is relaxed to allow either a # > letter or a digit. Host software MUST support this more liberal # > syntax. DOMAIN_PART_LABEL = /\A[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9]?\Z/ # From https://tools.ietf.org/id/draft-liman-tld-names-00.html#rfc.section.2 # # > A TLD label MUST be at least two characters long and MAY be as long as 63 characters - # > not counting any leading or trailing periods (.). It MUST consist of only ASCII characters # > from the groups "letters" (A-Z), "digits" (0-9) and "hyphen" (-), and it MUST start with an # > ASCII "letter", and it MUST NOT end with a "hyphen". Upper and lower case MAY be mixed at random, # > since DNS lookups are case-insensitive. # # tldlabel = ALPHA *61(ldh) ld # ldh = ld / "-" # ld = ALPHA / DIGIT # ALPHA = %x41-5A / %x61-7A ; A-Z / a-z # DIGIT = %x30-39 ; 0-9 DOMAIN_PART_TLD = /\A[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9]\Z/ def self.validate_email_domain(email, check_mx_timeout: 3) domain = email.to_s.downcase.match(/@(.+)/)[1] Resolv::DNS.open do |dns| dns.timeouts = check_mx_timeout @mx = dns.getresources(domain, Resolv::DNS::Resource::IN::MX) + dns.getresources(domain, Resolv::DNS::Resource::IN::A) end @mx.size > 0 end DEFAULT_MESSAGE = "does not appear to be valid" DEFAULT_MX_MESSAGE = "is not routable" ERROR_MESSAGE_I18N_KEY = :invalid_email_address ERROR_MX_MESSAGE_I18N_KEY = :email_address_not_routable def self.default_message defined?(I18n) ? I18n.t(ERROR_MESSAGE_I18N_KEY, scope: [:activemodel, :errors, :messages], default: DEFAULT_MESSAGE) : DEFAULT_MESSAGE end # Validates whether the specified value is a valid email address. Returns nil if the value is valid, otherwise returns an array # containing one or more validation error messages. # # Configuration options: # * <tt>message</tt> - A custom error message (default is: "does not appear to be valid") # * <tt>check_mx</tt> - Check for MX records (default is false) # * <tt>check_mx_timeout</tt> - Timeout in seconds for checking MX records before a `ResolvTimeout` is raised (default is 3) # * <tt>mx_message</tt> - A custom error message when an MX record validation fails (default is: "is not routable.") - # * <tt>with</tt> The regex to use for validating the format of the email address (deprecated) # * <tt>local_length</tt> Maximum number of characters allowed in the local part (default is 64) # * <tt>domain_length</tt> Maximum number of characters allowed in the domain part (default is 255) # * <tt>generate_message</tt> Return the I18n key of the error message instead of the error message itself (default is false) def self.validate_email_format(email, options = {}) default_options = {message: options[:generate_message] ? ERROR_MESSAGE_I18N_KEY : default_message, check_mx: false, check_mx_timeout: 3, mx_message: if options[:generate_message] ERROR_MX_MESSAGE_I18N_KEY else (defined?(I18n) ? I18n.t(ERROR_MX_MESSAGE_I18N_KEY, scope: [:activemodel, :errors, :messages], default: DEFAULT_MX_MESSAGE) : DEFAULT_MX_MESSAGE) end, domain_length: 255, local_length: 64, generate_message: false} opts = options.merge(default_options) { |key, old, new| old } # merge the default options into the specified options, retaining all specified options begin domain, local = email.reverse.split("@", 2) rescue return [opts[:message]] end # need local and domain parts return [opts[:message]] unless local && !local.empty? && domain && !domain.empty? # check lengths return [opts[:message]] unless domain.length <= opts[:domain_length] && local.length <= opts[:local_length] local.reverse! domain.reverse! if opts.has_key?(:with) # holdover from versions <= 1.4.7 + deprecation_warn(":with option is deprecated and will be removed in the next version") return [opts[:message]] unless email&.match?(opts[:with]) else return [opts[:message]] unless validate_local_part_syntax(local) && validate_domain_part_syntax(domain) end if opts[:check_mx] && !validate_email_domain(email, check_mx_timeout: opts[:check_mx_timeout]) return [opts[:mx_message]] end nil # represents no validation errors end def self.validate_local_part_syntax(local) in_quoted_pair = false in_quoted_string = false comment_depth = 0 (0..local.length - 1).each do |i| ord = local[i].ord # accept anything if it's got a backslash before it if in_quoted_pair in_quoted_pair = false next end if in_quoted_string next if QTEXT.match?(local[i]) end # opening paren to show we are going into a comment (CFWS) if ord == 40 comment_depth += 1 next end # closing paren if ord == 41 comment_depth -= 1 return false if comment_depth < 0 next end # backslash signifies the start of a quoted pair if ord == 92 && i < local.length - 1 return false if !in_quoted_string # must be in quoted string per http://www.rfc-editor.org/errata_search.php?rfc=3696 in_quoted_pair = true next end # double quote delimits quoted strings if ord == 34 in_quoted_string = !in_quoted_string next end if comment_depth > 0 next if CTEXT.match?(local[i]) elsif ATEXT.match?(local[i, 1]) next end # period must be followed by something if ord == 46 return false if i == 0 || i == local.length - 1 # can't be first or last char next unless local[i + 1].ord == 46 # can't be followed by a period end return false end return false if in_quoted_string # unbalanced quotes return false unless comment_depth.zero? # unbalanced comment parens true end def self.validate_domain_part_syntax(domain) parts = domain.downcase.split(".", -1) return false if parts.length <= 1 # Only one domain part # ipv4 return true if parts.length == 4 && parts.all? { |part| part =~ IP_OCTET && part.to_i.between?(0, 255) } # From https://datatracker.ietf.org/doc/html/rfc3696#section-2 this is the recommended, pragmatic way to validate a domain name: # # > It is likely that the better strategy has now become to make the "at least one period" test, # > to verify LDH conformance (including verification that the apparent TLD name is not all-numeric), # > and then to use the DNS to determine domain name validity, rather than trying to maintain # > a local list of valid TLD names. # # We do a little bit more but not too much and validate the tokens but do not check against a list of valid TLDs. parts.each do |part| return false if part.nil? || part.empty? return false if part.length > 63 return false unless DOMAIN_PART_LABEL.match?(part) end return false unless DOMAIN_PART_TLD.match?(parts[-1]) true end + + def self.deprecation_warn(msg) + if defined?(ActiveSupport::Deprecation) + ActiveSupport::Deprecation.warn(msg) + else + warn + end + end end require "validates_email_format_of/active_model" if defined?(::ActiveModel) && !(ActiveModel::VERSION::MAJOR < 2 || (ActiveModel::VERSION::MAJOR == 2 && ActiveModel::VERSION::MINOR < 1)) require "validates_email_format_of/railtie" if defined?(::Rails::Railtie)
validates-email-format-of/validates_email_format_of
2cef2491122ba71bfd78dcee0c74bbb030814222
v1.7.2
diff --git a/CHANGELOG.md b/CHANGELOG.md index de880eb..4fdc199 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,31 +1,35 @@ # CHANGELOG ## [Unreleased] +[Unreleased]: https://github.com/validates-email-format-of/validates_email_format_of/compare/v1.7.2...master + +## [1.7.2] + * Fix regression that disallowed domains starting with number - https://github.com/validates-email-format-of/validates_email_format_of/issues/88 -[Unreleased]: https://github.com/validates-email-format-of/validates_email_format_of/compare/v1.7.1...master +[Unreleased]: https://github.com/validates-email-format-of/validates_email_format_of/compare/v1.7.1...v1.7.2 ## [1.7.1] (3 Aug 2022) * Fix invalid symbols being allowed in the local part - https://github.com/validates-email-format-of/validates_email_format_of/issues/86 * Fix rspec_matcher when using a custom error message - https://github.com/validates-email-format-of/validates_email_format_of/pull/85 - thanks https://github.com/luuqnhu ! [1.7.1]: https://github.com/validates-email-format-of/validates_email_format_of/compare/v1.7.0...v1.7.1 ## [1.7.0] (29 July 2022) * Use Standard.rb for internal code formatting - https://github.com/validates-email-format-of/validates_email_format_of/commit/db1b0a86af58e478b7f9f2f269bf93bf48dc13c1 * Add support for comments in the local part and improve quoted character handling - https://github.com/validates-email-format-of/validates_email_format_of/issues/69 * Improve grammar for parsing domain part and validate domain part lengths - https://github.com/validates-email-format-of/validates_email_format_of/commit/2554b55e547c1fae6599d13b0c99296752888c91 * Do not strip spaces before validating - https://github.com/validates-email-format-of/validates_email_format_of/issues/61 and https://github.com/validates-email-format-of/validates_email_format_of/issues/72 * Allow setting check_mx_timeout and reduce the default timeout to 3 seconds - https://github.com/validates-email-format-of/validates_email_format_of/issues/66 * Fix regex duplicate character warning - https://github.com/validates-email-format-of/validates_email_format_of/pull/71 * Update CI to include Ruby 2.6 to 3.1 and Rails 4.2 to 7.0 [1.7.0]: https://github.com/validates-email-format-of/validates_email_format_of/compare/v1.6.1...v1.7.0 ## [1.6.1] (8 Sept 2014) * In a Rails context, this gem now uses ActiveModel's default logic for constructing I18n keys, to make it easier to override them on a model/attribute basis. [1.6.1]: https://github.com/validates-email-format-of/validates_email_format_of/compare/v1.6.0...v1.6.1 diff --git a/lib/validates_email_format_of/version.rb b/lib/validates_email_format_of/version.rb index 82e02bf..858d528 100644 --- a/lib/validates_email_format_of/version.rb +++ b/lib/validates_email_format_of/version.rb @@ -1,3 +1,3 @@ module ValidatesEmailFormatOf - VERSION = "1.7.1" + VERSION = "1.7.2" end
validates-email-format-of/validates_email_format_of
bf6ac3e7be326b6872b77958167b596c5555b2c2
Allow domain parts beginning with numbers
diff --git a/lib/validates_email_format_of.rb b/lib/validates_email_format_of.rb index 88b7521..2b472a2 100644 --- a/lib/validates_email_format_of.rb +++ b/lib/validates_email_format_of.rb @@ -1,255 +1,262 @@ require "validates_email_format_of/version" module ValidatesEmailFormatOf def self.load_i18n_locales require "i18n" I18n.load_path += Dir.glob(File.expand_path(File.join(File.dirname(__FILE__), "..", "config", "locales", "*.yml"))) end require "resolv" # Characters that are allowed in to appear in the local part unquoted # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.3 # # An addr-spec is a specific Internet identifier that contains a # locally interpreted string followed by the at-sign character ("@", # ASCII value 64) followed by an Internet domain. The locally # interpreted string is either a quoted-string or a dot-atom. If the # string can be represented as a dot-atom (that is, it contains no # characters other than atext characters or "." surrounded by atext # characters), then the dot-atom form SHOULD be used and the quoted- # string form SHOULD NOT be used. Comments and folding white space # SHOULD NOT be used around the "@" in the addr-spec. # # atext = ALPHA / DIGIT / # "!" / "#" / "$" / "%" / "&" / "'" / "*" / # "+" / "-" / "/" / "=" / "?" / "^" / "_" / # "`" / "{" / "|" / "}" / "~" # dot-atom-text = 1*atext *("." 1*atext) # dot-atom = [CFWS] dot-atom-text [CFWS] ATEXT = /\A[A-Z0-9!\#$%&'*\-\/=?+\^_`{|}~]\z/i # Characters that are allowed to appear unquoted in comments # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.2 # # ctext = %d33-39 / %d42-91 / %d93-126 # ccontent = ctext / quoted-pair / comment # comment = "(" *([FWS] ccontent) [FWS] ")" # CFWS = (1*([FWS] comment) [FWS]) / FWS CTEXT = /\A[#{Regexp.escape([33..39, 42..91, 93..126].map { |ascii_range| ascii_range.map(&:chr) }.flatten.join)}\s]/i # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.4 # # Strings of characters that include characters other than those # allowed in atoms can be represented in a quoted string format, where # the characters are surrounded by quote (DQUOTE, ASCII value 34) # characters. # # qtext = %d33 / ; Printable US-ASCII # %d35-91 / ; characters not including # %d93-126 / ; "\" or the quote character # obs-qtext # # qcontent = qtext / quoted-pair # quoted-string = [CFWS] # DQUOTE *([FWS] qcontent) [FWS] DQUOTE # [CFWS] QTEXT = /\A[#{Regexp.escape([33..33, 35..91, 93..126].map { |ascii_range| ascii_range.map(&:chr) }.flatten.join)}\s]/i IP_OCTET = /\A[0-9]+\Z/ # From https://datatracker.ietf.org/doc/html/rfc1035#section-2.3.1 # # > The labels must follow the rules for ARPANET host names. They must # > start with a letter, end with a letter or digit, and have as interior # > characters only letters, digits, and hyphen. There are also some # > restrictions on the length. Labels must be 63 characters or less. # # <label> | <subdomain> "." <label> # <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ] # <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str> # <let-dig-hyp> ::= <let-dig> | "-" # <let-dig> ::= <letter> | <digit> - DOMAIN_PART_LABEL = /\A[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9]?\Z/ + # + # Additionally, from https://datatracker.ietf.org/doc/html/rfc1123#section-2.1 + # + # > One aspect of host name syntax is hereby changed: the + # > restriction on the first character is relaxed to allow either a + # > letter or a digit. Host software MUST support this more liberal + # > syntax. + DOMAIN_PART_LABEL = /\A[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9]?\Z/ # From https://tools.ietf.org/id/draft-liman-tld-names-00.html#rfc.section.2 # # > A TLD label MUST be at least two characters long and MAY be as long as 63 characters - # > not counting any leading or trailing periods (.). It MUST consist of only ASCII characters # > from the groups "letters" (A-Z), "digits" (0-9) and "hyphen" (-), and it MUST start with an # > ASCII "letter", and it MUST NOT end with a "hyphen". Upper and lower case MAY be mixed at random, # > since DNS lookups are case-insensitive. # # tldlabel = ALPHA *61(ldh) ld # ldh = ld / "-" # ld = ALPHA / DIGIT # ALPHA = %x41-5A / %x61-7A ; A-Z / a-z # DIGIT = %x30-39 ; 0-9 DOMAIN_PART_TLD = /\A[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9]\Z/ def self.validate_email_domain(email, check_mx_timeout: 3) domain = email.to_s.downcase.match(/@(.+)/)[1] Resolv::DNS.open do |dns| dns.timeouts = check_mx_timeout @mx = dns.getresources(domain, Resolv::DNS::Resource::IN::MX) + dns.getresources(domain, Resolv::DNS::Resource::IN::A) end @mx.size > 0 end DEFAULT_MESSAGE = "does not appear to be valid" DEFAULT_MX_MESSAGE = "is not routable" ERROR_MESSAGE_I18N_KEY = :invalid_email_address ERROR_MX_MESSAGE_I18N_KEY = :email_address_not_routable def self.default_message defined?(I18n) ? I18n.t(ERROR_MESSAGE_I18N_KEY, scope: [:activemodel, :errors, :messages], default: DEFAULT_MESSAGE) : DEFAULT_MESSAGE end # Validates whether the specified value is a valid email address. Returns nil if the value is valid, otherwise returns an array # containing one or more validation error messages. # # Configuration options: # * <tt>message</tt> - A custom error message (default is: "does not appear to be valid") # * <tt>check_mx</tt> - Check for MX records (default is false) # * <tt>check_mx_timeout</tt> - Timeout in seconds for checking MX records before a `ResolvTimeout` is raised (default is 3) # * <tt>mx_message</tt> - A custom error message when an MX record validation fails (default is: "is not routable.") # * <tt>with</tt> The regex to use for validating the format of the email address (deprecated) # * <tt>local_length</tt> Maximum number of characters allowed in the local part (default is 64) # * <tt>domain_length</tt> Maximum number of characters allowed in the domain part (default is 255) # * <tt>generate_message</tt> Return the I18n key of the error message instead of the error message itself (default is false) def self.validate_email_format(email, options = {}) default_options = {message: options[:generate_message] ? ERROR_MESSAGE_I18N_KEY : default_message, check_mx: false, check_mx_timeout: 3, mx_message: if options[:generate_message] ERROR_MX_MESSAGE_I18N_KEY else (defined?(I18n) ? I18n.t(ERROR_MX_MESSAGE_I18N_KEY, scope: [:activemodel, :errors, :messages], default: DEFAULT_MX_MESSAGE) : DEFAULT_MX_MESSAGE) end, domain_length: 255, local_length: 64, generate_message: false} opts = options.merge(default_options) { |key, old, new| old } # merge the default options into the specified options, retaining all specified options begin domain, local = email.reverse.split("@", 2) rescue return [opts[:message]] end # need local and domain parts return [opts[:message]] unless local && !local.empty? && domain && !domain.empty? # check lengths return [opts[:message]] unless domain.length <= opts[:domain_length] && local.length <= opts[:local_length] local.reverse! domain.reverse! if opts.has_key?(:with) # holdover from versions <= 1.4.7 return [opts[:message]] unless email&.match?(opts[:with]) else return [opts[:message]] unless validate_local_part_syntax(local) && validate_domain_part_syntax(domain) end if opts[:check_mx] && !validate_email_domain(email, check_mx_timeout: opts[:check_mx_timeout]) return [opts[:mx_message]] end nil # represents no validation errors end def self.validate_local_part_syntax(local) in_quoted_pair = false in_quoted_string = false comment_depth = 0 (0..local.length - 1).each do |i| ord = local[i].ord # accept anything if it's got a backslash before it if in_quoted_pair in_quoted_pair = false next end if in_quoted_string next if QTEXT.match?(local[i]) end # opening paren to show we are going into a comment (CFWS) if ord == 40 comment_depth += 1 next end # closing paren if ord == 41 comment_depth -= 1 return false if comment_depth < 0 next end # backslash signifies the start of a quoted pair if ord == 92 && i < local.length - 1 return false if !in_quoted_string # must be in quoted string per http://www.rfc-editor.org/errata_search.php?rfc=3696 in_quoted_pair = true next end # double quote delimits quoted strings if ord == 34 in_quoted_string = !in_quoted_string next end if comment_depth > 0 next if CTEXT.match?(local[i]) elsif ATEXT.match?(local[i, 1]) next end # period must be followed by something if ord == 46 return false if i == 0 || i == local.length - 1 # can't be first or last char next unless local[i + 1].ord == 46 # can't be followed by a period end return false end return false if in_quoted_string # unbalanced quotes return false unless comment_depth.zero? # unbalanced comment parens true end def self.validate_domain_part_syntax(domain) parts = domain.downcase.split(".", -1) return false if parts.length <= 1 # Only one domain part # ipv4 return true if parts.length == 4 && parts.all? { |part| part =~ IP_OCTET && part.to_i.between?(0, 255) } # From https://datatracker.ietf.org/doc/html/rfc3696#section-2 this is the recommended, pragmatic way to validate a domain name: # # > It is likely that the better strategy has now become to make the "at least one period" test, # > to verify LDH conformance (including verification that the apparent TLD name is not all-numeric), # > and then to use the DNS to determine domain name validity, rather than trying to maintain # > a local list of valid TLD names. # # We do a little bit more but not too much and validate the tokens but do not check against a list of valid TLDs. parts.each do |part| return false if part.nil? || part.empty? return false if part.length > 63 return false unless DOMAIN_PART_LABEL.match?(part) end return false unless DOMAIN_PART_TLD.match?(parts[-1]) true end end require "validates_email_format_of/active_model" if defined?(::ActiveModel) && !(ActiveModel::VERSION::MAJOR < 2 || (ActiveModel::VERSION::MAJOR == 2 && ActiveModel::VERSION::MINOR < 1)) require "validates_email_format_of/railtie" if defined?(::Rails::Railtie) diff --git a/spec/validates_email_format_of_spec.rb b/spec/validates_email_format_of_spec.rb index 30cc586..51d3085 100644 --- a/spec/validates_email_format_of_spec.rb +++ b/spec/validates_email_format_of_spec.rb @@ -1,327 +1,328 @@ require "#{__dir__}/spec_helper" require "validates_email_format_of" RSpec.configure do |config| config.before(:suite) do ValidatesEmailFormatOf.load_i18n_locales I18n.enforce_available_locales = false end end describe ValidatesEmailFormatOf do subject do |example| user = Class.new do def initialize(email) @email = email.freeze end attr_reader :email include ActiveModel::Validations validates_email_format_of :email, example.example_group_instance.options def self.model_name ActiveModel::Name.new(self, nil, "User") end end user.new(example.example_group_instance.email).tap(&:valid?).errors.full_messages end let(:options) { {} } let(:email) { |example| example.example_group.description } shared_examples_for :all_specs do [ "valid@example.com", "Valid@test.example.com", "valid+valid123@test.example.com", "valid_valid123@test.example.com", "valid-valid+123@test.example.co.uk", "valid-valid+1.23@test.example.com.au", + "valid@1example.com", "valid@example.co.uk", "v@example.com", "valid@example.ca", "valid_@example.com", "valid123.456@example.org", "valid123.456@example.travel", "valid123.456@example.museum", "valid@example.mobi", "valid@example.info", "valid-@example.com", "fake@p-t.k12.ok.us", # allow single character domain parts "valid@mail.x.example.com", "valid@x.com", "valid@example.w-dash.sch.uk", # from RFC 3696, page 6 "customer/department=shipping@example.com", "$A12345@example.com", "!def!xyz%abc@example.com", "_somename@example.com", # apostrophes "test'test@example.com", # international domain names "test@xn--bcher-kva.ch", "test@example.xn--0zwm56d", "test@192.192.192.1", # Allow quoted characters. Valid according to http://www.rfc-editor.org/errata_search.php?rfc=3696 '"Abc\@def"@example.com', '"Quote(Only".Chars@wier.de', '"Fred\ Bloggs"@example.com', '"Joe.\\Blow"@example.com', # Balanced quoted characters %("example\\\\\\""@example.com), %("example\\\\"@example.com), "(leading comment)email@example.com", "(nested (comment))email@example.com", "email(trailing comment)@example.com" ].each do |address| describe address do it { should_not have_errors_on_email } end end [ "no_at_symbol", "multiple@at@symbols.com", "invalid@example-com", # period can not start local part ".invalid@example.com", # period can not end local part "invalid.@example.com", # period can not appear twice consecutively in local part "invali..d@example.com", # should not allow underscores in domain names "invalid@ex_mple.com", "invalid@e..example.com", "invalid@p-t..example.com", "invalid@example.com.", "invalid@example.com_", "invalid@example.com-", "invalid-example.com", "invalid@example.b#r.com", "invalid@example.c", "invali d@example.com", # TLD can not be only numeric "invalid@example.123", # unclosed quote "\"a-17180061943-10618354-1993365053@example.com", # too many special chars used to cause the regexp to hang "-+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++@foo", "invalidexample.com", # should not allow special chars after a period in the domain "local@sub.)domain.com", "local@sub.#domain.com", # one at a time "foo@example.com\nexample@gmail.com", "invalid@example.", "\"foo\\\\\"\"@bar.com", "foo@mail.com\r\nfoo@mail.com", "@example.com", "foo@", "foo", "Iñtërnâtiônàlizætiøn@hasnt.happened.to.email", # Escaped characters with quotes. From http://tools.ietf.org/html/rfc3696, page 5. Corrected in http://www.rfc-editor.org/errata_search.php?rfc=3696 'Fred\ Bloggs_@example.com', 'Abc\@def+@example.com', 'Joe.\\Blow@example.com', # Unbalanced quoted characters %("example\\\\""example.com), "\nnewline@example.com", " spacesbefore@example.com", "spacesafter@example.com ", "(unbalancedcomment@example.com" ].each do |address| describe address do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe do shared_examples_for :local_length_limit do |limit| describe "#{"a" * limit}@example.com" do it { should_not have_errors_on_email } end describe "#{"a" * (limit + 1)}@example.com" do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "when using default" do it_should_behave_like :local_length_limit, 64 end describe "when overriding defaults" do let(:options) { {local_length: 20} } it_should_behave_like :local_length_limit, 20 end end describe do shared_examples_for :domain_length_limit do |limit| describe "user@#{"a." * (limit / 2 - 3)}com" do it { should_not have_errors_on_email } end describe "user@#{"a." * (limit / 2 + 1)}com" do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "when using default" do it_should_behave_like :domain_length_limit, 255 end describe "when overriding defaults" do let(:options) { {domain_length: 100} } it_should_behave_like :domain_length_limit, 100 end end describe "custom error messages" do describe "invalid@example." do let(:options) { {message: "just because I don't like you"} } it { should have_errors_on_email.because("just because I don't like you") } end end describe "mx record" do domain = "example.com" email = "valid@#{domain}" describe "when testing" do let(:dns) { double(Resolv::DNS) } let(:mx_record) { [double] } let(:a_record) { [double] } before(:each) do allow(Resolv::DNS).to receive(:open).and_yield(dns) allow(dns).to receive(:"timeouts=").with(3).once allow(dns).to receive(:getresources).with(domain, Resolv::DNS::Resource::IN::MX).once.and_return(mx_record) allow(dns).to receive(:getresources).with(domain, Resolv::DNS::Resource::IN::A).once.and_return(a_record) end let(:options) { {check_mx: true, check_mx_timeout: 3} } describe "and only an mx record is found" do let(:a_record) { [] } describe email do it { should_not have_errors_on_email } end end describe "and only an a record is found" do let(:mx_record) { [] } describe email do it { should_not have_errors_on_email } end end describe "and both an mx record and an a record are found" do describe email do it { should_not have_errors_on_email } end end describe "and neither an mx record nor an a record is found" do let(:a_record) { [] } let(:mx_record) { [] } describe email do it { should have_errors_on_email.because("is not routable") } end describe "with a custom error message" do let(:options) { {check_mx: true, mx_message: "There ain't no such domain!"} } describe email do it { should have_errors_on_email.because("There ain't no such domain!") } end end describe "i18n" do before(:each) do allow(I18n.config).to receive(:locale).and_return(locale) end describe "present locale" do let(:locale) { :pl } describe email do it { should have_errors_on_email.because("jest nieosiągalny") } end end end end end describe "when not testing" do before(:each) { allow(Resolv::DNS).to receive(:open).never } describe "by default" do describe email do it { should_not have_errors_on_email } end end describe "explicitly" do describe email do let(:options) { {check_mx: false} } it { should_not have_errors_on_email } end end end describe "without mocks" do describe email do let(:options) { {check_mx: true} } it { should_not have_errors_on_email } end end end describe "custom regex" do let(:options) { {with: /[0-9]+@[0-9]+/} } describe "012345@789" do it { should_not have_errors_on_email } end describe "valid@example.com" do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "i18n" do before(:each) do allow(I18n.config).to receive(:locale).and_return(locale) end describe "present locale" do let(:locale) { :pl } describe "invalid@exmaple." do it { should have_errors_on_email.because("nieprawidłowy adres e-mail") } end end end end it_should_behave_like :all_specs describe "validation without ActiveModel" do subject do ValidatesEmailFormatOf.validate_email_format(email.freeze, options) end describe "valid@example.com" do it { should be_nil } end describe "custom error messages" do describe "invalid@example." do let(:options) { {message: "just because I don't like you"} } it { should match_array(["just because I don't like you"]) } end end describe "without i18n" do before(:each) { hide_const("I18n") } describe "invalid@exmaple." do it { should match_array(["does not appear to be valid"]) } end end end describe "shorthand ActiveModel validation" do subject do |example| user = Class.new do def initialize(email) @email = email.freeze end attr_reader :email include ActiveModel::Validations validates :email, email_format: example.example_group_instance.options def self.model_name ActiveModel::Name.new(self, nil, "User") end end user.new(example.example_group_instance.email).tap(&:valid?).errors.full_messages end it_should_behave_like :all_specs end end
validates-email-format-of/validates_email_format_of
21e0aff1c78514f611c236757d44f8ab1e93e529
v1.7.1
diff --git a/lib/validates_email_format_of/version.rb b/lib/validates_email_format_of/version.rb index 8c8dc37..82e02bf 100644 --- a/lib/validates_email_format_of/version.rb +++ b/lib/validates_email_format_of/version.rb @@ -1,3 +1,3 @@ module ValidatesEmailFormatOf - VERSION = "1.7.0" + VERSION = "1.7.1" end
validates-email-format-of/validates_email_format_of
fee02366adca3f67ddd2e635386ba260de9db056
Fix allowed symbols in atom-text
diff --git a/lib/validates_email_format_of.rb b/lib/validates_email_format_of.rb index 6b067a1..88b7521 100644 --- a/lib/validates_email_format_of.rb +++ b/lib/validates_email_format_of.rb @@ -1,253 +1,255 @@ require "validates_email_format_of/version" module ValidatesEmailFormatOf def self.load_i18n_locales require "i18n" I18n.load_path += Dir.glob(File.expand_path(File.join(File.dirname(__FILE__), "..", "config", "locales", "*.yml"))) end require "resolv" - ATEXT_SYMBOLS = /[!\#$%&'*\-\/=?+\^_`{|}~]/ - # Characters that are allowed in to appear in the local part unquoted - # https://www.rfc-editor.org/rfc/rfc5322#section-3.4.1 + # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.3 # # An addr-spec is a specific Internet identifier that contains a # locally interpreted string followed by the at-sign character ("@", # ASCII value 64) followed by an Internet domain. The locally # interpreted string is either a quoted-string or a dot-atom. If the # string can be represented as a dot-atom (that is, it contains no # characters other than atext characters or "." surrounded by atext # characters), then the dot-atom form SHOULD be used and the quoted- # string form SHOULD NOT be used. Comments and folding white space # SHOULD NOT be used around the "@" in the addr-spec. # + # atext = ALPHA / DIGIT / + # "!" / "#" / "$" / "%" / "&" / "'" / "*" / + # "+" / "-" / "/" / "=" / "?" / "^" / "_" / + # "`" / "{" / "|" / "}" / "~" # dot-atom-text = 1*atext *("." 1*atext) # dot-atom = [CFWS] dot-atom-text [CFWS] - ATEXT = /\A[A-Z0-9#{ATEXT_SYMBOLS}]\z/i + ATEXT = /\A[A-Z0-9!\#$%&'*\-\/=?+\^_`{|}~]\z/i # Characters that are allowed to appear unquoted in comments # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.2 # # ctext = %d33-39 / %d42-91 / %d93-126 # ccontent = ctext / quoted-pair / comment # comment = "(" *([FWS] ccontent) [FWS] ")" # CFWS = (1*([FWS] comment) [FWS]) / FWS CTEXT = /\A[#{Regexp.escape([33..39, 42..91, 93..126].map { |ascii_range| ascii_range.map(&:chr) }.flatten.join)}\s]/i # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.4 # # Strings of characters that include characters other than those # allowed in atoms can be represented in a quoted string format, where # the characters are surrounded by quote (DQUOTE, ASCII value 34) # characters. # # qtext = %d33 / ; Printable US-ASCII # %d35-91 / ; characters not including # %d93-126 / ; "\" or the quote character # obs-qtext # # qcontent = qtext / quoted-pair # quoted-string = [CFWS] # DQUOTE *([FWS] qcontent) [FWS] DQUOTE # [CFWS] QTEXT = /\A[#{Regexp.escape([33..33, 35..91, 93..126].map { |ascii_range| ascii_range.map(&:chr) }.flatten.join)}\s]/i IP_OCTET = /\A[0-9]+\Z/ # From https://datatracker.ietf.org/doc/html/rfc1035#section-2.3.1 # # > The labels must follow the rules for ARPANET host names. They must # > start with a letter, end with a letter or digit, and have as interior # > characters only letters, digits, and hyphen. There are also some # > restrictions on the length. Labels must be 63 characters or less. # # <label> | <subdomain> "." <label> # <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ] # <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str> # <let-dig-hyp> ::= <let-dig> | "-" # <let-dig> ::= <letter> | <digit> DOMAIN_PART_LABEL = /\A[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9]?\Z/ # From https://tools.ietf.org/id/draft-liman-tld-names-00.html#rfc.section.2 # # > A TLD label MUST be at least two characters long and MAY be as long as 63 characters - # > not counting any leading or trailing periods (.). It MUST consist of only ASCII characters # > from the groups "letters" (A-Z), "digits" (0-9) and "hyphen" (-), and it MUST start with an # > ASCII "letter", and it MUST NOT end with a "hyphen". Upper and lower case MAY be mixed at random, # > since DNS lookups are case-insensitive. # # tldlabel = ALPHA *61(ldh) ld # ldh = ld / "-" # ld = ALPHA / DIGIT # ALPHA = %x41-5A / %x61-7A ; A-Z / a-z # DIGIT = %x30-39 ; 0-9 DOMAIN_PART_TLD = /\A[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9]\Z/ def self.validate_email_domain(email, check_mx_timeout: 3) domain = email.to_s.downcase.match(/@(.+)/)[1] Resolv::DNS.open do |dns| dns.timeouts = check_mx_timeout @mx = dns.getresources(domain, Resolv::DNS::Resource::IN::MX) + dns.getresources(domain, Resolv::DNS::Resource::IN::A) end @mx.size > 0 end DEFAULT_MESSAGE = "does not appear to be valid" DEFAULT_MX_MESSAGE = "is not routable" ERROR_MESSAGE_I18N_KEY = :invalid_email_address ERROR_MX_MESSAGE_I18N_KEY = :email_address_not_routable def self.default_message defined?(I18n) ? I18n.t(ERROR_MESSAGE_I18N_KEY, scope: [:activemodel, :errors, :messages], default: DEFAULT_MESSAGE) : DEFAULT_MESSAGE end # Validates whether the specified value is a valid email address. Returns nil if the value is valid, otherwise returns an array # containing one or more validation error messages. # # Configuration options: # * <tt>message</tt> - A custom error message (default is: "does not appear to be valid") # * <tt>check_mx</tt> - Check for MX records (default is false) # * <tt>check_mx_timeout</tt> - Timeout in seconds for checking MX records before a `ResolvTimeout` is raised (default is 3) # * <tt>mx_message</tt> - A custom error message when an MX record validation fails (default is: "is not routable.") # * <tt>with</tt> The regex to use for validating the format of the email address (deprecated) # * <tt>local_length</tt> Maximum number of characters allowed in the local part (default is 64) # * <tt>domain_length</tt> Maximum number of characters allowed in the domain part (default is 255) # * <tt>generate_message</tt> Return the I18n key of the error message instead of the error message itself (default is false) def self.validate_email_format(email, options = {}) default_options = {message: options[:generate_message] ? ERROR_MESSAGE_I18N_KEY : default_message, check_mx: false, check_mx_timeout: 3, mx_message: if options[:generate_message] ERROR_MX_MESSAGE_I18N_KEY else (defined?(I18n) ? I18n.t(ERROR_MX_MESSAGE_I18N_KEY, scope: [:activemodel, :errors, :messages], default: DEFAULT_MX_MESSAGE) : DEFAULT_MX_MESSAGE) end, domain_length: 255, local_length: 64, generate_message: false} opts = options.merge(default_options) { |key, old, new| old } # merge the default options into the specified options, retaining all specified options begin domain, local = email.reverse.split("@", 2) rescue return [opts[:message]] end # need local and domain parts return [opts[:message]] unless local && !local.empty? && domain && !domain.empty? # check lengths return [opts[:message]] unless domain.length <= opts[:domain_length] && local.length <= opts[:local_length] local.reverse! domain.reverse! if opts.has_key?(:with) # holdover from versions <= 1.4.7 return [opts[:message]] unless email&.match?(opts[:with]) else return [opts[:message]] unless validate_local_part_syntax(local) && validate_domain_part_syntax(domain) end if opts[:check_mx] && !validate_email_domain(email, check_mx_timeout: opts[:check_mx_timeout]) return [opts[:mx_message]] end nil # represents no validation errors end def self.validate_local_part_syntax(local) in_quoted_pair = false in_quoted_string = false comment_depth = 0 (0..local.length - 1).each do |i| ord = local[i].ord # accept anything if it's got a backslash before it if in_quoted_pair in_quoted_pair = false next end if in_quoted_string next if QTEXT.match?(local[i]) end # opening paren to show we are going into a comment (CFWS) if ord == 40 comment_depth += 1 next end # closing paren if ord == 41 comment_depth -= 1 return false if comment_depth < 0 next end # backslash signifies the start of a quoted pair if ord == 92 && i < local.length - 1 return false if !in_quoted_string # must be in quoted string per http://www.rfc-editor.org/errata_search.php?rfc=3696 in_quoted_pair = true next end # double quote delimits quoted strings if ord == 34 in_quoted_string = !in_quoted_string next end if comment_depth > 0 next if CTEXT.match?(local[i]) elsif ATEXT.match?(local[i, 1]) next end # period must be followed by something if ord == 46 return false if i == 0 || i == local.length - 1 # can't be first or last char next unless local[i + 1].ord == 46 # can't be followed by a period end return false end return false if in_quoted_string # unbalanced quotes return false unless comment_depth.zero? # unbalanced comment parens true end def self.validate_domain_part_syntax(domain) parts = domain.downcase.split(".", -1) return false if parts.length <= 1 # Only one domain part # ipv4 return true if parts.length == 4 && parts.all? { |part| part =~ IP_OCTET && part.to_i.between?(0, 255) } # From https://datatracker.ietf.org/doc/html/rfc3696#section-2 this is the recommended, pragmatic way to validate a domain name: # # > It is likely that the better strategy has now become to make the "at least one period" test, # > to verify LDH conformance (including verification that the apparent TLD name is not all-numeric), # > and then to use the DNS to determine domain name validity, rather than trying to maintain # > a local list of valid TLD names. # # We do a little bit more but not too much and validate the tokens but do not check against a list of valid TLDs. parts.each do |part| return false if part.nil? || part.empty? return false if part.length > 63 return false unless DOMAIN_PART_LABEL.match?(part) end return false unless DOMAIN_PART_TLD.match?(parts[-1]) true end end require "validates_email_format_of/active_model" if defined?(::ActiveModel) && !(ActiveModel::VERSION::MAJOR < 2 || (ActiveModel::VERSION::MAJOR == 2 && ActiveModel::VERSION::MINOR < 1)) require "validates_email_format_of/railtie" if defined?(::Rails::Railtie) diff --git a/spec/validates_email_format_of_spec.rb b/spec/validates_email_format_of_spec.rb index e5fa6bb..30cc586 100644 --- a/spec/validates_email_format_of_spec.rb +++ b/spec/validates_email_format_of_spec.rb @@ -1,326 +1,327 @@ require "#{__dir__}/spec_helper" require "validates_email_format_of" RSpec.configure do |config| config.before(:suite) do ValidatesEmailFormatOf.load_i18n_locales I18n.enforce_available_locales = false end end describe ValidatesEmailFormatOf do subject do |example| user = Class.new do def initialize(email) @email = email.freeze end attr_reader :email include ActiveModel::Validations validates_email_format_of :email, example.example_group_instance.options def self.model_name ActiveModel::Name.new(self, nil, "User") end end user.new(example.example_group_instance.email).tap(&:valid?).errors.full_messages end let(:options) { {} } let(:email) { |example| example.example_group.description } shared_examples_for :all_specs do [ "valid@example.com", "Valid@test.example.com", "valid+valid123@test.example.com", "valid_valid123@test.example.com", "valid-valid+123@test.example.co.uk", "valid-valid+1.23@test.example.com.au", "valid@example.co.uk", "v@example.com", "valid@example.ca", "valid_@example.com", "valid123.456@example.org", "valid123.456@example.travel", "valid123.456@example.museum", "valid@example.mobi", "valid@example.info", "valid-@example.com", "fake@p-t.k12.ok.us", # allow single character domain parts "valid@mail.x.example.com", "valid@x.com", "valid@example.w-dash.sch.uk", # from RFC 3696, page 6 "customer/department=shipping@example.com", "$A12345@example.com", "!def!xyz%abc@example.com", "_somename@example.com", # apostrophes "test'test@example.com", # international domain names "test@xn--bcher-kva.ch", "test@example.xn--0zwm56d", "test@192.192.192.1", # Allow quoted characters. Valid according to http://www.rfc-editor.org/errata_search.php?rfc=3696 '"Abc\@def"@example.com', '"Quote(Only".Chars@wier.de', '"Fred\ Bloggs"@example.com', '"Joe.\\Blow"@example.com', # Balanced quoted characters %("example\\\\\\""@example.com), %("example\\\\"@example.com), "(leading comment)email@example.com", "(nested (comment))email@example.com", "email(trailing comment)@example.com" ].each do |address| describe address do it { should_not have_errors_on_email } end end [ "no_at_symbol", + "multiple@at@symbols.com", "invalid@example-com", # period can not start local part ".invalid@example.com", # period can not end local part "invalid.@example.com", # period can not appear twice consecutively in local part "invali..d@example.com", # should not allow underscores in domain names "invalid@ex_mple.com", "invalid@e..example.com", "invalid@p-t..example.com", "invalid@example.com.", "invalid@example.com_", "invalid@example.com-", "invalid-example.com", "invalid@example.b#r.com", "invalid@example.c", "invali d@example.com", # TLD can not be only numeric "invalid@example.123", # unclosed quote "\"a-17180061943-10618354-1993365053@example.com", # too many special chars used to cause the regexp to hang "-+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++@foo", "invalidexample.com", # should not allow special chars after a period in the domain "local@sub.)domain.com", "local@sub.#domain.com", # one at a time "foo@example.com\nexample@gmail.com", "invalid@example.", "\"foo\\\\\"\"@bar.com", "foo@mail.com\r\nfoo@mail.com", "@example.com", "foo@", "foo", "Iñtërnâtiônàlizætiøn@hasnt.happened.to.email", # Escaped characters with quotes. From http://tools.ietf.org/html/rfc3696, page 5. Corrected in http://www.rfc-editor.org/errata_search.php?rfc=3696 'Fred\ Bloggs_@example.com', 'Abc\@def+@example.com', 'Joe.\\Blow@example.com', # Unbalanced quoted characters %("example\\\\""example.com), "\nnewline@example.com", " spacesbefore@example.com", "spacesafter@example.com ", "(unbalancedcomment@example.com" ].each do |address| describe address do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe do shared_examples_for :local_length_limit do |limit| describe "#{"a" * limit}@example.com" do it { should_not have_errors_on_email } end describe "#{"a" * (limit + 1)}@example.com" do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "when using default" do it_should_behave_like :local_length_limit, 64 end describe "when overriding defaults" do let(:options) { {local_length: 20} } it_should_behave_like :local_length_limit, 20 end end describe do shared_examples_for :domain_length_limit do |limit| describe "user@#{"a." * (limit / 2 - 3)}com" do it { should_not have_errors_on_email } end describe "user@#{"a." * (limit / 2 + 1)}com" do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "when using default" do it_should_behave_like :domain_length_limit, 255 end describe "when overriding defaults" do let(:options) { {domain_length: 100} } it_should_behave_like :domain_length_limit, 100 end end describe "custom error messages" do describe "invalid@example." do let(:options) { {message: "just because I don't like you"} } it { should have_errors_on_email.because("just because I don't like you") } end end describe "mx record" do domain = "example.com" email = "valid@#{domain}" describe "when testing" do let(:dns) { double(Resolv::DNS) } let(:mx_record) { [double] } let(:a_record) { [double] } before(:each) do allow(Resolv::DNS).to receive(:open).and_yield(dns) allow(dns).to receive(:"timeouts=").with(3).once allow(dns).to receive(:getresources).with(domain, Resolv::DNS::Resource::IN::MX).once.and_return(mx_record) allow(dns).to receive(:getresources).with(domain, Resolv::DNS::Resource::IN::A).once.and_return(a_record) end let(:options) { {check_mx: true, check_mx_timeout: 3} } describe "and only an mx record is found" do let(:a_record) { [] } describe email do it { should_not have_errors_on_email } end end describe "and only an a record is found" do let(:mx_record) { [] } describe email do it { should_not have_errors_on_email } end end describe "and both an mx record and an a record are found" do describe email do it { should_not have_errors_on_email } end end describe "and neither an mx record nor an a record is found" do let(:a_record) { [] } let(:mx_record) { [] } describe email do it { should have_errors_on_email.because("is not routable") } end describe "with a custom error message" do let(:options) { {check_mx: true, mx_message: "There ain't no such domain!"} } describe email do it { should have_errors_on_email.because("There ain't no such domain!") } end end describe "i18n" do before(:each) do allow(I18n.config).to receive(:locale).and_return(locale) end describe "present locale" do let(:locale) { :pl } describe email do it { should have_errors_on_email.because("jest nieosiągalny") } end end end end end describe "when not testing" do before(:each) { allow(Resolv::DNS).to receive(:open).never } describe "by default" do describe email do it { should_not have_errors_on_email } end end describe "explicitly" do describe email do let(:options) { {check_mx: false} } it { should_not have_errors_on_email } end end end describe "without mocks" do describe email do let(:options) { {check_mx: true} } it { should_not have_errors_on_email } end end end describe "custom regex" do let(:options) { {with: /[0-9]+@[0-9]+/} } describe "012345@789" do it { should_not have_errors_on_email } end describe "valid@example.com" do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "i18n" do before(:each) do allow(I18n.config).to receive(:locale).and_return(locale) end describe "present locale" do let(:locale) { :pl } describe "invalid@exmaple." do it { should have_errors_on_email.because("nieprawidłowy adres e-mail") } end end end end it_should_behave_like :all_specs describe "validation without ActiveModel" do subject do ValidatesEmailFormatOf.validate_email_format(email.freeze, options) end describe "valid@example.com" do it { should be_nil } end describe "custom error messages" do describe "invalid@example." do let(:options) { {message: "just because I don't like you"} } it { should match_array(["just because I don't like you"]) } end end describe "without i18n" do before(:each) { hide_const("I18n") } describe "invalid@exmaple." do it { should match_array(["does not appear to be valid"]) } end end end describe "shorthand ActiveModel validation" do subject do |example| user = Class.new do def initialize(email) @email = email.freeze end attr_reader :email include ActiveModel::Validations validates :email, email_format: example.example_group_instance.options def self.model_name ActiveModel::Name.new(self, nil, "User") end end user.new(example.example_group_instance.email).tap(&:valid?).errors.full_messages end it_should_behave_like :all_specs end end
validates-email-format-of/validates_email_format_of
868c8ca1776b69f2bf52406f8956c84ed60b2a60
Fix rspec run fail when using custom error message
diff --git a/lib/validates_email_format_of/rspec_matcher.rb b/lib/validates_email_format_of/rspec_matcher.rb index 4ae6638..3498c36 100644 --- a/lib/validates_email_format_of/rspec_matcher.rb +++ b/lib/validates_email_format_of/rspec_matcher.rb @@ -1,14 +1,14 @@ require "validates_email_format_of" RSpec::Matchers.define :validate_email_format_of do |attribute| match do actual = subject.is_a?(Class) ? subject.new : subject actual.send(:"#{attribute}=", "invalid@example.") expect(actual).to be_invalid @expected_message ||= ValidatesEmailFormatOf.default_message - expect(actual.errors.added?(attribute, :invalid_email_address)).to be_truthy + expect(actual.errors.added?(attribute, @expected_message)).to be_truthy end chain :with_message do |message| @expected_message = message end end
validates-email-format-of/validates_email_format_of
bdd5048e7b36637d381c36b050873a79b1d61567
Bump version to 1.7.0
diff --git a/lib/validates_email_format_of/version.rb b/lib/validates_email_format_of/version.rb index ac9b371..8c8dc37 100644 --- a/lib/validates_email_format_of/version.rb +++ b/lib/validates_email_format_of/version.rb @@ -1,3 +1,3 @@ module ValidatesEmailFormatOf - VERSION = "1.6.3" + VERSION = "1.7.0" end
validates-email-format-of/validates_email_format_of
7cebb48a6d22c51d6184bba4526e3ed9e8301b86
Always run specs with activemodel
diff --git a/spec/rspec_matcher_spec.rb b/spec/rspec_matcher_spec.rb index 37ee2f6..a80c1ff 100644 --- a/spec/rspec_matcher_spec.rb +++ b/spec/rspec_matcher_spec.rb @@ -1,14 +1,12 @@ require "#{__dir__}/spec_helper" -if defined?(ActiveModel) - require "validates_email_format_of/rspec_matcher" +require "validates_email_format_of/rspec_matcher" - class Person - attr_accessor :email_address - include ::ActiveModel::Validations - validates_email_format_of :email_address - end +class Person + attr_accessor :email_address + include ::ActiveModel::Validations + validates_email_format_of :email_address +end - describe Person do - it { should validate_email_format_of(:email_address) } - end +describe Person do + it { should validate_email_format_of(:email_address) } end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 795d852..d6cc154 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,24 +1,25 @@ -require "active_model" if Gem.loaded_specs.key?("activemodel") +require "active_model" +require "active_support" require "pry" require "byebug" RSpec::Matchers.define :have_errors_on_email do match do |actual| expect(actual).not_to be_nil, "#{actual} should not be nil" expect(actual).not_to be_empty, "#{actual} should not be empty" expect(actual.size).to eq(@reasons.size), "#{actual} should have #{@reasons.size} elements" @reasons.each do |reason| - reason = "#{"Email " if defined?(ActiveModel)}#{reason}" + reason = "Email #{reason}" expect(actual).to include(reason), "#{actual} should contain #{reason}" end end chain :because do |reason| (@reasons ||= []) << reason end chain :and_because do |reason| (@reasons ||= []) << reason end match_when_negated do |actual| - expect(actual).to(defined?(ActiveModel) ? be_empty : be_nil) + expect(actual).to(be_empty) end end diff --git a/spec/validates_email_format_of_spec.rb b/spec/validates_email_format_of_spec.rb index 7e4220e..e5fa6bb 100644 --- a/spec/validates_email_format_of_spec.rb +++ b/spec/validates_email_format_of_spec.rb @@ -1,338 +1,326 @@ require "#{__dir__}/spec_helper" require "validates_email_format_of" RSpec.configure do |config| config.before(:suite) do ValidatesEmailFormatOf.load_i18n_locales I18n.enforce_available_locales = false end end describe ValidatesEmailFormatOf do subject do |example| - if defined?(ActiveModel) - user = Class.new do - def initialize(email) - @email = email.freeze - end - attr_reader :email - include ActiveModel::Validations - validates_email_format_of :email, example.example_group_instance.options + user = Class.new do + def initialize(email) + @email = email.freeze + end + attr_reader :email + include ActiveModel::Validations + validates_email_format_of :email, example.example_group_instance.options - def self.model_name - ActiveModel::Name.new(self, nil, "User") - end + def self.model_name + ActiveModel::Name.new(self, nil, "User") end - user.new(example.example_group_instance.email).tap(&:valid?).errors.full_messages - else - ValidatesEmailFormatOf.validate_email_format(email.freeze, options) end + user.new(example.example_group_instance.email).tap(&:valid?).errors.full_messages end let(:options) { {} } let(:email) { |example| example.example_group.description } shared_examples_for :all_specs do [ "valid@example.com", "Valid@test.example.com", "valid+valid123@test.example.com", "valid_valid123@test.example.com", "valid-valid+123@test.example.co.uk", "valid-valid+1.23@test.example.com.au", "valid@example.co.uk", "v@example.com", "valid@example.ca", "valid_@example.com", "valid123.456@example.org", "valid123.456@example.travel", "valid123.456@example.museum", "valid@example.mobi", "valid@example.info", "valid-@example.com", "fake@p-t.k12.ok.us", # allow single character domain parts "valid@mail.x.example.com", "valid@x.com", "valid@example.w-dash.sch.uk", # from RFC 3696, page 6 "customer/department=shipping@example.com", "$A12345@example.com", "!def!xyz%abc@example.com", "_somename@example.com", # apostrophes "test'test@example.com", # international domain names "test@xn--bcher-kva.ch", "test@example.xn--0zwm56d", "test@192.192.192.1", # Allow quoted characters. Valid according to http://www.rfc-editor.org/errata_search.php?rfc=3696 '"Abc\@def"@example.com', '"Quote(Only".Chars@wier.de', '"Fred\ Bloggs"@example.com', '"Joe.\\Blow"@example.com', # Balanced quoted characters %("example\\\\\\""@example.com), %("example\\\\"@example.com), "(leading comment)email@example.com", "(nested (comment))email@example.com", "email(trailing comment)@example.com" ].each do |address| describe address do it { should_not have_errors_on_email } end end [ "no_at_symbol", "invalid@example-com", # period can not start local part ".invalid@example.com", # period can not end local part "invalid.@example.com", # period can not appear twice consecutively in local part "invali..d@example.com", # should not allow underscores in domain names "invalid@ex_mple.com", "invalid@e..example.com", "invalid@p-t..example.com", "invalid@example.com.", "invalid@example.com_", "invalid@example.com-", "invalid-example.com", "invalid@example.b#r.com", "invalid@example.c", "invali d@example.com", # TLD can not be only numeric "invalid@example.123", # unclosed quote "\"a-17180061943-10618354-1993365053@example.com", # too many special chars used to cause the regexp to hang "-+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++@foo", "invalidexample.com", # should not allow special chars after a period in the domain "local@sub.)domain.com", "local@sub.#domain.com", # one at a time "foo@example.com\nexample@gmail.com", "invalid@example.", "\"foo\\\\\"\"@bar.com", "foo@mail.com\r\nfoo@mail.com", "@example.com", "foo@", "foo", "Iñtërnâtiônàlizætiøn@hasnt.happened.to.email", # Escaped characters with quotes. From http://tools.ietf.org/html/rfc3696, page 5. Corrected in http://www.rfc-editor.org/errata_search.php?rfc=3696 'Fred\ Bloggs_@example.com', 'Abc\@def+@example.com', 'Joe.\\Blow@example.com', # Unbalanced quoted characters %("example\\\\""example.com), "\nnewline@example.com", " spacesbefore@example.com", "spacesafter@example.com ", "(unbalancedcomment@example.com" ].each do |address| describe address do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe do shared_examples_for :local_length_limit do |limit| describe "#{"a" * limit}@example.com" do it { should_not have_errors_on_email } end describe "#{"a" * (limit + 1)}@example.com" do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "when using default" do it_should_behave_like :local_length_limit, 64 end describe "when overriding defaults" do let(:options) { {local_length: 20} } it_should_behave_like :local_length_limit, 20 end end describe do shared_examples_for :domain_length_limit do |limit| describe "user@#{"a." * (limit / 2 - 3)}com" do it { should_not have_errors_on_email } end describe "user@#{"a." * (limit / 2 + 1)}com" do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "when using default" do it_should_behave_like :domain_length_limit, 255 end describe "when overriding defaults" do let(:options) { {domain_length: 100} } it_should_behave_like :domain_length_limit, 100 end end describe "custom error messages" do describe "invalid@example." do let(:options) { {message: "just because I don't like you"} } - it { should have_errors_on_email.because("just because I don't like you") } + it { + should have_errors_on_email.because("just because I don't like you") + } end end describe "mx record" do domain = "example.com" email = "valid@#{domain}" describe "when testing" do let(:dns) { double(Resolv::DNS) } let(:mx_record) { [double] } let(:a_record) { [double] } before(:each) do allow(Resolv::DNS).to receive(:open).and_yield(dns) - expect(dns).to receive(:"timeouts=").with(3).once + allow(dns).to receive(:"timeouts=").with(3).once allow(dns).to receive(:getresources).with(domain, Resolv::DNS::Resource::IN::MX).once.and_return(mx_record) allow(dns).to receive(:getresources).with(domain, Resolv::DNS::Resource::IN::A).once.and_return(a_record) end - let(:options) { {check_mx: true} } + let(:options) { {check_mx: true, check_mx_timeout: 3} } describe "and only an mx record is found" do let(:a_record) { [] } describe email do it { should_not have_errors_on_email } end end describe "and only an a record is found" do let(:mx_record) { [] } describe email do it { should_not have_errors_on_email } end end describe "and both an mx record and an a record are found" do describe email do it { should_not have_errors_on_email } end end describe "and neither an mx record nor an a record is found" do let(:a_record) { [] } let(:mx_record) { [] } describe email do it { should have_errors_on_email.because("is not routable") } end describe "with a custom error message" do let(:options) { {check_mx: true, mx_message: "There ain't no such domain!"} } describe email do it { should have_errors_on_email.because("There ain't no such domain!") } end end describe "i18n" do before(:each) do allow(I18n.config).to receive(:locale).and_return(locale) end describe "present locale" do let(:locale) { :pl } describe email do it { should have_errors_on_email.because("jest nieosiągalny") } end end - unless defined?(ActiveModel) - describe email do - let(:locale) { :ir } - describe email do - it { should have_errors_on_email.because("is not routable") } - end - end - end - end - unless defined?(ActiveModel) - describe "without i18n" do - before(:each) { hide_const("I18n") } - describe email do - it { should have_errors_on_email.because("is not routable") } - end - end end end end describe "when not testing" do before(:each) { allow(Resolv::DNS).to receive(:open).never } describe "by default" do describe email do it { should_not have_errors_on_email } end end describe "explicitly" do describe email do let(:options) { {check_mx: false} } it { should_not have_errors_on_email } end end end describe "without mocks" do describe email do let(:options) { {check_mx: true} } it { should_not have_errors_on_email } end end end describe "custom regex" do let(:options) { {with: /[0-9]+@[0-9]+/} } describe "012345@789" do it { should_not have_errors_on_email } end describe "valid@example.com" do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "i18n" do before(:each) do allow(I18n.config).to receive(:locale).and_return(locale) end describe "present locale" do let(:locale) { :pl } describe "invalid@exmaple." do it { should have_errors_on_email.because("nieprawidłowy adres e-mail") } end end - unless defined?(ActiveModel) - describe "missing locale" do - let(:locale) { :ir } - describe "invalid@exmaple." do - it { should have_errors_on_email.because("does not appear to be valid") } - end - end + end + end + it_should_behave_like :all_specs + + describe "validation without ActiveModel" do + subject do + ValidatesEmailFormatOf.validate_email_format(email.freeze, options) + end + + describe "valid@example.com" do + it { should be_nil } + end + + describe "custom error messages" do + describe "invalid@example." do + let(:options) { {message: "just because I don't like you"} } + it { should match_array(["just because I don't like you"]) } end end - unless defined?(ActiveModel) - describe "without i18n" do - before(:each) { hide_const("I18n") } - describe "invalid@exmaple." do - it { should have_errors_on_email.because("does not appear to be valid") } - end + + describe "without i18n" do + before(:each) { hide_const("I18n") } + describe "invalid@exmaple." do + it { should match_array(["does not appear to be valid"]) } end end end - it_should_behave_like :all_specs - if defined?(ActiveModel) - describe "shorthand ActiveModel validation" do - subject do |example| - user = Class.new do - def initialize(email) - @email = email.freeze - end - attr_reader :email - include ActiveModel::Validations - validates :email, email_format: example.example_group_instance.options + describe "shorthand ActiveModel validation" do + subject do |example| + user = Class.new do + def initialize(email) + @email = email.freeze + end + attr_reader :email + include ActiveModel::Validations + validates :email, email_format: example.example_group_instance.options - def self.model_name - ActiveModel::Name.new(self, nil, "User") - end + def self.model_name + ActiveModel::Name.new(self, nil, "User") end - user.new(example.example_group_instance.email).tap(&:valid?).errors.full_messages end - - it_should_behave_like :all_specs + user.new(example.example_group_instance.email).tap(&:valid?).errors.full_messages end + + it_should_behave_like :all_specs end end diff --git a/validates_email_format_of.gemspec b/validates_email_format_of.gemspec index 33f4855..bb7c031 100644 --- a/validates_email_format_of.gemspec +++ b/validates_email_format_of.gemspec @@ -1,27 +1,28 @@ $:.unshift File.expand_path("../lib", __FILE__) require "validates_email_format_of/version" Gem::Specification.new do |s| s.name = "validates_email_format_of" s.version = ValidatesEmailFormatOf::VERSION s.summary = "Validate e-mail addresses against RFC 2822 and RFC 3696." s.description = s.summary s.authors = ["Alex Dunae", "Isaac Betesh"] s.email = ["code@dunae.ca", "iybetesh@gmail.com"] s.homepage = "https://github.com/validates-email-format-of/validates_email_format_of" s.license = "MIT" s.files = `git ls-files`.split($/) s.require_paths = ["lib"] if RUBY_VERSION < "1.9.3" s.add_dependency "i18n", "< 0.7.0" else s.add_dependency "i18n" end + s.add_development_dependency "activemodel" s.add_development_dependency "bundler" s.add_development_dependency "rspec" s.add_development_dependency "standard" s.add_development_dependency "appraisal" s.add_development_dependency "pry-byebug" end
validates-email-format-of/validates_email_format_of
85752fb63ae964af19c5fdd3adef9206335aa295
Use && and || for boolean logic
diff --git a/lib/validates_email_format_of.rb b/lib/validates_email_format_of.rb index e672203..6b067a1 100644 --- a/lib/validates_email_format_of.rb +++ b/lib/validates_email_format_of.rb @@ -1,253 +1,253 @@ require "validates_email_format_of/version" module ValidatesEmailFormatOf def self.load_i18n_locales require "i18n" I18n.load_path += Dir.glob(File.expand_path(File.join(File.dirname(__FILE__), "..", "config", "locales", "*.yml"))) end require "resolv" ATEXT_SYMBOLS = /[!\#$%&'*\-\/=?+\^_`{|}~]/ # Characters that are allowed in to appear in the local part unquoted # https://www.rfc-editor.org/rfc/rfc5322#section-3.4.1 # # An addr-spec is a specific Internet identifier that contains a # locally interpreted string followed by the at-sign character ("@", # ASCII value 64) followed by an Internet domain. The locally # interpreted string is either a quoted-string or a dot-atom. If the # string can be represented as a dot-atom (that is, it contains no # characters other than atext characters or "." surrounded by atext # characters), then the dot-atom form SHOULD be used and the quoted- # string form SHOULD NOT be used. Comments and folding white space # SHOULD NOT be used around the "@" in the addr-spec. # # dot-atom-text = 1*atext *("." 1*atext) # dot-atom = [CFWS] dot-atom-text [CFWS] ATEXT = /\A[A-Z0-9#{ATEXT_SYMBOLS}]\z/i # Characters that are allowed to appear unquoted in comments # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.2 # # ctext = %d33-39 / %d42-91 / %d93-126 # ccontent = ctext / quoted-pair / comment # comment = "(" *([FWS] ccontent) [FWS] ")" # CFWS = (1*([FWS] comment) [FWS]) / FWS CTEXT = /\A[#{Regexp.escape([33..39, 42..91, 93..126].map { |ascii_range| ascii_range.map(&:chr) }.flatten.join)}\s]/i # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.4 # # Strings of characters that include characters other than those # allowed in atoms can be represented in a quoted string format, where # the characters are surrounded by quote (DQUOTE, ASCII value 34) # characters. # # qtext = %d33 / ; Printable US-ASCII # %d35-91 / ; characters not including # %d93-126 / ; "\" or the quote character # obs-qtext # # qcontent = qtext / quoted-pair # quoted-string = [CFWS] # DQUOTE *([FWS] qcontent) [FWS] DQUOTE # [CFWS] QTEXT = /\A[#{Regexp.escape([33..33, 35..91, 93..126].map { |ascii_range| ascii_range.map(&:chr) }.flatten.join)}\s]/i IP_OCTET = /\A[0-9]+\Z/ # From https://datatracker.ietf.org/doc/html/rfc1035#section-2.3.1 # # > The labels must follow the rules for ARPANET host names. They must # > start with a letter, end with a letter or digit, and have as interior # > characters only letters, digits, and hyphen. There are also some # > restrictions on the length. Labels must be 63 characters or less. # # <label> | <subdomain> "." <label> # <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ] # <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str> # <let-dig-hyp> ::= <let-dig> | "-" # <let-dig> ::= <letter> | <digit> DOMAIN_PART_LABEL = /\A[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9]?\Z/ # From https://tools.ietf.org/id/draft-liman-tld-names-00.html#rfc.section.2 # # > A TLD label MUST be at least two characters long and MAY be as long as 63 characters - # > not counting any leading or trailing periods (.). It MUST consist of only ASCII characters # > from the groups "letters" (A-Z), "digits" (0-9) and "hyphen" (-), and it MUST start with an # > ASCII "letter", and it MUST NOT end with a "hyphen". Upper and lower case MAY be mixed at random, # > since DNS lookups are case-insensitive. # # tldlabel = ALPHA *61(ldh) ld # ldh = ld / "-" # ld = ALPHA / DIGIT # ALPHA = %x41-5A / %x61-7A ; A-Z / a-z # DIGIT = %x30-39 ; 0-9 DOMAIN_PART_TLD = /\A[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9]\Z/ def self.validate_email_domain(email, check_mx_timeout: 3) domain = email.to_s.downcase.match(/@(.+)/)[1] Resolv::DNS.open do |dns| dns.timeouts = check_mx_timeout @mx = dns.getresources(domain, Resolv::DNS::Resource::IN::MX) + dns.getresources(domain, Resolv::DNS::Resource::IN::A) end @mx.size > 0 end DEFAULT_MESSAGE = "does not appear to be valid" DEFAULT_MX_MESSAGE = "is not routable" ERROR_MESSAGE_I18N_KEY = :invalid_email_address ERROR_MX_MESSAGE_I18N_KEY = :email_address_not_routable def self.default_message defined?(I18n) ? I18n.t(ERROR_MESSAGE_I18N_KEY, scope: [:activemodel, :errors, :messages], default: DEFAULT_MESSAGE) : DEFAULT_MESSAGE end # Validates whether the specified value is a valid email address. Returns nil if the value is valid, otherwise returns an array # containing one or more validation error messages. # # Configuration options: # * <tt>message</tt> - A custom error message (default is: "does not appear to be valid") # * <tt>check_mx</tt> - Check for MX records (default is false) # * <tt>check_mx_timeout</tt> - Timeout in seconds for checking MX records before a `ResolvTimeout` is raised (default is 3) # * <tt>mx_message</tt> - A custom error message when an MX record validation fails (default is: "is not routable.") # * <tt>with</tt> The regex to use for validating the format of the email address (deprecated) # * <tt>local_length</tt> Maximum number of characters allowed in the local part (default is 64) # * <tt>domain_length</tt> Maximum number of characters allowed in the domain part (default is 255) # * <tt>generate_message</tt> Return the I18n key of the error message instead of the error message itself (default is false) def self.validate_email_format(email, options = {}) default_options = {message: options[:generate_message] ? ERROR_MESSAGE_I18N_KEY : default_message, check_mx: false, check_mx_timeout: 3, mx_message: if options[:generate_message] ERROR_MX_MESSAGE_I18N_KEY else (defined?(I18n) ? I18n.t(ERROR_MX_MESSAGE_I18N_KEY, scope: [:activemodel, :errors, :messages], default: DEFAULT_MX_MESSAGE) : DEFAULT_MX_MESSAGE) end, domain_length: 255, local_length: 64, generate_message: false} opts = options.merge(default_options) { |key, old, new| old } # merge the default options into the specified options, retaining all specified options begin domain, local = email.reverse.split("@", 2) rescue return [opts[:message]] end # need local and domain parts - return [opts[:message]] unless local and !local.empty? and domain and !domain.empty? + return [opts[:message]] unless local && !local.empty? && domain && !domain.empty? # check lengths - return [opts[:message]] unless domain.length <= opts[:domain_length] and local.length <= opts[:local_length] + return [opts[:message]] unless domain.length <= opts[:domain_length] && local.length <= opts[:local_length] local.reverse! domain.reverse! if opts.has_key?(:with) # holdover from versions <= 1.4.7 return [opts[:message]] unless email&.match?(opts[:with]) else - return [opts[:message]] unless validate_local_part_syntax(local) and validate_domain_part_syntax(domain) + return [opts[:message]] unless validate_local_part_syntax(local) && validate_domain_part_syntax(domain) end - if opts[:check_mx] and !validate_email_domain(email, check_mx_timeout: opts[:check_mx_timeout]) + if opts[:check_mx] && !validate_email_domain(email, check_mx_timeout: opts[:check_mx_timeout]) return [opts[:mx_message]] end nil # represents no validation errors end def self.validate_local_part_syntax(local) in_quoted_pair = false in_quoted_string = false comment_depth = 0 (0..local.length - 1).each do |i| ord = local[i].ord # accept anything if it's got a backslash before it if in_quoted_pair in_quoted_pair = false next end if in_quoted_string next if QTEXT.match?(local[i]) end # opening paren to show we are going into a comment (CFWS) if ord == 40 comment_depth += 1 next end # closing paren if ord == 41 comment_depth -= 1 return false if comment_depth < 0 next end # backslash signifies the start of a quoted pair - if ord == 92 and i < local.length - 1 + if ord == 92 && i < local.length - 1 return false if !in_quoted_string # must be in quoted string per http://www.rfc-editor.org/errata_search.php?rfc=3696 in_quoted_pair = true next end # double quote delimits quoted strings if ord == 34 in_quoted_string = !in_quoted_string next end if comment_depth > 0 next if CTEXT.match?(local[i]) elsif ATEXT.match?(local[i, 1]) next end # period must be followed by something if ord == 46 - return false if i == 0 or i == local.length - 1 # can't be first or last char + return false if i == 0 || i == local.length - 1 # can't be first or last char next unless local[i + 1].ord == 46 # can't be followed by a period end return false end return false if in_quoted_string # unbalanced quotes return false unless comment_depth.zero? # unbalanced comment parens true end def self.validate_domain_part_syntax(domain) parts = domain.downcase.split(".", -1) return false if parts.length <= 1 # Only one domain part # ipv4 return true if parts.length == 4 && parts.all? { |part| part =~ IP_OCTET && part.to_i.between?(0, 255) } # From https://datatracker.ietf.org/doc/html/rfc3696#section-2 this is the recommended, pragmatic way to validate a domain name: # # > It is likely that the better strategy has now become to make the "at least one period" test, # > to verify LDH conformance (including verification that the apparent TLD name is not all-numeric), # > and then to use the DNS to determine domain name validity, rather than trying to maintain # > a local list of valid TLD names. # # We do a little bit more but not too much and validate the tokens but do not check against a list of valid TLDs. parts.each do |part| return false if part.nil? || part.empty? return false if part.length > 63 return false unless DOMAIN_PART_LABEL.match?(part) end return false unless DOMAIN_PART_TLD.match?(parts[-1]) true end end require "validates_email_format_of/active_model" if defined?(::ActiveModel) && !(ActiveModel::VERSION::MAJOR < 2 || (ActiveModel::VERSION::MAJOR == 2 && ActiveModel::VERSION::MINOR < 1)) require "validates_email_format_of/railtie" if defined?(::Rails::Railtie)
validates-email-format-of/validates_email_format_of
89191552d4a6fb5dc5d7a988a54e942ca6cc5ff3
Simplify key lookup
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 2bf92ef..795d852 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,24 +1,24 @@ -require "active_model" if Gem.loaded_specs.keys.include?("activemodel") +require "active_model" if Gem.loaded_specs.key?("activemodel") require "pry" require "byebug" RSpec::Matchers.define :have_errors_on_email do match do |actual| expect(actual).not_to be_nil, "#{actual} should not be nil" expect(actual).not_to be_empty, "#{actual} should not be empty" expect(actual.size).to eq(@reasons.size), "#{actual} should have #{@reasons.size} elements" @reasons.each do |reason| reason = "#{"Email " if defined?(ActiveModel)}#{reason}" expect(actual).to include(reason), "#{actual} should contain #{reason}" end end chain :because do |reason| (@reasons ||= []) << reason end chain :and_because do |reason| (@reasons ||= []) << reason end match_when_negated do |actual| expect(actual).to(defined?(ActiveModel) ? be_empty : be_nil) end end
validates-email-format-of/validates_email_format_of
1ba27695f0260e6e9a130017ec22f9fea35dcf26
Swap comparison order for standard.rb
diff --git a/lib/validates_email_format_of.rb b/lib/validates_email_format_of.rb index cee6606..e672203 100644 --- a/lib/validates_email_format_of.rb +++ b/lib/validates_email_format_of.rb @@ -1,253 +1,253 @@ require "validates_email_format_of/version" module ValidatesEmailFormatOf def self.load_i18n_locales require "i18n" I18n.load_path += Dir.glob(File.expand_path(File.join(File.dirname(__FILE__), "..", "config", "locales", "*.yml"))) end require "resolv" ATEXT_SYMBOLS = /[!\#$%&'*\-\/=?+\^_`{|}~]/ # Characters that are allowed in to appear in the local part unquoted # https://www.rfc-editor.org/rfc/rfc5322#section-3.4.1 # # An addr-spec is a specific Internet identifier that contains a # locally interpreted string followed by the at-sign character ("@", # ASCII value 64) followed by an Internet domain. The locally # interpreted string is either a quoted-string or a dot-atom. If the # string can be represented as a dot-atom (that is, it contains no # characters other than atext characters or "." surrounded by atext # characters), then the dot-atom form SHOULD be used and the quoted- # string form SHOULD NOT be used. Comments and folding white space # SHOULD NOT be used around the "@" in the addr-spec. # # dot-atom-text = 1*atext *("." 1*atext) # dot-atom = [CFWS] dot-atom-text [CFWS] ATEXT = /\A[A-Z0-9#{ATEXT_SYMBOLS}]\z/i # Characters that are allowed to appear unquoted in comments # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.2 # # ctext = %d33-39 / %d42-91 / %d93-126 # ccontent = ctext / quoted-pair / comment # comment = "(" *([FWS] ccontent) [FWS] ")" # CFWS = (1*([FWS] comment) [FWS]) / FWS CTEXT = /\A[#{Regexp.escape([33..39, 42..91, 93..126].map { |ascii_range| ascii_range.map(&:chr) }.flatten.join)}\s]/i # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.4 # # Strings of characters that include characters other than those # allowed in atoms can be represented in a quoted string format, where # the characters are surrounded by quote (DQUOTE, ASCII value 34) # characters. # # qtext = %d33 / ; Printable US-ASCII # %d35-91 / ; characters not including # %d93-126 / ; "\" or the quote character # obs-qtext # # qcontent = qtext / quoted-pair # quoted-string = [CFWS] # DQUOTE *([FWS] qcontent) [FWS] DQUOTE # [CFWS] QTEXT = /\A[#{Regexp.escape([33..33, 35..91, 93..126].map { |ascii_range| ascii_range.map(&:chr) }.flatten.join)}\s]/i IP_OCTET = /\A[0-9]+\Z/ # From https://datatracker.ietf.org/doc/html/rfc1035#section-2.3.1 # # > The labels must follow the rules for ARPANET host names. They must # > start with a letter, end with a letter or digit, and have as interior # > characters only letters, digits, and hyphen. There are also some # > restrictions on the length. Labels must be 63 characters or less. # # <label> | <subdomain> "." <label> # <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ] # <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str> # <let-dig-hyp> ::= <let-dig> | "-" # <let-dig> ::= <letter> | <digit> DOMAIN_PART_LABEL = /\A[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9]?\Z/ # From https://tools.ietf.org/id/draft-liman-tld-names-00.html#rfc.section.2 # # > A TLD label MUST be at least two characters long and MAY be as long as 63 characters - # > not counting any leading or trailing periods (.). It MUST consist of only ASCII characters # > from the groups "letters" (A-Z), "digits" (0-9) and "hyphen" (-), and it MUST start with an # > ASCII "letter", and it MUST NOT end with a "hyphen". Upper and lower case MAY be mixed at random, # > since DNS lookups are case-insensitive. # # tldlabel = ALPHA *61(ldh) ld # ldh = ld / "-" # ld = ALPHA / DIGIT # ALPHA = %x41-5A / %x61-7A ; A-Z / a-z # DIGIT = %x30-39 ; 0-9 DOMAIN_PART_TLD = /\A[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9]\Z/ def self.validate_email_domain(email, check_mx_timeout: 3) domain = email.to_s.downcase.match(/@(.+)/)[1] Resolv::DNS.open do |dns| dns.timeouts = check_mx_timeout @mx = dns.getresources(domain, Resolv::DNS::Resource::IN::MX) + dns.getresources(domain, Resolv::DNS::Resource::IN::A) end @mx.size > 0 end DEFAULT_MESSAGE = "does not appear to be valid" DEFAULT_MX_MESSAGE = "is not routable" ERROR_MESSAGE_I18N_KEY = :invalid_email_address ERROR_MX_MESSAGE_I18N_KEY = :email_address_not_routable def self.default_message defined?(I18n) ? I18n.t(ERROR_MESSAGE_I18N_KEY, scope: [:activemodel, :errors, :messages], default: DEFAULT_MESSAGE) : DEFAULT_MESSAGE end # Validates whether the specified value is a valid email address. Returns nil if the value is valid, otherwise returns an array # containing one or more validation error messages. # # Configuration options: # * <tt>message</tt> - A custom error message (default is: "does not appear to be valid") # * <tt>check_mx</tt> - Check for MX records (default is false) # * <tt>check_mx_timeout</tt> - Timeout in seconds for checking MX records before a `ResolvTimeout` is raised (default is 3) # * <tt>mx_message</tt> - A custom error message when an MX record validation fails (default is: "is not routable.") # * <tt>with</tt> The regex to use for validating the format of the email address (deprecated) # * <tt>local_length</tt> Maximum number of characters allowed in the local part (default is 64) # * <tt>domain_length</tt> Maximum number of characters allowed in the domain part (default is 255) # * <tt>generate_message</tt> Return the I18n key of the error message instead of the error message itself (default is false) def self.validate_email_format(email, options = {}) default_options = {message: options[:generate_message] ? ERROR_MESSAGE_I18N_KEY : default_message, check_mx: false, check_mx_timeout: 3, mx_message: if options[:generate_message] ERROR_MX_MESSAGE_I18N_KEY else (defined?(I18n) ? I18n.t(ERROR_MX_MESSAGE_I18N_KEY, scope: [:activemodel, :errors, :messages], default: DEFAULT_MX_MESSAGE) : DEFAULT_MX_MESSAGE) end, domain_length: 255, local_length: 64, generate_message: false} opts = options.merge(default_options) { |key, old, new| old } # merge the default options into the specified options, retaining all specified options begin domain, local = email.reverse.split("@", 2) rescue return [opts[:message]] end # need local and domain parts return [opts[:message]] unless local and !local.empty? and domain and !domain.empty? # check lengths return [opts[:message]] unless domain.length <= opts[:domain_length] and local.length <= opts[:local_length] local.reverse! domain.reverse! if opts.has_key?(:with) # holdover from versions <= 1.4.7 return [opts[:message]] unless email&.match?(opts[:with]) else return [opts[:message]] unless validate_local_part_syntax(local) and validate_domain_part_syntax(domain) end if opts[:check_mx] and !validate_email_domain(email, check_mx_timeout: opts[:check_mx_timeout]) return [opts[:mx_message]] end nil # represents no validation errors end def self.validate_local_part_syntax(local) in_quoted_pair = false in_quoted_string = false comment_depth = 0 (0..local.length - 1).each do |i| ord = local[i].ord # accept anything if it's got a backslash before it if in_quoted_pair in_quoted_pair = false next end if in_quoted_string next if QTEXT.match?(local[i]) end # opening paren to show we are going into a comment (CFWS) if ord == 40 comment_depth += 1 next end # closing paren if ord == 41 comment_depth -= 1 return false if comment_depth < 0 next end # backslash signifies the start of a quoted pair if ord == 92 and i < local.length - 1 return false if !in_quoted_string # must be in quoted string per http://www.rfc-editor.org/errata_search.php?rfc=3696 in_quoted_pair = true next end # double quote delimits quoted strings if ord == 34 in_quoted_string = !in_quoted_string next end if comment_depth > 0 next if CTEXT.match?(local[i]) elsif ATEXT.match?(local[i, 1]) next end # period must be followed by something if ord == 46 return false if i == 0 or i == local.length - 1 # can't be first or last char next unless local[i + 1].ord == 46 # can't be followed by a period end return false end return false if in_quoted_string # unbalanced quotes return false unless comment_depth.zero? # unbalanced comment parens true end def self.validate_domain_part_syntax(domain) parts = domain.downcase.split(".", -1) return false if parts.length <= 1 # Only one domain part # ipv4 return true if parts.length == 4 && parts.all? { |part| part =~ IP_OCTET && part.to_i.between?(0, 255) } # From https://datatracker.ietf.org/doc/html/rfc3696#section-2 this is the recommended, pragmatic way to validate a domain name: # # > It is likely that the better strategy has now become to make the "at least one period" test, # > to verify LDH conformance (including verification that the apparent TLD name is not all-numeric), # > and then to use the DNS to determine domain name validity, rather than trying to maintain # > a local list of valid TLD names. # # We do a little bit more but not too much and validate the tokens but do not check against a list of valid TLDs. parts.each do |part| return false if part.nil? || part.empty? return false if part.length > 63 return false unless DOMAIN_PART_LABEL.match?(part) end return false unless DOMAIN_PART_TLD.match?(parts[-1]) true end end -require "validates_email_format_of/active_model" if defined?(::ActiveModel) && !(ActiveModel::VERSION::MAJOR < 2 || (2 == ActiveModel::VERSION::MAJOR && ActiveModel::VERSION::MINOR < 1)) +require "validates_email_format_of/active_model" if defined?(::ActiveModel) && !(ActiveModel::VERSION::MAJOR < 2 || (ActiveModel::VERSION::MAJOR == 2 && ActiveModel::VERSION::MINOR < 1)) require "validates_email_format_of/railtie" if defined?(::Rails::Railtie) diff --git a/lib/validates_email_format_of/active_model.rb b/lib/validates_email_format_of/active_model.rb index 1cedf9c..fcb289c 100644 --- a/lib/validates_email_format_of/active_model.rb +++ b/lib/validates_email_format_of/active_model.rb @@ -1,24 +1,24 @@ require "validates_email_format_of" require "active_model" -if ActiveModel::VERSION::MAJOR < 2 || (2 == ActiveModel::VERSION::MAJOR && ActiveModel::VERSION::MINOR < 1) +if ActiveModel::VERSION::MAJOR < 2 || (ActiveModel::VERSION::MAJOR == 2 && ActiveModel::VERSION::MINOR < 1) puts "WARNING: ActiveModel validation helper methods in validates_email_format_of gem are not compatible with ActiveModel < 2.1.0. Please use ValidatesEmailFormatOf::validate_email_format(email, options) or upgrade ActiveModel" end module ActiveModel module Validations class EmailFormatValidator < EachValidator def validate_each(record, attribute, value) (ValidatesEmailFormatOf.validate_email_format(value, options.merge(generate_message: true)) || []).each do |error| record.errors.add(attribute, error) end end end module HelperMethods def validates_email_format_of(*attr_names) validates_with EmailFormatValidator, _merge_attributes(attr_names) end end end end
validates-email-format-of/validates_email_format_of
bfb41134b7e44a43874ee5a16189dd64ca3c4848
Remove unused variable assignments
diff --git a/spec/validates_email_format_of_spec.rb b/spec/validates_email_format_of_spec.rb index 98e0fb6..7e4220e 100644 --- a/spec/validates_email_format_of_spec.rb +++ b/spec/validates_email_format_of_spec.rb @@ -1,338 +1,338 @@ require "#{__dir__}/spec_helper" require "validates_email_format_of" RSpec.configure do |config| config.before(:suite) do ValidatesEmailFormatOf.load_i18n_locales I18n.enforce_available_locales = false end end describe ValidatesEmailFormatOf do subject do |example| if defined?(ActiveModel) user = Class.new do def initialize(email) @email = email.freeze end attr_reader :email include ActiveModel::Validations validates_email_format_of :email, example.example_group_instance.options def self.model_name ActiveModel::Name.new(self, nil, "User") end end user.new(example.example_group_instance.email).tap(&:valid?).errors.full_messages else ValidatesEmailFormatOf.validate_email_format(email.freeze, options) end end let(:options) { {} } let(:email) { |example| example.example_group.description } shared_examples_for :all_specs do [ "valid@example.com", "Valid@test.example.com", "valid+valid123@test.example.com", "valid_valid123@test.example.com", "valid-valid+123@test.example.co.uk", "valid-valid+1.23@test.example.com.au", "valid@example.co.uk", "v@example.com", "valid@example.ca", "valid_@example.com", "valid123.456@example.org", "valid123.456@example.travel", "valid123.456@example.museum", "valid@example.mobi", "valid@example.info", "valid-@example.com", "fake@p-t.k12.ok.us", # allow single character domain parts "valid@mail.x.example.com", "valid@x.com", "valid@example.w-dash.sch.uk", # from RFC 3696, page 6 "customer/department=shipping@example.com", "$A12345@example.com", "!def!xyz%abc@example.com", "_somename@example.com", # apostrophes "test'test@example.com", # international domain names "test@xn--bcher-kva.ch", "test@example.xn--0zwm56d", "test@192.192.192.1", # Allow quoted characters. Valid according to http://www.rfc-editor.org/errata_search.php?rfc=3696 '"Abc\@def"@example.com', '"Quote(Only".Chars@wier.de', '"Fred\ Bloggs"@example.com', '"Joe.\\Blow"@example.com', # Balanced quoted characters %("example\\\\\\""@example.com), %("example\\\\"@example.com), "(leading comment)email@example.com", "(nested (comment))email@example.com", "email(trailing comment)@example.com" ].each do |address| describe address do it { should_not have_errors_on_email } end end [ "no_at_symbol", "invalid@example-com", # period can not start local part ".invalid@example.com", # period can not end local part "invalid.@example.com", # period can not appear twice consecutively in local part "invali..d@example.com", # should not allow underscores in domain names "invalid@ex_mple.com", "invalid@e..example.com", "invalid@p-t..example.com", "invalid@example.com.", "invalid@example.com_", "invalid@example.com-", "invalid-example.com", "invalid@example.b#r.com", "invalid@example.c", "invali d@example.com", # TLD can not be only numeric "invalid@example.123", # unclosed quote "\"a-17180061943-10618354-1993365053@example.com", # too many special chars used to cause the regexp to hang "-+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++@foo", "invalidexample.com", # should not allow special chars after a period in the domain "local@sub.)domain.com", "local@sub.#domain.com", # one at a time "foo@example.com\nexample@gmail.com", "invalid@example.", "\"foo\\\\\"\"@bar.com", "foo@mail.com\r\nfoo@mail.com", "@example.com", "foo@", "foo", "Iñtërnâtiônàlizætiøn@hasnt.happened.to.email", # Escaped characters with quotes. From http://tools.ietf.org/html/rfc3696, page 5. Corrected in http://www.rfc-editor.org/errata_search.php?rfc=3696 'Fred\ Bloggs_@example.com', 'Abc\@def+@example.com', 'Joe.\\Blow@example.com', # Unbalanced quoted characters %("example\\\\""example.com), "\nnewline@example.com", " spacesbefore@example.com", "spacesafter@example.com ", "(unbalancedcomment@example.com" ].each do |address| describe address do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe do shared_examples_for :local_length_limit do |limit| describe "#{"a" * limit}@example.com" do it { should_not have_errors_on_email } end describe "#{"a" * (limit + 1)}@example.com" do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "when using default" do it_should_behave_like :local_length_limit, 64 end describe "when overriding defaults" do let(:options) { {local_length: 20} } it_should_behave_like :local_length_limit, 20 end end describe do shared_examples_for :domain_length_limit do |limit| describe "user@#{"a." * (limit / 2 - 3)}com" do it { should_not have_errors_on_email } end describe "user@#{"a." * (limit / 2 + 1)}com" do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "when using default" do it_should_behave_like :domain_length_limit, 255 end describe "when overriding defaults" do let(:options) { {domain_length: 100} } it_should_behave_like :domain_length_limit, 100 end end describe "custom error messages" do describe "invalid@example." do let(:options) { {message: "just because I don't like you"} } it { should have_errors_on_email.because("just because I don't like you") } end end describe "mx record" do domain = "example.com" email = "valid@#{domain}" - check_mx_timeout = 3 + describe "when testing" do let(:dns) { double(Resolv::DNS) } let(:mx_record) { [double] } let(:a_record) { [double] } before(:each) do allow(Resolv::DNS).to receive(:open).and_yield(dns) expect(dns).to receive(:"timeouts=").with(3).once allow(dns).to receive(:getresources).with(domain, Resolv::DNS::Resource::IN::MX).once.and_return(mx_record) allow(dns).to receive(:getresources).with(domain, Resolv::DNS::Resource::IN::A).once.and_return(a_record) end let(:options) { {check_mx: true} } describe "and only an mx record is found" do let(:a_record) { [] } describe email do it { should_not have_errors_on_email } end end describe "and only an a record is found" do let(:mx_record) { [] } describe email do it { should_not have_errors_on_email } end end describe "and both an mx record and an a record are found" do describe email do it { should_not have_errors_on_email } end end describe "and neither an mx record nor an a record is found" do let(:a_record) { [] } let(:mx_record) { [] } describe email do it { should have_errors_on_email.because("is not routable") } end describe "with a custom error message" do let(:options) { {check_mx: true, mx_message: "There ain't no such domain!"} } describe email do it { should have_errors_on_email.because("There ain't no such domain!") } end end describe "i18n" do before(:each) do allow(I18n.config).to receive(:locale).and_return(locale) end describe "present locale" do let(:locale) { :pl } describe email do it { should have_errors_on_email.because("jest nieosiągalny") } end end unless defined?(ActiveModel) describe email do let(:locale) { :ir } describe email do it { should have_errors_on_email.because("is not routable") } end end end end unless defined?(ActiveModel) describe "without i18n" do before(:each) { hide_const("I18n") } describe email do it { should have_errors_on_email.because("is not routable") } end end end end end describe "when not testing" do before(:each) { allow(Resolv::DNS).to receive(:open).never } describe "by default" do describe email do it { should_not have_errors_on_email } end end describe "explicitly" do describe email do let(:options) { {check_mx: false} } it { should_not have_errors_on_email } end end end describe "without mocks" do describe email do let(:options) { {check_mx: true} } it { should_not have_errors_on_email } end end end describe "custom regex" do let(:options) { {with: /[0-9]+@[0-9]+/} } describe "012345@789" do it { should_not have_errors_on_email } end describe "valid@example.com" do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "i18n" do before(:each) do allow(I18n.config).to receive(:locale).and_return(locale) end describe "present locale" do let(:locale) { :pl } describe "invalid@exmaple." do it { should have_errors_on_email.because("nieprawidłowy adres e-mail") } end end unless defined?(ActiveModel) describe "missing locale" do let(:locale) { :ir } describe "invalid@exmaple." do it { should have_errors_on_email.because("does not appear to be valid") } end end end end unless defined?(ActiveModel) describe "without i18n" do before(:each) { hide_const("I18n") } describe "invalid@exmaple." do it { should have_errors_on_email.because("does not appear to be valid") } end end end end it_should_behave_like :all_specs if defined?(ActiveModel) describe "shorthand ActiveModel validation" do subject do |example| user = Class.new do def initialize(email) @email = email.freeze end attr_reader :email include ActiveModel::Validations validates :email, email_format: example.example_group_instance.options def self.model_name ActiveModel::Name.new(self, nil, "User") end end user.new(example.example_group_instance.email).tap(&:valid?).errors.full_messages end it_should_behave_like :all_specs end end end diff --git a/validates_email_format_of.gemspec b/validates_email_format_of.gemspec index 1ace3af..33f4855 100644 --- a/validates_email_format_of.gemspec +++ b/validates_email_format_of.gemspec @@ -1,27 +1,27 @@ $:.unshift File.expand_path("../lib", __FILE__) require "validates_email_format_of/version" -spec = Gem::Specification.new do |s| +Gem::Specification.new do |s| s.name = "validates_email_format_of" s.version = ValidatesEmailFormatOf::VERSION s.summary = "Validate e-mail addresses against RFC 2822 and RFC 3696." s.description = s.summary s.authors = ["Alex Dunae", "Isaac Betesh"] s.email = ["code@dunae.ca", "iybetesh@gmail.com"] s.homepage = "https://github.com/validates-email-format-of/validates_email_format_of" s.license = "MIT" s.files = `git ls-files`.split($/) s.require_paths = ["lib"] if RUBY_VERSION < "1.9.3" s.add_dependency "i18n", "< 0.7.0" else s.add_dependency "i18n" end s.add_development_dependency "bundler" s.add_development_dependency "rspec" s.add_development_dependency "standard" s.add_development_dependency "appraisal" s.add_development_dependency "pry-byebug" end
validates-email-format-of/validates_email_format_of
9035c8ab03edfacf0e4c61df8d66e0cf75aeb6c0
Rename constants for standard.rb
diff --git a/lib/validates_email_format_of.rb b/lib/validates_email_format_of.rb index 925a868..cee6606 100644 --- a/lib/validates_email_format_of.rb +++ b/lib/validates_email_format_of.rb @@ -1,253 +1,253 @@ require "validates_email_format_of/version" module ValidatesEmailFormatOf def self.load_i18n_locales require "i18n" I18n.load_path += Dir.glob(File.expand_path(File.join(File.dirname(__FILE__), "..", "config", "locales", "*.yml"))) end require "resolv" - LocalPartSpecialChars = /[!\#$%&'*\-\/=?+\^_`{|}~]/ + ATEXT_SYMBOLS = /[!\#$%&'*\-\/=?+\^_`{|}~]/ # Characters that are allowed in to appear in the local part unquoted # https://www.rfc-editor.org/rfc/rfc5322#section-3.4.1 # # An addr-spec is a specific Internet identifier that contains a # locally interpreted string followed by the at-sign character ("@", # ASCII value 64) followed by an Internet domain. The locally # interpreted string is either a quoted-string or a dot-atom. If the # string can be represented as a dot-atom (that is, it contains no # characters other than atext characters or "." surrounded by atext # characters), then the dot-atom form SHOULD be used and the quoted- # string form SHOULD NOT be used. Comments and folding white space # SHOULD NOT be used around the "@" in the addr-spec. # # dot-atom-text = 1*atext *("." 1*atext) # dot-atom = [CFWS] dot-atom-text [CFWS] - ATEXT = /\A[A-Z0-9#{LocalPartSpecialChars}]\z/i + ATEXT = /\A[A-Z0-9#{ATEXT_SYMBOLS}]\z/i # Characters that are allowed to appear unquoted in comments # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.2 # # ctext = %d33-39 / %d42-91 / %d93-126 # ccontent = ctext / quoted-pair / comment # comment = "(" *([FWS] ccontent) [FWS] ")" # CFWS = (1*([FWS] comment) [FWS]) / FWS CTEXT = /\A[#{Regexp.escape([33..39, 42..91, 93..126].map { |ascii_range| ascii_range.map(&:chr) }.flatten.join)}\s]/i # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.4 # # Strings of characters that include characters other than those # allowed in atoms can be represented in a quoted string format, where # the characters are surrounded by quote (DQUOTE, ASCII value 34) # characters. # # qtext = %d33 / ; Printable US-ASCII # %d35-91 / ; characters not including # %d93-126 / ; "\" or the quote character # obs-qtext # # qcontent = qtext / quoted-pair # quoted-string = [CFWS] # DQUOTE *([FWS] qcontent) [FWS] DQUOTE # [CFWS] QTEXT = /\A[#{Regexp.escape([33..33, 35..91, 93..126].map { |ascii_range| ascii_range.map(&:chr) }.flatten.join)}\s]/i + IP_OCTET = /\A[0-9]+\Z/ + # From https://datatracker.ietf.org/doc/html/rfc1035#section-2.3.1 # # > The labels must follow the rules for ARPANET host names. They must # > start with a letter, end with a letter or digit, and have as interior # > characters only letters, digits, and hyphen. There are also some # > restrictions on the length. Labels must be 63 characters or less. # # <label> | <subdomain> "." <label> # <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ] # <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str> # <let-dig-hyp> ::= <let-dig> | "-" # <let-dig> ::= <letter> | <digit> - DomainPartLabel = /\A[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9]?\Z/ - - IPAddressPart = /\A[0-9]+\Z/ + DOMAIN_PART_LABEL = /\A[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9]?\Z/ # From https://tools.ietf.org/id/draft-liman-tld-names-00.html#rfc.section.2 # # > A TLD label MUST be at least two characters long and MAY be as long as 63 characters - # > not counting any leading or trailing periods (.). It MUST consist of only ASCII characters # > from the groups "letters" (A-Z), "digits" (0-9) and "hyphen" (-), and it MUST start with an # > ASCII "letter", and it MUST NOT end with a "hyphen". Upper and lower case MAY be mixed at random, # > since DNS lookups are case-insensitive. # # tldlabel = ALPHA *61(ldh) ld # ldh = ld / "-" # ld = ALPHA / DIGIT # ALPHA = %x41-5A / %x61-7A ; A-Z / a-z # DIGIT = %x30-39 ; 0-9 - DomainPartTLD = /\A[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9]\Z/ + DOMAIN_PART_TLD = /\A[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9]\Z/ def self.validate_email_domain(email, check_mx_timeout: 3) domain = email.to_s.downcase.match(/@(.+)/)[1] Resolv::DNS.open do |dns| dns.timeouts = check_mx_timeout @mx = dns.getresources(domain, Resolv::DNS::Resource::IN::MX) + dns.getresources(domain, Resolv::DNS::Resource::IN::A) end @mx.size > 0 end DEFAULT_MESSAGE = "does not appear to be valid" DEFAULT_MX_MESSAGE = "is not routable" ERROR_MESSAGE_I18N_KEY = :invalid_email_address ERROR_MX_MESSAGE_I18N_KEY = :email_address_not_routable def self.default_message defined?(I18n) ? I18n.t(ERROR_MESSAGE_I18N_KEY, scope: [:activemodel, :errors, :messages], default: DEFAULT_MESSAGE) : DEFAULT_MESSAGE end # Validates whether the specified value is a valid email address. Returns nil if the value is valid, otherwise returns an array # containing one or more validation error messages. # # Configuration options: # * <tt>message</tt> - A custom error message (default is: "does not appear to be valid") # * <tt>check_mx</tt> - Check for MX records (default is false) # * <tt>check_mx_timeout</tt> - Timeout in seconds for checking MX records before a `ResolvTimeout` is raised (default is 3) # * <tt>mx_message</tt> - A custom error message when an MX record validation fails (default is: "is not routable.") # * <tt>with</tt> The regex to use for validating the format of the email address (deprecated) # * <tt>local_length</tt> Maximum number of characters allowed in the local part (default is 64) # * <tt>domain_length</tt> Maximum number of characters allowed in the domain part (default is 255) # * <tt>generate_message</tt> Return the I18n key of the error message instead of the error message itself (default is false) def self.validate_email_format(email, options = {}) default_options = {message: options[:generate_message] ? ERROR_MESSAGE_I18N_KEY : default_message, check_mx: false, check_mx_timeout: 3, mx_message: if options[:generate_message] ERROR_MX_MESSAGE_I18N_KEY else (defined?(I18n) ? I18n.t(ERROR_MX_MESSAGE_I18N_KEY, scope: [:activemodel, :errors, :messages], default: DEFAULT_MX_MESSAGE) : DEFAULT_MX_MESSAGE) end, domain_length: 255, local_length: 64, generate_message: false} opts = options.merge(default_options) { |key, old, new| old } # merge the default options into the specified options, retaining all specified options begin domain, local = email.reverse.split("@", 2) rescue return [opts[:message]] end # need local and domain parts return [opts[:message]] unless local and !local.empty? and domain and !domain.empty? # check lengths return [opts[:message]] unless domain.length <= opts[:domain_length] and local.length <= opts[:local_length] local.reverse! domain.reverse! if opts.has_key?(:with) # holdover from versions <= 1.4.7 return [opts[:message]] unless email&.match?(opts[:with]) else return [opts[:message]] unless validate_local_part_syntax(local) and validate_domain_part_syntax(domain) end if opts[:check_mx] and !validate_email_domain(email, check_mx_timeout: opts[:check_mx_timeout]) return [opts[:mx_message]] end nil # represents no validation errors end def self.validate_local_part_syntax(local) in_quoted_pair = false in_quoted_string = false comment_depth = 0 (0..local.length - 1).each do |i| ord = local[i].ord # accept anything if it's got a backslash before it if in_quoted_pair in_quoted_pair = false next end if in_quoted_string next if QTEXT.match?(local[i]) end # opening paren to show we are going into a comment (CFWS) if ord == 40 comment_depth += 1 next end # closing paren if ord == 41 comment_depth -= 1 return false if comment_depth < 0 next end # backslash signifies the start of a quoted pair if ord == 92 and i < local.length - 1 return false if !in_quoted_string # must be in quoted string per http://www.rfc-editor.org/errata_search.php?rfc=3696 in_quoted_pair = true next end # double quote delimits quoted strings if ord == 34 in_quoted_string = !in_quoted_string next end if comment_depth > 0 next if CTEXT.match?(local[i]) elsif ATEXT.match?(local[i, 1]) next end # period must be followed by something if ord == 46 return false if i == 0 or i == local.length - 1 # can't be first or last char next unless local[i + 1].ord == 46 # can't be followed by a period end return false end return false if in_quoted_string # unbalanced quotes return false unless comment_depth.zero? # unbalanced comment parens true end def self.validate_domain_part_syntax(domain) parts = domain.downcase.split(".", -1) return false if parts.length <= 1 # Only one domain part # ipv4 - return true if parts.length == 4 && parts.all? { |part| part =~ IPAddressPart && part.to_i.between?(0, 255) } + return true if parts.length == 4 && parts.all? { |part| part =~ IP_OCTET && part.to_i.between?(0, 255) } # From https://datatracker.ietf.org/doc/html/rfc3696#section-2 this is the recommended, pragmatic way to validate a domain name: # # > It is likely that the better strategy has now become to make the "at least one period" test, # > to verify LDH conformance (including verification that the apparent TLD name is not all-numeric), # > and then to use the DNS to determine domain name validity, rather than trying to maintain # > a local list of valid TLD names. # # We do a little bit more but not too much and validate the tokens but do not check against a list of valid TLDs. parts.each do |part| return false if part.nil? || part.empty? return false if part.length > 63 - return false unless DomainPartLabel.match?(part) + return false unless DOMAIN_PART_LABEL.match?(part) end - return false unless DomainPartTLD.match?(parts[-1]) + return false unless DOMAIN_PART_TLD.match?(parts[-1]) true end end require "validates_email_format_of/active_model" if defined?(::ActiveModel) && !(ActiveModel::VERSION::MAJOR < 2 || (2 == ActiveModel::VERSION::MAJOR && ActiveModel::VERSION::MINOR < 1)) require "validates_email_format_of/railtie" if defined?(::Rails::Railtie)
validates-email-format-of/validates_email_format_of
99fea1232e464eb2ce7891abd1f2dddc2ce9f880
Define model_name instead of assigning a constant
diff --git a/spec/validates_email_format_of_spec.rb b/spec/validates_email_format_of_spec.rb index a335889..98e0fb6 100644 --- a/spec/validates_email_format_of_spec.rb +++ b/spec/validates_email_format_of_spec.rb @@ -1,332 +1,338 @@ require "#{__dir__}/spec_helper" require "validates_email_format_of" RSpec.configure do |config| config.before(:suite) do ValidatesEmailFormatOf.load_i18n_locales I18n.enforce_available_locales = false end end describe ValidatesEmailFormatOf do subject do |example| if defined?(ActiveModel) user = Class.new do def initialize(email) @email = email.freeze end attr_reader :email include ActiveModel::Validations validates_email_format_of :email, example.example_group_instance.options + + def self.model_name + ActiveModel::Name.new(self, nil, "User") + end end - example.example_group_instance.class::User = user user.new(example.example_group_instance.email).tap(&:valid?).errors.full_messages else ValidatesEmailFormatOf.validate_email_format(email.freeze, options) end end let(:options) { {} } let(:email) { |example| example.example_group.description } shared_examples_for :all_specs do [ "valid@example.com", "Valid@test.example.com", "valid+valid123@test.example.com", "valid_valid123@test.example.com", "valid-valid+123@test.example.co.uk", "valid-valid+1.23@test.example.com.au", "valid@example.co.uk", "v@example.com", "valid@example.ca", "valid_@example.com", "valid123.456@example.org", "valid123.456@example.travel", "valid123.456@example.museum", "valid@example.mobi", "valid@example.info", "valid-@example.com", "fake@p-t.k12.ok.us", # allow single character domain parts "valid@mail.x.example.com", "valid@x.com", "valid@example.w-dash.sch.uk", # from RFC 3696, page 6 "customer/department=shipping@example.com", "$A12345@example.com", "!def!xyz%abc@example.com", "_somename@example.com", # apostrophes "test'test@example.com", # international domain names "test@xn--bcher-kva.ch", "test@example.xn--0zwm56d", "test@192.192.192.1", # Allow quoted characters. Valid according to http://www.rfc-editor.org/errata_search.php?rfc=3696 '"Abc\@def"@example.com', '"Quote(Only".Chars@wier.de', '"Fred\ Bloggs"@example.com', '"Joe.\\Blow"@example.com', # Balanced quoted characters %("example\\\\\\""@example.com), %("example\\\\"@example.com), "(leading comment)email@example.com", "(nested (comment))email@example.com", "email(trailing comment)@example.com" ].each do |address| describe address do it { should_not have_errors_on_email } end end [ "no_at_symbol", "invalid@example-com", # period can not start local part ".invalid@example.com", # period can not end local part "invalid.@example.com", # period can not appear twice consecutively in local part "invali..d@example.com", # should not allow underscores in domain names "invalid@ex_mple.com", "invalid@e..example.com", "invalid@p-t..example.com", "invalid@example.com.", "invalid@example.com_", "invalid@example.com-", "invalid-example.com", "invalid@example.b#r.com", "invalid@example.c", "invali d@example.com", # TLD can not be only numeric "invalid@example.123", # unclosed quote "\"a-17180061943-10618354-1993365053@example.com", # too many special chars used to cause the regexp to hang "-+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++@foo", "invalidexample.com", # should not allow special chars after a period in the domain "local@sub.)domain.com", "local@sub.#domain.com", # one at a time "foo@example.com\nexample@gmail.com", "invalid@example.", "\"foo\\\\\"\"@bar.com", "foo@mail.com\r\nfoo@mail.com", "@example.com", "foo@", "foo", "Iñtërnâtiônàlizætiøn@hasnt.happened.to.email", # Escaped characters with quotes. From http://tools.ietf.org/html/rfc3696, page 5. Corrected in http://www.rfc-editor.org/errata_search.php?rfc=3696 'Fred\ Bloggs_@example.com', 'Abc\@def+@example.com', 'Joe.\\Blow@example.com', # Unbalanced quoted characters %("example\\\\""example.com), "\nnewline@example.com", " spacesbefore@example.com", "spacesafter@example.com ", "(unbalancedcomment@example.com" ].each do |address| describe address do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe do shared_examples_for :local_length_limit do |limit| describe "#{"a" * limit}@example.com" do it { should_not have_errors_on_email } end describe "#{"a" * (limit + 1)}@example.com" do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "when using default" do it_should_behave_like :local_length_limit, 64 end describe "when overriding defaults" do let(:options) { {local_length: 20} } it_should_behave_like :local_length_limit, 20 end end describe do shared_examples_for :domain_length_limit do |limit| describe "user@#{"a." * (limit / 2 - 3)}com" do it { should_not have_errors_on_email } end describe "user@#{"a." * (limit / 2 + 1)}com" do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "when using default" do it_should_behave_like :domain_length_limit, 255 end describe "when overriding defaults" do let(:options) { {domain_length: 100} } it_should_behave_like :domain_length_limit, 100 end end describe "custom error messages" do describe "invalid@example." do let(:options) { {message: "just because I don't like you"} } it { should have_errors_on_email.because("just because I don't like you") } end end describe "mx record" do domain = "example.com" email = "valid@#{domain}" check_mx_timeout = 3 describe "when testing" do let(:dns) { double(Resolv::DNS) } let(:mx_record) { [double] } let(:a_record) { [double] } before(:each) do allow(Resolv::DNS).to receive(:open).and_yield(dns) expect(dns).to receive(:"timeouts=").with(3).once allow(dns).to receive(:getresources).with(domain, Resolv::DNS::Resource::IN::MX).once.and_return(mx_record) allow(dns).to receive(:getresources).with(domain, Resolv::DNS::Resource::IN::A).once.and_return(a_record) end let(:options) { {check_mx: true} } describe "and only an mx record is found" do let(:a_record) { [] } describe email do it { should_not have_errors_on_email } end end describe "and only an a record is found" do let(:mx_record) { [] } describe email do it { should_not have_errors_on_email } end end describe "and both an mx record and an a record are found" do describe email do it { should_not have_errors_on_email } end end describe "and neither an mx record nor an a record is found" do let(:a_record) { [] } let(:mx_record) { [] } describe email do it { should have_errors_on_email.because("is not routable") } end describe "with a custom error message" do let(:options) { {check_mx: true, mx_message: "There ain't no such domain!"} } describe email do it { should have_errors_on_email.because("There ain't no such domain!") } end end describe "i18n" do before(:each) do allow(I18n.config).to receive(:locale).and_return(locale) end describe "present locale" do let(:locale) { :pl } describe email do it { should have_errors_on_email.because("jest nieosiągalny") } end end unless defined?(ActiveModel) describe email do let(:locale) { :ir } describe email do it { should have_errors_on_email.because("is not routable") } end end end end unless defined?(ActiveModel) describe "without i18n" do before(:each) { hide_const("I18n") } describe email do it { should have_errors_on_email.because("is not routable") } end end end end end describe "when not testing" do before(:each) { allow(Resolv::DNS).to receive(:open).never } describe "by default" do describe email do it { should_not have_errors_on_email } end end describe "explicitly" do describe email do let(:options) { {check_mx: false} } it { should_not have_errors_on_email } end end end describe "without mocks" do describe email do let(:options) { {check_mx: true} } it { should_not have_errors_on_email } end end end describe "custom regex" do let(:options) { {with: /[0-9]+@[0-9]+/} } describe "012345@789" do it { should_not have_errors_on_email } end describe "valid@example.com" do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "i18n" do before(:each) do allow(I18n.config).to receive(:locale).and_return(locale) end describe "present locale" do let(:locale) { :pl } describe "invalid@exmaple." do it { should have_errors_on_email.because("nieprawidłowy adres e-mail") } end end unless defined?(ActiveModel) describe "missing locale" do let(:locale) { :ir } describe "invalid@exmaple." do it { should have_errors_on_email.because("does not appear to be valid") } end end end end unless defined?(ActiveModel) describe "without i18n" do before(:each) { hide_const("I18n") } describe "invalid@exmaple." do it { should have_errors_on_email.because("does not appear to be valid") } end end end end it_should_behave_like :all_specs if defined?(ActiveModel) describe "shorthand ActiveModel validation" do subject do |example| user = Class.new do def initialize(email) @email = email.freeze end attr_reader :email include ActiveModel::Validations validates :email, email_format: example.example_group_instance.options + + def self.model_name + ActiveModel::Name.new(self, nil, "User") + end end - example.example_group_instance.class::User = user user.new(example.example_group_instance.email).tap(&:valid?).errors.full_messages end it_should_behave_like :all_specs end end end
validates-email-format-of/validates_email_format_of
e9bfff3cecba90a664805ce6a75295fc898f57ff
Wire up standard.rb to run automatically
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1051f7d..b68b3e8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -1,64 +1,67 @@ name: CI on: push: branches: [master] pull_request: branches: [master] permissions: contents: read jobs: test: name: "Ruby ${{ matrix.ruby }}, Rails ${{ matrix.gemfile }}" runs-on: ubuntu-latest strategy: matrix: ruby: ["2.6", "2.7", "3.0", "3.1"] gemfile: ["4.2", "5.0", "5.1", "5.2", "6.0", "6.1", "7.0"] exclude: - gemfile: "4.2" ruby: "3.0" - gemfile: "4.2" ruby: "3.1" - gemfile: "5.0" ruby: "3.0" - gemfile: "5.0" ruby: "3.1" - gemfile: "5.1" ruby: "3.0" - gemfile: "5.1" ruby: "3.1" - gemfile: "5.2" ruby: "3.0" - gemfile: "5.2" ruby: "3.1" - gemfile: "7.0" ruby: "2.5" - gemfile: "7.0" ruby: "2.6" - gemfile: "7.0" ruby: "2.7" env: BUNDLE_GEMFILE: gemfiles/rails_${{ matrix.gemfile }}.gemfile RAILS_ENV: test steps: - uses: actions/checkout@v3 - name: "Install Ruby ${{ matrix.ruby }}" # To automatically get bug fixes and new Ruby versions for ruby/setup-ruby, # change this to (see https://github.com/ruby/setup-ruby#versioning): # uses: ruby/setup-ruby@v1 uses: ruby/setup-ruby@v1 with: bundler: 1 ruby-version: ${{ matrix.ruby }} bundler-cache: true # runs 'bundle install' and caches installed gems automatically - name: Run specs run: bundle exec rspec + + - name: Run standard.rb + run: bundle exec rake standard diff --git a/rakefile.rb b/rakefile.rb index 1e1a3f7..8ade5f5 100644 --- a/rakefile.rb +++ b/rakefile.rb @@ -1,2 +1,4 @@ -require 'bundler/gem_tasks' -require 'standard/rake' +require "bundler/gem_tasks" +require "standard/rake" + +task default: [:spec, "standard:fix"]
validates-email-format-of/validates_email_format_of
a6c93e31dbea7d2f25c08b3e3d74bab121a1e1d4
Standard.rb style updates
diff --git a/Appraisals b/Appraisals index 122b1d6..51ed0d6 100644 --- a/Appraisals +++ b/Appraisals @@ -1,32 +1,32 @@ # run `bundle exec appraisal install` after making changes here appraise "rails-7.0" do gem "rails", "~> 7.0" end appraise "rails-6.1" do gem "rails", "~> 6.1.0" end appraise "rails-6.0" do - gem "rails", "~> 6.0.3", '>= 6.0.3.2' + gem "rails", "~> 6.0.3", ">= 6.0.3.2" end appraise "rails-5.2" do - gem "rails", "~> 5.2.4", '>= 5.2.4.3' + gem "rails", "~> 5.2.4", ">= 5.2.4.3" gem "i18n", "< 1" end appraise "rails-5.1" do gem "rails", "~> 5.1.7" gem "i18n", "< 1" end appraise "rails-5.0" do - gem "rails", "~> 5.0.7", '>= 5.0.7.2' + gem "rails", "~> 5.0.7", ">= 5.0.7.2" gem "i18n", "< 1" end appraise "rails-4.2" do gem "rails", "~> 4.2.0" gem "i18n", "< 1" end diff --git a/lib/validates_email_format_of.rb b/lib/validates_email_format_of.rb index a68ec16..925a868 100644 --- a/lib/validates_email_format_of.rb +++ b/lib/validates_email_format_of.rb @@ -1,252 +1,253 @@ -# encoding: utf-8 -require 'validates_email_format_of/version' +require "validates_email_format_of/version" module ValidatesEmailFormatOf def self.load_i18n_locales - require 'i18n' - I18n.load_path += Dir.glob(File.expand_path(File.join(File.dirname(__FILE__), '..', 'config', 'locales', '*.yml'))) + require "i18n" + I18n.load_path += Dir.glob(File.expand_path(File.join(File.dirname(__FILE__), "..", "config", "locales", "*.yml"))) end - require 'resolv' + require "resolv" - LocalPartSpecialChars = /[\!\#\$\%\&\'\*\-\/\=\?\+\^\_\`\{\|\}\~]/.freeze + LocalPartSpecialChars = /[!\#$%&'*\-\/=?+\^_`{|}~]/ # Characters that are allowed in to appear in the local part unquoted # https://www.rfc-editor.org/rfc/rfc5322#section-3.4.1 # # An addr-spec is a specific Internet identifier that contains a # locally interpreted string followed by the at-sign character ("@", # ASCII value 64) followed by an Internet domain. The locally # interpreted string is either a quoted-string or a dot-atom. If the # string can be represented as a dot-atom (that is, it contains no # characters other than atext characters or "." surrounded by atext # characters), then the dot-atom form SHOULD be used and the quoted- # string form SHOULD NOT be used. Comments and folding white space # SHOULD NOT be used around the "@" in the addr-spec. # # dot-atom-text = 1*atext *("." 1*atext) # dot-atom = [CFWS] dot-atom-text [CFWS] ATEXT = /\A[A-Z0-9#{LocalPartSpecialChars}]\z/i # Characters that are allowed to appear unquoted in comments # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.2 # # ctext = %d33-39 / %d42-91 / %d93-126 # ccontent = ctext / quoted-pair / comment # comment = "(" *([FWS] ccontent) [FWS] ")" # CFWS = (1*([FWS] comment) [FWS]) / FWS - CTEXT = /\A[#{Regexp.escape([33..39, 42..91, 93..126].map { |ascii_range| ascii_range.map(&:chr) }.flatten.join)}\s]/i.freeze + CTEXT = /\A[#{Regexp.escape([33..39, 42..91, 93..126].map { |ascii_range| ascii_range.map(&:chr) }.flatten.join)}\s]/i # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.4 # # Strings of characters that include characters other than those # allowed in atoms can be represented in a quoted string format, where # the characters are surrounded by quote (DQUOTE, ASCII value 34) # characters. # # qtext = %d33 / ; Printable US-ASCII # %d35-91 / ; characters not including # %d93-126 / ; "\" or the quote character # obs-qtext # # qcontent = qtext / quoted-pair # quoted-string = [CFWS] # DQUOTE *([FWS] qcontent) [FWS] DQUOTE # [CFWS] - QTEXT = /\A[#{Regexp.escape([33..33, 35..91, 93..126].map { |ascii_range| ascii_range.map(&:chr) }.flatten.join)}\s]/i.freeze + QTEXT = /\A[#{Regexp.escape([33..33, 35..91, 93..126].map { |ascii_range| ascii_range.map(&:chr) }.flatten.join)}\s]/i # From https://datatracker.ietf.org/doc/html/rfc1035#section-2.3.1 # # > The labels must follow the rules for ARPANET host names. They must # > start with a letter, end with a letter or digit, and have as interior # > characters only letters, digits, and hyphen. There are also some # > restrictions on the length. Labels must be 63 characters or less. # # <label> | <subdomain> "." <label> # <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ] # <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str> # <let-dig-hyp> ::= <let-dig> | "-" # <let-dig> ::= <letter> | <digit> - DomainPartLabel = /\A[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9]?\Z/.freeze + DomainPartLabel = /\A[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9]?\Z/ - IPAddressPart = /\A[0-9]+\Z/.freeze + IPAddressPart = /\A[0-9]+\Z/ # From https://tools.ietf.org/id/draft-liman-tld-names-00.html#rfc.section.2 # # > A TLD label MUST be at least two characters long and MAY be as long as 63 characters - # > not counting any leading or trailing periods (.). It MUST consist of only ASCII characters # > from the groups "letters" (A-Z), "digits" (0-9) and "hyphen" (-), and it MUST start with an # > ASCII "letter", and it MUST NOT end with a "hyphen". Upper and lower case MAY be mixed at random, # > since DNS lookups are case-insensitive. # # tldlabel = ALPHA *61(ldh) ld # ldh = ld / "-" # ld = ALPHA / DIGIT # ALPHA = %x41-5A / %x61-7A ; A-Z / a-z # DIGIT = %x30-39 ; 0-9 - DomainPartTLD = /\A[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9]\Z/.freeze + DomainPartTLD = /\A[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9]\Z/ def self.validate_email_domain(email, check_mx_timeout: 3) - domain = email.to_s.downcase.match(/\@(.+)/)[1] + domain = email.to_s.downcase.match(/@(.+)/)[1] Resolv::DNS.open do |dns| dns.timeouts = check_mx_timeout @mx = dns.getresources(domain, Resolv::DNS::Resource::IN::MX) + dns.getresources(domain, Resolv::DNS::Resource::IN::A) end - @mx.size > 0 ? true : false + @mx.size > 0 end DEFAULT_MESSAGE = "does not appear to be valid" DEFAULT_MX_MESSAGE = "is not routable" ERROR_MESSAGE_I18N_KEY = :invalid_email_address ERROR_MX_MESSAGE_I18N_KEY = :email_address_not_routable def self.default_message - defined?(I18n) ? I18n.t(ERROR_MESSAGE_I18N_KEY, :scope => [:activemodel, :errors, :messages], :default => DEFAULT_MESSAGE) : DEFAULT_MESSAGE + defined?(I18n) ? I18n.t(ERROR_MESSAGE_I18N_KEY, scope: [:activemodel, :errors, :messages], default: DEFAULT_MESSAGE) : DEFAULT_MESSAGE end # Validates whether the specified value is a valid email address. Returns nil if the value is valid, otherwise returns an array # containing one or more validation error messages. # # Configuration options: # * <tt>message</tt> - A custom error message (default is: "does not appear to be valid") # * <tt>check_mx</tt> - Check for MX records (default is false) # * <tt>check_mx_timeout</tt> - Timeout in seconds for checking MX records before a `ResolvTimeout` is raised (default is 3) # * <tt>mx_message</tt> - A custom error message when an MX record validation fails (default is: "is not routable.") # * <tt>with</tt> The regex to use for validating the format of the email address (deprecated) # * <tt>local_length</tt> Maximum number of characters allowed in the local part (default is 64) # * <tt>domain_length</tt> Maximum number of characters allowed in the domain part (default is 255) # * <tt>generate_message</tt> Return the I18n key of the error message instead of the error message itself (default is false) - def self.validate_email_format(email, options={}) - default_options = { :message => options[:generate_message] ? ERROR_MESSAGE_I18N_KEY : default_message, - :check_mx => false, - :check_mx_timeout => 3, - :mx_message => options[:generate_message] ? ERROR_MX_MESSAGE_I18N_KEY : (defined?(I18n) ? I18n.t(ERROR_MX_MESSAGE_I18N_KEY, :scope => [:activemodel, :errors, :messages], :default => DEFAULT_MX_MESSAGE) : DEFAULT_MX_MESSAGE), - :domain_length => 255, - :local_length => 64, - :generate_message => false - } - opts = options.merge(default_options) {|key, old, new| old} # merge the default options into the specified options, retaining all specified options - - begin - domain, local = email.reverse.split('@', 2) - rescue - return [ opts[:message] ] - end + def self.validate_email_format(email, options = {}) + default_options = {message: options[:generate_message] ? ERROR_MESSAGE_I18N_KEY : default_message, + check_mx: false, + check_mx_timeout: 3, + mx_message: if options[:generate_message] + ERROR_MX_MESSAGE_I18N_KEY + else + (defined?(I18n) ? I18n.t(ERROR_MX_MESSAGE_I18N_KEY, scope: [:activemodel, :errors, :messages], default: DEFAULT_MX_MESSAGE) : DEFAULT_MX_MESSAGE) + end, + domain_length: 255, + local_length: 64, + generate_message: false} + opts = options.merge(default_options) { |key, old, new| old } # merge the default options into the specified options, retaining all specified options + + begin + domain, local = email.reverse.split("@", 2) + rescue + return [opts[:message]] + end - # need local and domain parts - return [ opts[:message] ] unless local and not local.empty? and domain and not domain.empty? + # need local and domain parts + return [opts[:message]] unless local and !local.empty? and domain and !domain.empty? - # check lengths - return [ opts[:message] ] unless domain.length <= opts[:domain_length] and local.length <= opts[:local_length] + # check lengths + return [opts[:message]] unless domain.length <= opts[:domain_length] and local.length <= opts[:local_length] - local.reverse! - domain.reverse! + local.reverse! + domain.reverse! - if opts.has_key?(:with) # holdover from versions <= 1.4.7 - return [ opts[:message] ] unless email =~ opts[:with] - else - return [ opts[:message] ] unless self.validate_local_part_syntax(local) and self.validate_domain_part_syntax(domain) - end + if opts.has_key?(:with) # holdover from versions <= 1.4.7 + return [opts[:message]] unless email&.match?(opts[:with]) + else + return [opts[:message]] unless validate_local_part_syntax(local) and validate_domain_part_syntax(domain) + end - if opts[:check_mx] and !self.validate_email_domain(email, check_mx_timeout: opts[:check_mx_timeout]) - return [ opts[:mx_message] ] - end + if opts[:check_mx] and !validate_email_domain(email, check_mx_timeout: opts[:check_mx_timeout]) + return [opts[:mx_message]] + end - return nil # represents no validation errors + nil # represents no validation errors end - def self.validate_local_part_syntax(local) in_quoted_pair = false in_quoted_string = false comment_depth = 0 - (0..local.length-1).each do |i| + (0..local.length - 1).each do |i| ord = local[i].ord # accept anything if it's got a backslash before it if in_quoted_pair in_quoted_pair = false next end if in_quoted_string - next if local[i] =~ QTEXT + next if QTEXT.match?(local[i]) end # opening paren to show we are going into a comment (CFWS) if ord == 40 comment_depth += 1 next end # closing paren if ord == 41 comment_depth -= 1 return false if comment_depth < 0 next end # backslash signifies the start of a quoted pair if ord == 92 and i < local.length - 1 - return false if not in_quoted_string # must be in quoted string per http://www.rfc-editor.org/errata_search.php?rfc=3696 + return false if !in_quoted_string # must be in quoted string per http://www.rfc-editor.org/errata_search.php?rfc=3696 in_quoted_pair = true next end # double quote delimits quoted strings if ord == 34 in_quoted_string = !in_quoted_string next end if comment_depth > 0 - next if local[i] =~ CTEXT - else - next if local[i,1] =~ ATEXT + next if CTEXT.match?(local[i]) + elsif ATEXT.match?(local[i, 1]) + next end # period must be followed by something if ord == 46 return false if i == 0 or i == local.length - 1 # can't be first or last char - next unless local[i+1].ord == 46 # can't be followed by a period + next unless local[i + 1].ord == 46 # can't be followed by a period end return false end return false if in_quoted_string # unbalanced quotes return false unless comment_depth.zero? # unbalanced comment parens - return true + true end def self.validate_domain_part_syntax(domain) - parts = domain.downcase.split('.', -1) + parts = domain.downcase.split(".", -1) return false if parts.length <= 1 # Only one domain part # ipv4 return true if parts.length == 4 && parts.all? { |part| part =~ IPAddressPart && part.to_i.between?(0, 255) } # From https://datatracker.ietf.org/doc/html/rfc3696#section-2 this is the recommended, pragmatic way to validate a domain name: # # > It is likely that the better strategy has now become to make the "at least one period" test, # > to verify LDH conformance (including verification that the apparent TLD name is not all-numeric), # > and then to use the DNS to determine domain name validity, rather than trying to maintain # > a local list of valid TLD names. # # We do a little bit more but not too much and validate the tokens but do not check against a list of valid TLDs. parts.each do |part| return false if part.nil? || part.empty? return false if part.length > 63 - return false unless part =~ DomainPartLabel + return false unless DomainPartLabel.match?(part) end - return false unless parts[-1] =~ DomainPartTLD - return true + return false unless DomainPartTLD.match?(parts[-1]) + true end end -require 'validates_email_format_of/active_model' if defined?(::ActiveModel) && !(ActiveModel::VERSION::MAJOR < 2 || (2 == ActiveModel::VERSION::MAJOR && ActiveModel::VERSION::MINOR < 1)) -require 'validates_email_format_of/railtie' if defined?(::Rails::Railtie) +require "validates_email_format_of/active_model" if defined?(::ActiveModel) && !(ActiveModel::VERSION::MAJOR < 2 || (2 == ActiveModel::VERSION::MAJOR && ActiveModel::VERSION::MINOR < 1)) +require "validates_email_format_of/railtie" if defined?(::Rails::Railtie) diff --git a/lib/validates_email_format_of/active_model.rb b/lib/validates_email_format_of/active_model.rb index b9a95a7..1cedf9c 100644 --- a/lib/validates_email_format_of/active_model.rb +++ b/lib/validates_email_format_of/active_model.rb @@ -1,24 +1,24 @@ -require 'validates_email_format_of' -require 'active_model' +require "validates_email_format_of" +require "active_model" if ActiveModel::VERSION::MAJOR < 2 || (2 == ActiveModel::VERSION::MAJOR && ActiveModel::VERSION::MINOR < 1) puts "WARNING: ActiveModel validation helper methods in validates_email_format_of gem are not compatible with ActiveModel < 2.1.0. Please use ValidatesEmailFormatOf::validate_email_format(email, options) or upgrade ActiveModel" end module ActiveModel module Validations class EmailFormatValidator < EachValidator def validate_each(record, attribute, value) - (ValidatesEmailFormatOf::validate_email_format(value, options.merge(:generate_message => true)) || []).each do |error| + (ValidatesEmailFormatOf.validate_email_format(value, options.merge(generate_message: true)) || []).each do |error| record.errors.add(attribute, error) end end end module HelperMethods def validates_email_format_of(*attr_names) validates_with EmailFormatValidator, _merge_attributes(attr_names) end end end end diff --git a/lib/validates_email_format_of/railtie.rb b/lib/validates_email_format_of/railtie.rb index 6937342..e67f479 100644 --- a/lib/validates_email_format_of/railtie.rb +++ b/lib/validates_email_format_of/railtie.rb @@ -1,7 +1,7 @@ module ValidatesEmailFormatOf class Railtie < Rails::Railtie - initializer 'validates_email_format_of.load_i18n_locales' do |app| - ValidatesEmailFormatOf::load_i18n_locales + initializer "validates_email_format_of.load_i18n_locales" do |app| + ValidatesEmailFormatOf.load_i18n_locales end end end diff --git a/lib/validates_email_format_of/version.rb b/lib/validates_email_format_of/version.rb index ff8a9d4..ac9b371 100644 --- a/lib/validates_email_format_of/version.rb +++ b/lib/validates_email_format_of/version.rb @@ -1,3 +1,3 @@ module ValidatesEmailFormatOf - VERSION = '1.6.3' + VERSION = "1.6.3" end diff --git a/spec/rspec_matcher_spec.rb b/spec/rspec_matcher_spec.rb index bc0496c..37ee2f6 100644 --- a/spec/rspec_matcher_spec.rb +++ b/spec/rspec_matcher_spec.rb @@ -1,14 +1,14 @@ -require "#{File.expand_path(File.dirname(__FILE__))}/spec_helper" +require "#{__dir__}/spec_helper" if defined?(ActiveModel) require "validates_email_format_of/rspec_matcher" class Person attr_accessor :email_address include ::ActiveModel::Validations validates_email_format_of :email_address end describe Person do it { should validate_email_format_of(:email_address) } end end diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 29cd87e..2bf92ef 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,24 +1,24 @@ -require 'active_model' if Gem.loaded_specs.keys.include?('activemodel') -require 'pry' -require 'byebug' +require "active_model" if Gem.loaded_specs.keys.include?("activemodel") +require "pry" +require "byebug" RSpec::Matchers.define :have_errors_on_email do match do |actual| expect(actual).not_to be_nil, "#{actual} should not be nil" expect(actual).not_to be_empty, "#{actual} should not be empty" expect(actual.size).to eq(@reasons.size), "#{actual} should have #{@reasons.size} elements" @reasons.each do |reason| reason = "#{"Email " if defined?(ActiveModel)}#{reason}" expect(actual).to include(reason), "#{actual} should contain #{reason}" end end chain :because do |reason| (@reasons ||= []) << reason end chain :and_because do |reason| (@reasons ||= []) << reason end match_when_negated do |actual| - expect(actual).to (defined?(ActiveModel) ? be_empty : be_nil) + expect(actual).to(defined?(ActiveModel) ? be_empty : be_nil) end end diff --git a/spec/validates_email_format_of_spec.rb b/spec/validates_email_format_of_spec.rb index 8e03f3e..a335889 100644 --- a/spec/validates_email_format_of_spec.rb +++ b/spec/validates_email_format_of_spec.rb @@ -1,333 +1,332 @@ -# -*- encoding : utf-8 -*- -require "#{File.expand_path(File.dirname(__FILE__))}/spec_helper" +require "#{__dir__}/spec_helper" require "validates_email_format_of" RSpec.configure do |config| config.before(:suite) do ValidatesEmailFormatOf.load_i18n_locales I18n.enforce_available_locales = false end end describe ValidatesEmailFormatOf do subject do |example| if defined?(ActiveModel) user = Class.new do def initialize(email) @email = email.freeze end attr_reader :email include ActiveModel::Validations validates_email_format_of :email, example.example_group_instance.options end example.example_group_instance.class::User = user user.new(example.example_group_instance.email).tap(&:valid?).errors.full_messages else - ValidatesEmailFormatOf::validate_email_format(email.freeze, options) + ValidatesEmailFormatOf.validate_email_format(email.freeze, options) end end let(:options) { {} } let(:email) { |example| example.example_group.description } shared_examples_for :all_specs do [ - 'valid@example.com', - 'Valid@test.example.com', - 'valid+valid123@test.example.com', - 'valid_valid123@test.example.com', - 'valid-valid+123@test.example.co.uk', - 'valid-valid+1.23@test.example.com.au', - 'valid@example.co.uk', - 'v@example.com', - 'valid@example.ca', - 'valid_@example.com', - 'valid123.456@example.org', - 'valid123.456@example.travel', - 'valid123.456@example.museum', - 'valid@example.mobi', - 'valid@example.info', - 'valid-@example.com', - 'fake@p-t.k12.ok.us', + "valid@example.com", + "Valid@test.example.com", + "valid+valid123@test.example.com", + "valid_valid123@test.example.com", + "valid-valid+123@test.example.co.uk", + "valid-valid+1.23@test.example.com.au", + "valid@example.co.uk", + "v@example.com", + "valid@example.ca", + "valid_@example.com", + "valid123.456@example.org", + "valid123.456@example.travel", + "valid123.456@example.museum", + "valid@example.mobi", + "valid@example.info", + "valid-@example.com", + "fake@p-t.k12.ok.us", # allow single character domain parts - 'valid@mail.x.example.com', - 'valid@x.com', - 'valid@example.w-dash.sch.uk', + "valid@mail.x.example.com", + "valid@x.com", + "valid@example.w-dash.sch.uk", # from RFC 3696, page 6 - 'customer/department=shipping@example.com', - '$A12345@example.com', - '!def!xyz%abc@example.com', - '_somename@example.com', + "customer/department=shipping@example.com", + "$A12345@example.com", + "!def!xyz%abc@example.com", + "_somename@example.com", # apostrophes "test'test@example.com", # international domain names - 'test@xn--bcher-kva.ch', - 'test@example.xn--0zwm56d', - 'test@192.192.192.1', + "test@xn--bcher-kva.ch", + "test@example.xn--0zwm56d", + "test@192.192.192.1", # Allow quoted characters. Valid according to http://www.rfc-editor.org/errata_search.php?rfc=3696 '"Abc\@def"@example.com', '"Quote(Only".Chars@wier.de', '"Fred\ Bloggs"@example.com', '"Joe.\\Blow"@example.com', # Balanced quoted characters - %!"example\\\\\\""@example.com!, - %!"example\\\\"@example.com!, - '(leading comment)email@example.com', - '(nested (comment))email@example.com', - 'email(trailing comment)@example.com' + %("example\\\\\\""@example.com), + %("example\\\\"@example.com), + "(leading comment)email@example.com", + "(nested (comment))email@example.com", + "email(trailing comment)@example.com" ].each do |address| describe address do it { should_not have_errors_on_email } end end [ - 'no_at_symbol', - 'invalid@example-com', + "no_at_symbol", + "invalid@example-com", # period can not start local part - '.invalid@example.com', + ".invalid@example.com", # period can not end local part - 'invalid.@example.com', + "invalid.@example.com", # period can not appear twice consecutively in local part - 'invali..d@example.com', + "invali..d@example.com", # should not allow underscores in domain names - 'invalid@ex_mple.com', - 'invalid@e..example.com', - 'invalid@p-t..example.com', - 'invalid@example.com.', - 'invalid@example.com_', - 'invalid@example.com-', - 'invalid-example.com', - 'invalid@example.b#r.com', - 'invalid@example.c', - 'invali d@example.com', + "invalid@ex_mple.com", + "invalid@e..example.com", + "invalid@p-t..example.com", + "invalid@example.com.", + "invalid@example.com_", + "invalid@example.com-", + "invalid-example.com", + "invalid@example.b#r.com", + "invalid@example.c", + "invali d@example.com", # TLD can not be only numeric - 'invalid@example.123', + "invalid@example.123", # unclosed quote "\"a-17180061943-10618354-1993365053@example.com", # too many special chars used to cause the regexp to hang "-+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++@foo", - 'invalidexample.com', + "invalidexample.com", # should not allow special chars after a period in the domain - 'local@sub.)domain.com', - 'local@sub.#domain.com', + "local@sub.)domain.com", + "local@sub.#domain.com", # one at a time "foo@example.com\nexample@gmail.com", - 'invalid@example.', + "invalid@example.", "\"foo\\\\\"\"@bar.com", "foo@mail.com\r\nfoo@mail.com", - '@example.com', - 'foo@', - 'foo', - 'Iñtërnâtiônàlizætiøn@hasnt.happened.to.email', + "@example.com", + "foo@", + "foo", + "Iñtërnâtiônàlizætiøn@hasnt.happened.to.email", # Escaped characters with quotes. From http://tools.ietf.org/html/rfc3696, page 5. Corrected in http://www.rfc-editor.org/errata_search.php?rfc=3696 'Fred\ Bloggs_@example.com', 'Abc\@def+@example.com', 'Joe.\\Blow@example.com', # Unbalanced quoted characters - %!"example\\\\""example.com!, + %("example\\\\""example.com), "\nnewline@example.com", " spacesbefore@example.com", "spacesafter@example.com ", "(unbalancedcomment@example.com" ].each do |address| describe address do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe do shared_examples_for :local_length_limit do |limit| - describe "#{'a' * limit}@example.com" do + describe "#{"a" * limit}@example.com" do it { should_not have_errors_on_email } end - describe "#{'a' * (limit + 1)}@example.com" do + describe "#{"a" * (limit + 1)}@example.com" do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "when using default" do it_should_behave_like :local_length_limit, 64 end describe "when overriding defaults" do - let(:options) { { :local_length => 20 } } + let(:options) { {local_length: 20} } it_should_behave_like :local_length_limit, 20 end end describe do shared_examples_for :domain_length_limit do |limit| - describe "user@#{'a.' * (limit / 2 - 3)}com" do + describe "user@#{"a." * (limit / 2 - 3)}com" do it { should_not have_errors_on_email } end - describe "user@#{'a.' * (limit / 2 + 1)}com" do + describe "user@#{"a." * (limit / 2 + 1)}com" do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "when using default" do it_should_behave_like :domain_length_limit, 255 end describe "when overriding defaults" do - let(:options) { { :domain_length => 100 } } + let(:options) { {domain_length: 100} } it_should_behave_like :domain_length_limit, 100 end end describe "custom error messages" do - describe 'invalid@example.' do - let(:options) { { :message => "just because I don't like you" } } + describe "invalid@example." do + let(:options) { {message: "just because I don't like you"} } it { should have_errors_on_email.because("just because I don't like you") } end end describe "mx record" do domain = "example.com" email = "valid@#{domain}" check_mx_timeout = 3 describe "when testing" do let(:dns) { double(Resolv::DNS) } let(:mx_record) { [double] } let(:a_record) { [double] } before(:each) do allow(Resolv::DNS).to receive(:open).and_yield(dns) expect(dns).to receive(:"timeouts=").with(3).once allow(dns).to receive(:getresources).with(domain, Resolv::DNS::Resource::IN::MX).once.and_return(mx_record) allow(dns).to receive(:getresources).with(domain, Resolv::DNS::Resource::IN::A).once.and_return(a_record) end - let(:options) { { :check_mx => true } } + let(:options) { {check_mx: true} } describe "and only an mx record is found" do let(:a_record) { [] } describe email do it { should_not have_errors_on_email } end end describe "and only an a record is found" do let(:mx_record) { [] } describe email do it { should_not have_errors_on_email } end end describe "and both an mx record and an a record are found" do describe email do it { should_not have_errors_on_email } end end describe "and neither an mx record nor an a record is found" do let(:a_record) { [] } let(:mx_record) { [] } describe email do it { should have_errors_on_email.because("is not routable") } end describe "with a custom error message" do - let(:options) { { :check_mx => true, :mx_message => "There ain't no such domain!" } } + let(:options) { {check_mx: true, mx_message: "There ain't no such domain!"} } describe email do it { should have_errors_on_email.because("There ain't no such domain!") } end end describe "i18n" do before(:each) do allow(I18n.config).to receive(:locale).and_return(locale) end describe "present locale" do let(:locale) { :pl } describe email do it { should have_errors_on_email.because("jest nieosiągalny") } end end unless defined?(ActiveModel) describe email do let(:locale) { :ir } describe email do it { should have_errors_on_email.because("is not routable") } end end end end unless defined?(ActiveModel) describe "without i18n" do before(:each) { hide_const("I18n") } describe email do it { should have_errors_on_email.because("is not routable") } end end end end end describe "when not testing" do before(:each) { allow(Resolv::DNS).to receive(:open).never } describe "by default" do describe email do it { should_not have_errors_on_email } end end describe "explicitly" do describe email do - let(:options) { { :check_mx => false } } + let(:options) { {check_mx: false} } it { should_not have_errors_on_email } end end end describe "without mocks" do describe email do - let(:options) { { :check_mx => true } } + let(:options) { {check_mx: true} } it { should_not have_errors_on_email } end end end describe "custom regex" do - let(:options) { { :with => /[0-9]+\@[0-9]+/ } } - describe '012345@789' do + let(:options) { {with: /[0-9]+@[0-9]+/} } + describe "012345@789" do it { should_not have_errors_on_email } end - describe 'valid@example.com' do + describe "valid@example.com" do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "i18n" do before(:each) do allow(I18n.config).to receive(:locale).and_return(locale) end describe "present locale" do let(:locale) { :pl } describe "invalid@exmaple." do it { should have_errors_on_email.because("nieprawidłowy adres e-mail") } end end unless defined?(ActiveModel) describe "missing locale" do let(:locale) { :ir } describe "invalid@exmaple." do it { should have_errors_on_email.because("does not appear to be valid") } end end end end unless defined?(ActiveModel) describe "without i18n" do before(:each) { hide_const("I18n") } describe "invalid@exmaple." do it { should have_errors_on_email.because("does not appear to be valid") } end end end end it_should_behave_like :all_specs if defined?(ActiveModel) describe "shorthand ActiveModel validation" do subject do |example| user = Class.new do def initialize(email) @email = email.freeze end attr_reader :email include ActiveModel::Validations - validates :email, :email_format => example.example_group_instance.options + validates :email, email_format: example.example_group_instance.options end example.example_group_instance.class::User = user user.new(example.example_group_instance.email).tap(&:valid?).errors.full_messages end it_should_behave_like :all_specs end end end diff --git a/validates_email_format_of.gemspec b/validates_email_format_of.gemspec index e5e6062..1ace3af 100644 --- a/validates_email_format_of.gemspec +++ b/validates_email_format_of.gemspec @@ -1,28 +1,27 @@ -# -*- encoding: utf-8 -*- -$:.unshift File.expand_path('../lib', __FILE__) -require 'validates_email_format_of/version' +$:.unshift File.expand_path("../lib", __FILE__) +require "validates_email_format_of/version" spec = Gem::Specification.new do |s| - s.name = 'validates_email_format_of' - s.version = ValidatesEmailFormatOf::VERSION - s.summary = 'Validate e-mail addresses against RFC 2822 and RFC 3696.' - s.description = s.summary - s.authors = ['Alex Dunae', 'Isaac Betesh'] - s.email = ['code@dunae.ca', 'iybetesh@gmail.com'] - s.homepage = 'https://github.com/validates-email-format-of/validates_email_format_of' - s.license = 'MIT' - s.files = `git ls-files`.split($/) - s.require_paths = ['lib'] + s.name = "validates_email_format_of" + s.version = ValidatesEmailFormatOf::VERSION + s.summary = "Validate e-mail addresses against RFC 2822 and RFC 3696." + s.description = s.summary + s.authors = ["Alex Dunae", "Isaac Betesh"] + s.email = ["code@dunae.ca", "iybetesh@gmail.com"] + s.homepage = "https://github.com/validates-email-format-of/validates_email_format_of" + s.license = "MIT" + s.files = `git ls-files`.split($/) + s.require_paths = ["lib"] if RUBY_VERSION < "1.9.3" - s.add_dependency 'i18n', '< 0.7.0' + s.add_dependency "i18n", "< 0.7.0" else - s.add_dependency 'i18n' + s.add_dependency "i18n" end - s.add_development_dependency 'bundler' - s.add_development_dependency 'rspec' - s.add_development_dependency 'standard' - s.add_development_dependency 'appraisal' - s.add_development_dependency 'pry-byebug' + s.add_development_dependency "bundler" + s.add_development_dependency "rspec" + s.add_development_dependency "standard" + s.add_development_dependency "appraisal" + s.add_development_dependency "pry-byebug" end
validates-email-format-of/validates_email_format_of
2cbb0ee183a2631de817c035a4cee3330ef6773d
Setup Standard.rb
diff --git a/rakefile.rb b/rakefile.rb index c702cfc..1e1a3f7 100644 --- a/rakefile.rb +++ b/rakefile.rb @@ -1 +1,2 @@ require 'bundler/gem_tasks' +require 'standard/rake' diff --git a/validates_email_format_of.gemspec b/validates_email_format_of.gemspec index 19d9413..e5e6062 100644 --- a/validates_email_format_of.gemspec +++ b/validates_email_format_of.gemspec @@ -1,27 +1,28 @@ # -*- encoding: utf-8 -*- $:.unshift File.expand_path('../lib', __FILE__) require 'validates_email_format_of/version' spec = Gem::Specification.new do |s| s.name = 'validates_email_format_of' s.version = ValidatesEmailFormatOf::VERSION s.summary = 'Validate e-mail addresses against RFC 2822 and RFC 3696.' s.description = s.summary s.authors = ['Alex Dunae', 'Isaac Betesh'] s.email = ['code@dunae.ca', 'iybetesh@gmail.com'] s.homepage = 'https://github.com/validates-email-format-of/validates_email_format_of' s.license = 'MIT' s.files = `git ls-files`.split($/) s.require_paths = ['lib'] if RUBY_VERSION < "1.9.3" s.add_dependency 'i18n', '< 0.7.0' else s.add_dependency 'i18n' end s.add_development_dependency 'bundler' s.add_development_dependency 'rspec' + s.add_development_dependency 'standard' s.add_development_dependency 'appraisal' s.add_development_dependency 'pry-byebug' end
validates-email-format-of/validates_email_format_of
8fa9d4ff01e3119ba3a50949b6445d67193f9999
Add support for quoted text (QTEXT)
diff --git a/lib/validates_email_format_of.rb b/lib/validates_email_format_of.rb index d20cf3b..a68ec16 100644 --- a/lib/validates_email_format_of.rb +++ b/lib/validates_email_format_of.rb @@ -1,230 +1,252 @@ # encoding: utf-8 require 'validates_email_format_of/version' module ValidatesEmailFormatOf def self.load_i18n_locales require 'i18n' I18n.load_path += Dir.glob(File.expand_path(File.join(File.dirname(__FILE__), '..', 'config', 'locales', '*.yml'))) end require 'resolv' LocalPartSpecialChars = /[\!\#\$\%\&\'\*\-\/\=\?\+\^\_\`\{\|\}\~]/.freeze # Characters that are allowed in to appear in the local part unquoted # https://www.rfc-editor.org/rfc/rfc5322#section-3.4.1 # # An addr-spec is a specific Internet identifier that contains a # locally interpreted string followed by the at-sign character ("@", # ASCII value 64) followed by an Internet domain. The locally # interpreted string is either a quoted-string or a dot-atom. If the # string can be represented as a dot-atom (that is, it contains no # characters other than atext characters or "." surrounded by atext # characters), then the dot-atom form SHOULD be used and the quoted- # string form SHOULD NOT be used. Comments and folding white space # SHOULD NOT be used around the "@" in the addr-spec. # # dot-atom-text = 1*atext *("." 1*atext) # dot-atom = [CFWS] dot-atom-text [CFWS] ATEXT = /\A[A-Z0-9#{LocalPartSpecialChars}]\z/i # Characters that are allowed to appear unquoted in comments # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.2 # # ctext = %d33-39 / %d42-91 / %d93-126 # ccontent = ctext / quoted-pair / comment # comment = "(" *([FWS] ccontent) [FWS] ")" # CFWS = (1*([FWS] comment) [FWS]) / FWS CTEXT = /\A[#{Regexp.escape([33..39, 42..91, 93..126].map { |ascii_range| ascii_range.map(&:chr) }.flatten.join)}\s]/i.freeze + # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.4 + # + # Strings of characters that include characters other than those + # allowed in atoms can be represented in a quoted string format, where + # the characters are surrounded by quote (DQUOTE, ASCII value 34) + # characters. + # + # qtext = %d33 / ; Printable US-ASCII + # %d35-91 / ; characters not including + # %d93-126 / ; "\" or the quote character + # obs-qtext + # + # qcontent = qtext / quoted-pair + # quoted-string = [CFWS] + # DQUOTE *([FWS] qcontent) [FWS] DQUOTE + # [CFWS] + QTEXT = /\A[#{Regexp.escape([33..33, 35..91, 93..126].map { |ascii_range| ascii_range.map(&:chr) }.flatten.join)}\s]/i.freeze + # From https://datatracker.ietf.org/doc/html/rfc1035#section-2.3.1 # # > The labels must follow the rules for ARPANET host names. They must # > start with a letter, end with a letter or digit, and have as interior # > characters only letters, digits, and hyphen. There are also some # > restrictions on the length. Labels must be 63 characters or less. # # <label> | <subdomain> "." <label> # <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ] # <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str> # <let-dig-hyp> ::= <let-dig> | "-" # <let-dig> ::= <letter> | <digit> DomainPartLabel = /\A[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9]?\Z/.freeze IPAddressPart = /\A[0-9]+\Z/.freeze # From https://tools.ietf.org/id/draft-liman-tld-names-00.html#rfc.section.2 # # > A TLD label MUST be at least two characters long and MAY be as long as 63 characters - # > not counting any leading or trailing periods (.). It MUST consist of only ASCII characters # > from the groups "letters" (A-Z), "digits" (0-9) and "hyphen" (-), and it MUST start with an # > ASCII "letter", and it MUST NOT end with a "hyphen". Upper and lower case MAY be mixed at random, # > since DNS lookups are case-insensitive. # # tldlabel = ALPHA *61(ldh) ld # ldh = ld / "-" # ld = ALPHA / DIGIT # ALPHA = %x41-5A / %x61-7A ; A-Z / a-z # DIGIT = %x30-39 ; 0-9 DomainPartTLD = /\A[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9]\Z/.freeze def self.validate_email_domain(email, check_mx_timeout: 3) domain = email.to_s.downcase.match(/\@(.+)/)[1] Resolv::DNS.open do |dns| dns.timeouts = check_mx_timeout @mx = dns.getresources(domain, Resolv::DNS::Resource::IN::MX) + dns.getresources(domain, Resolv::DNS::Resource::IN::A) end @mx.size > 0 ? true : false end DEFAULT_MESSAGE = "does not appear to be valid" DEFAULT_MX_MESSAGE = "is not routable" ERROR_MESSAGE_I18N_KEY = :invalid_email_address ERROR_MX_MESSAGE_I18N_KEY = :email_address_not_routable def self.default_message defined?(I18n) ? I18n.t(ERROR_MESSAGE_I18N_KEY, :scope => [:activemodel, :errors, :messages], :default => DEFAULT_MESSAGE) : DEFAULT_MESSAGE end # Validates whether the specified value is a valid email address. Returns nil if the value is valid, otherwise returns an array # containing one or more validation error messages. # # Configuration options: # * <tt>message</tt> - A custom error message (default is: "does not appear to be valid") # * <tt>check_mx</tt> - Check for MX records (default is false) # * <tt>check_mx_timeout</tt> - Timeout in seconds for checking MX records before a `ResolvTimeout` is raised (default is 3) # * <tt>mx_message</tt> - A custom error message when an MX record validation fails (default is: "is not routable.") # * <tt>with</tt> The regex to use for validating the format of the email address (deprecated) # * <tt>local_length</tt> Maximum number of characters allowed in the local part (default is 64) # * <tt>domain_length</tt> Maximum number of characters allowed in the domain part (default is 255) # * <tt>generate_message</tt> Return the I18n key of the error message instead of the error message itself (default is false) def self.validate_email_format(email, options={}) default_options = { :message => options[:generate_message] ? ERROR_MESSAGE_I18N_KEY : default_message, :check_mx => false, :check_mx_timeout => 3, :mx_message => options[:generate_message] ? ERROR_MX_MESSAGE_I18N_KEY : (defined?(I18n) ? I18n.t(ERROR_MX_MESSAGE_I18N_KEY, :scope => [:activemodel, :errors, :messages], :default => DEFAULT_MX_MESSAGE) : DEFAULT_MX_MESSAGE), :domain_length => 255, :local_length => 64, :generate_message => false } opts = options.merge(default_options) {|key, old, new| old} # merge the default options into the specified options, retaining all specified options begin domain, local = email.reverse.split('@', 2) rescue return [ opts[:message] ] end # need local and domain parts return [ opts[:message] ] unless local and not local.empty? and domain and not domain.empty? # check lengths return [ opts[:message] ] unless domain.length <= opts[:domain_length] and local.length <= opts[:local_length] local.reverse! domain.reverse! if opts.has_key?(:with) # holdover from versions <= 1.4.7 return [ opts[:message] ] unless email =~ opts[:with] else return [ opts[:message] ] unless self.validate_local_part_syntax(local) and self.validate_domain_part_syntax(domain) end if opts[:check_mx] and !self.validate_email_domain(email, check_mx_timeout: opts[:check_mx_timeout]) return [ opts[:mx_message] ] end return nil # represents no validation errors end def self.validate_local_part_syntax(local) in_quoted_pair = false in_quoted_string = false comment_depth = 0 (0..local.length-1).each do |i| ord = local[i].ord # accept anything if it's got a backslash before it if in_quoted_pair in_quoted_pair = false next end + if in_quoted_string + next if local[i] =~ QTEXT + end + # opening paren to show we are going into a comment (CFWS) if ord == 40 comment_depth += 1 next end # closing paren if ord == 41 comment_depth -= 1 return false if comment_depth < 0 next end # backslash signifies the start of a quoted pair if ord == 92 and i < local.length - 1 return false if not in_quoted_string # must be in quoted string per http://www.rfc-editor.org/errata_search.php?rfc=3696 in_quoted_pair = true next end # double quote delimits quoted strings if ord == 34 in_quoted_string = !in_quoted_string next end if comment_depth > 0 next if local[i] =~ CTEXT else next if local[i,1] =~ ATEXT end # period must be followed by something if ord == 46 return false if i == 0 or i == local.length - 1 # can't be first or last char next unless local[i+1].ord == 46 # can't be followed by a period end return false end return false if in_quoted_string # unbalanced quotes return false unless comment_depth.zero? # unbalanced comment parens return true end def self.validate_domain_part_syntax(domain) parts = domain.downcase.split('.', -1) return false if parts.length <= 1 # Only one domain part # ipv4 return true if parts.length == 4 && parts.all? { |part| part =~ IPAddressPart && part.to_i.between?(0, 255) } # From https://datatracker.ietf.org/doc/html/rfc3696#section-2 this is the recommended, pragmatic way to validate a domain name: # # > It is likely that the better strategy has now become to make the "at least one period" test, # > to verify LDH conformance (including verification that the apparent TLD name is not all-numeric), # > and then to use the DNS to determine domain name validity, rather than trying to maintain # > a local list of valid TLD names. # # We do a little bit more but not too much and validate the tokens but do not check against a list of valid TLDs. parts.each do |part| return false if part.nil? || part.empty? return false if part.length > 63 return false unless part =~ DomainPartLabel end return false unless parts[-1] =~ DomainPartTLD return true end end require 'validates_email_format_of/active_model' if defined?(::ActiveModel) && !(ActiveModel::VERSION::MAJOR < 2 || (2 == ActiveModel::VERSION::MAJOR && ActiveModel::VERSION::MINOR < 1)) require 'validates_email_format_of/railtie' if defined?(::Rails::Railtie) diff --git a/spec/validates_email_format_of_spec.rb b/spec/validates_email_format_of_spec.rb index f983151..8e03f3e 100644 --- a/spec/validates_email_format_of_spec.rb +++ b/spec/validates_email_format_of_spec.rb @@ -1,332 +1,333 @@ # -*- encoding : utf-8 -*- require "#{File.expand_path(File.dirname(__FILE__))}/spec_helper" require "validates_email_format_of" RSpec.configure do |config| config.before(:suite) do ValidatesEmailFormatOf.load_i18n_locales I18n.enforce_available_locales = false end end describe ValidatesEmailFormatOf do subject do |example| if defined?(ActiveModel) user = Class.new do def initialize(email) @email = email.freeze end attr_reader :email include ActiveModel::Validations validates_email_format_of :email, example.example_group_instance.options end example.example_group_instance.class::User = user user.new(example.example_group_instance.email).tap(&:valid?).errors.full_messages else ValidatesEmailFormatOf::validate_email_format(email.freeze, options) end end let(:options) { {} } let(:email) { |example| example.example_group.description } shared_examples_for :all_specs do [ 'valid@example.com', 'Valid@test.example.com', 'valid+valid123@test.example.com', 'valid_valid123@test.example.com', 'valid-valid+123@test.example.co.uk', 'valid-valid+1.23@test.example.com.au', 'valid@example.co.uk', 'v@example.com', 'valid@example.ca', 'valid_@example.com', 'valid123.456@example.org', 'valid123.456@example.travel', 'valid123.456@example.museum', 'valid@example.mobi', 'valid@example.info', 'valid-@example.com', 'fake@p-t.k12.ok.us', # allow single character domain parts 'valid@mail.x.example.com', 'valid@x.com', 'valid@example.w-dash.sch.uk', # from RFC 3696, page 6 'customer/department=shipping@example.com', '$A12345@example.com', '!def!xyz%abc@example.com', '_somename@example.com', # apostrophes "test'test@example.com", # international domain names 'test@xn--bcher-kva.ch', 'test@example.xn--0zwm56d', 'test@192.192.192.1', # Allow quoted characters. Valid according to http://www.rfc-editor.org/errata_search.php?rfc=3696 '"Abc\@def"@example.com', + '"Quote(Only".Chars@wier.de', '"Fred\ Bloggs"@example.com', '"Joe.\\Blow"@example.com', # Balanced quoted characters %!"example\\\\\\""@example.com!, %!"example\\\\"@example.com!, '(leading comment)email@example.com', '(nested (comment))email@example.com', 'email(trailing comment)@example.com' ].each do |address| describe address do it { should_not have_errors_on_email } end end [ 'no_at_symbol', 'invalid@example-com', # period can not start local part '.invalid@example.com', # period can not end local part 'invalid.@example.com', # period can not appear twice consecutively in local part 'invali..d@example.com', # should not allow underscores in domain names 'invalid@ex_mple.com', 'invalid@e..example.com', 'invalid@p-t..example.com', 'invalid@example.com.', 'invalid@example.com_', 'invalid@example.com-', 'invalid-example.com', 'invalid@example.b#r.com', 'invalid@example.c', 'invali d@example.com', # TLD can not be only numeric 'invalid@example.123', # unclosed quote "\"a-17180061943-10618354-1993365053@example.com", # too many special chars used to cause the regexp to hang "-+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++@foo", 'invalidexample.com', # should not allow special chars after a period in the domain 'local@sub.)domain.com', 'local@sub.#domain.com', # one at a time "foo@example.com\nexample@gmail.com", 'invalid@example.', "\"foo\\\\\"\"@bar.com", "foo@mail.com\r\nfoo@mail.com", '@example.com', 'foo@', 'foo', 'Iñtërnâtiônàlizætiøn@hasnt.happened.to.email', # Escaped characters with quotes. From http://tools.ietf.org/html/rfc3696, page 5. Corrected in http://www.rfc-editor.org/errata_search.php?rfc=3696 'Fred\ Bloggs_@example.com', 'Abc\@def+@example.com', 'Joe.\\Blow@example.com', # Unbalanced quoted characters %!"example\\\\""example.com!, "\nnewline@example.com", " spacesbefore@example.com", "spacesafter@example.com ", "(unbalancedcomment@example.com" ].each do |address| describe address do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe do shared_examples_for :local_length_limit do |limit| describe "#{'a' * limit}@example.com" do it { should_not have_errors_on_email } end describe "#{'a' * (limit + 1)}@example.com" do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "when using default" do it_should_behave_like :local_length_limit, 64 end describe "when overriding defaults" do let(:options) { { :local_length => 20 } } it_should_behave_like :local_length_limit, 20 end end describe do shared_examples_for :domain_length_limit do |limit| describe "user@#{'a.' * (limit / 2 - 3)}com" do it { should_not have_errors_on_email } end describe "user@#{'a.' * (limit / 2 + 1)}com" do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "when using default" do it_should_behave_like :domain_length_limit, 255 end describe "when overriding defaults" do let(:options) { { :domain_length => 100 } } it_should_behave_like :domain_length_limit, 100 end end describe "custom error messages" do describe 'invalid@example.' do let(:options) { { :message => "just because I don't like you" } } it { should have_errors_on_email.because("just because I don't like you") } end end describe "mx record" do domain = "example.com" email = "valid@#{domain}" check_mx_timeout = 3 describe "when testing" do let(:dns) { double(Resolv::DNS) } let(:mx_record) { [double] } let(:a_record) { [double] } before(:each) do allow(Resolv::DNS).to receive(:open).and_yield(dns) expect(dns).to receive(:"timeouts=").with(3).once allow(dns).to receive(:getresources).with(domain, Resolv::DNS::Resource::IN::MX).once.and_return(mx_record) allow(dns).to receive(:getresources).with(domain, Resolv::DNS::Resource::IN::A).once.and_return(a_record) end let(:options) { { :check_mx => true } } describe "and only an mx record is found" do let(:a_record) { [] } describe email do it { should_not have_errors_on_email } end end describe "and only an a record is found" do let(:mx_record) { [] } describe email do it { should_not have_errors_on_email } end end describe "and both an mx record and an a record are found" do describe email do it { should_not have_errors_on_email } end end describe "and neither an mx record nor an a record is found" do let(:a_record) { [] } let(:mx_record) { [] } describe email do it { should have_errors_on_email.because("is not routable") } end describe "with a custom error message" do let(:options) { { :check_mx => true, :mx_message => "There ain't no such domain!" } } describe email do it { should have_errors_on_email.because("There ain't no such domain!") } end end describe "i18n" do before(:each) do allow(I18n.config).to receive(:locale).and_return(locale) end describe "present locale" do let(:locale) { :pl } describe email do it { should have_errors_on_email.because("jest nieosiągalny") } end end unless defined?(ActiveModel) describe email do let(:locale) { :ir } describe email do it { should have_errors_on_email.because("is not routable") } end end end end unless defined?(ActiveModel) describe "without i18n" do before(:each) { hide_const("I18n") } describe email do it { should have_errors_on_email.because("is not routable") } end end end end end describe "when not testing" do before(:each) { allow(Resolv::DNS).to receive(:open).never } describe "by default" do describe email do it { should_not have_errors_on_email } end end describe "explicitly" do describe email do let(:options) { { :check_mx => false } } it { should_not have_errors_on_email } end end end describe "without mocks" do describe email do let(:options) { { :check_mx => true } } it { should_not have_errors_on_email } end end end describe "custom regex" do let(:options) { { :with => /[0-9]+\@[0-9]+/ } } describe '012345@789' do it { should_not have_errors_on_email } end describe 'valid@example.com' do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "i18n" do before(:each) do allow(I18n.config).to receive(:locale).and_return(locale) end describe "present locale" do let(:locale) { :pl } describe "invalid@exmaple." do it { should have_errors_on_email.because("nieprawidłowy adres e-mail") } end end unless defined?(ActiveModel) describe "missing locale" do let(:locale) { :ir } describe "invalid@exmaple." do it { should have_errors_on_email.because("does not appear to be valid") } end end end end unless defined?(ActiveModel) describe "without i18n" do before(:each) { hide_const("I18n") } describe "invalid@exmaple." do it { should have_errors_on_email.because("does not appear to be valid") } end end end end it_should_behave_like :all_specs if defined?(ActiveModel) describe "shorthand ActiveModel validation" do subject do |example| user = Class.new do def initialize(email) @email = email.freeze end attr_reader :email include ActiveModel::Validations validates :email, :email_format => example.example_group_instance.options end example.example_group_instance.class::User = user user.new(example.example_group_instance.email).tap(&:valid?).errors.full_messages end it_should_behave_like :all_specs end end end
validates-email-format-of/validates_email_format_of
9fd6d99a51e85097732874502dbec8bc59fc3000
Add support for comments in the local part
diff --git a/lib/validates_email_format_of.rb b/lib/validates_email_format_of.rb index fb9bd6b..d20cf3b 100644 --- a/lib/validates_email_format_of.rb +++ b/lib/validates_email_format_of.rb @@ -1,186 +1,230 @@ # encoding: utf-8 require 'validates_email_format_of/version' module ValidatesEmailFormatOf def self.load_i18n_locales require 'i18n' I18n.load_path += Dir.glob(File.expand_path(File.join(File.dirname(__FILE__), '..', 'config', 'locales', '*.yml'))) end require 'resolv' LocalPartSpecialChars = /[\!\#\$\%\&\'\*\-\/\=\?\+\^\_\`\{\|\}\~]/.freeze + # Characters that are allowed in to appear in the local part unquoted + # https://www.rfc-editor.org/rfc/rfc5322#section-3.4.1 + # + # An addr-spec is a specific Internet identifier that contains a + # locally interpreted string followed by the at-sign character ("@", + # ASCII value 64) followed by an Internet domain. The locally + # interpreted string is either a quoted-string or a dot-atom. If the + # string can be represented as a dot-atom (that is, it contains no + # characters other than atext characters or "." surrounded by atext + # characters), then the dot-atom form SHOULD be used and the quoted- + # string form SHOULD NOT be used. Comments and folding white space + # SHOULD NOT be used around the "@" in the addr-spec. + # + # dot-atom-text = 1*atext *("." 1*atext) + # dot-atom = [CFWS] dot-atom-text [CFWS] + ATEXT = /\A[A-Z0-9#{LocalPartSpecialChars}]\z/i + + # Characters that are allowed to appear unquoted in comments + # https://www.rfc-editor.org/rfc/rfc5322#section-3.2.2 + # + # ctext = %d33-39 / %d42-91 / %d93-126 + # ccontent = ctext / quoted-pair / comment + # comment = "(" *([FWS] ccontent) [FWS] ")" + # CFWS = (1*([FWS] comment) [FWS]) / FWS + CTEXT = /\A[#{Regexp.escape([33..39, 42..91, 93..126].map { |ascii_range| ascii_range.map(&:chr) }.flatten.join)}\s]/i.freeze + # From https://datatracker.ietf.org/doc/html/rfc1035#section-2.3.1 # # > The labels must follow the rules for ARPANET host names. They must # > start with a letter, end with a letter or digit, and have as interior # > characters only letters, digits, and hyphen. There are also some # > restrictions on the length. Labels must be 63 characters or less. # # <label> | <subdomain> "." <label> # <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ] # <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str> # <let-dig-hyp> ::= <let-dig> | "-" # <let-dig> ::= <letter> | <digit> DomainPartLabel = /\A[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9]?\Z/.freeze IPAddressPart = /\A[0-9]+\Z/.freeze # From https://tools.ietf.org/id/draft-liman-tld-names-00.html#rfc.section.2 # # > A TLD label MUST be at least two characters long and MAY be as long as 63 characters - # > not counting any leading or trailing periods (.). It MUST consist of only ASCII characters # > from the groups "letters" (A-Z), "digits" (0-9) and "hyphen" (-), and it MUST start with an # > ASCII "letter", and it MUST NOT end with a "hyphen". Upper and lower case MAY be mixed at random, # > since DNS lookups are case-insensitive. # # tldlabel = ALPHA *61(ldh) ld # ldh = ld / "-" # ld = ALPHA / DIGIT # ALPHA = %x41-5A / %x61-7A ; A-Z / a-z # DIGIT = %x30-39 ; 0-9 DomainPartTLD = /\A[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9]\Z/.freeze def self.validate_email_domain(email, check_mx_timeout: 3) domain = email.to_s.downcase.match(/\@(.+)/)[1] Resolv::DNS.open do |dns| dns.timeouts = check_mx_timeout @mx = dns.getresources(domain, Resolv::DNS::Resource::IN::MX) + dns.getresources(domain, Resolv::DNS::Resource::IN::A) end @mx.size > 0 ? true : false end DEFAULT_MESSAGE = "does not appear to be valid" DEFAULT_MX_MESSAGE = "is not routable" ERROR_MESSAGE_I18N_KEY = :invalid_email_address ERROR_MX_MESSAGE_I18N_KEY = :email_address_not_routable def self.default_message defined?(I18n) ? I18n.t(ERROR_MESSAGE_I18N_KEY, :scope => [:activemodel, :errors, :messages], :default => DEFAULT_MESSAGE) : DEFAULT_MESSAGE end # Validates whether the specified value is a valid email address. Returns nil if the value is valid, otherwise returns an array # containing one or more validation error messages. # # Configuration options: # * <tt>message</tt> - A custom error message (default is: "does not appear to be valid") # * <tt>check_mx</tt> - Check for MX records (default is false) # * <tt>check_mx_timeout</tt> - Timeout in seconds for checking MX records before a `ResolvTimeout` is raised (default is 3) # * <tt>mx_message</tt> - A custom error message when an MX record validation fails (default is: "is not routable.") # * <tt>with</tt> The regex to use for validating the format of the email address (deprecated) # * <tt>local_length</tt> Maximum number of characters allowed in the local part (default is 64) # * <tt>domain_length</tt> Maximum number of characters allowed in the domain part (default is 255) # * <tt>generate_message</tt> Return the I18n key of the error message instead of the error message itself (default is false) def self.validate_email_format(email, options={}) default_options = { :message => options[:generate_message] ? ERROR_MESSAGE_I18N_KEY : default_message, :check_mx => false, :check_mx_timeout => 3, :mx_message => options[:generate_message] ? ERROR_MX_MESSAGE_I18N_KEY : (defined?(I18n) ? I18n.t(ERROR_MX_MESSAGE_I18N_KEY, :scope => [:activemodel, :errors, :messages], :default => DEFAULT_MX_MESSAGE) : DEFAULT_MX_MESSAGE), :domain_length => 255, :local_length => 64, :generate_message => false } opts = options.merge(default_options) {|key, old, new| old} # merge the default options into the specified options, retaining all specified options begin domain, local = email.reverse.split('@', 2) rescue return [ opts[:message] ] end # need local and domain parts return [ opts[:message] ] unless local and not local.empty? and domain and not domain.empty? # check lengths return [ opts[:message] ] unless domain.length <= opts[:domain_length] and local.length <= opts[:local_length] local.reverse! domain.reverse! if opts.has_key?(:with) # holdover from versions <= 1.4.7 return [ opts[:message] ] unless email =~ opts[:with] else return [ opts[:message] ] unless self.validate_local_part_syntax(local) and self.validate_domain_part_syntax(domain) end if opts[:check_mx] and !self.validate_email_domain(email, check_mx_timeout: opts[:check_mx_timeout]) return [ opts[:mx_message] ] end return nil # represents no validation errors end def self.validate_local_part_syntax(local) in_quoted_pair = false in_quoted_string = false + comment_depth = 0 (0..local.length-1).each do |i| ord = local[i].ord # accept anything if it's got a backslash before it if in_quoted_pair in_quoted_pair = false next end + # opening paren to show we are going into a comment (CFWS) + if ord == 40 + comment_depth += 1 + next + end + + # closing paren + if ord == 41 + comment_depth -= 1 + return false if comment_depth < 0 + next + end + # backslash signifies the start of a quoted pair if ord == 92 and i < local.length - 1 return false if not in_quoted_string # must be in quoted string per http://www.rfc-editor.org/errata_search.php?rfc=3696 in_quoted_pair = true next end # double quote delimits quoted strings if ord == 34 in_quoted_string = !in_quoted_string next end - next if local[i,1] =~ /[a-z0-9]/i - next if local[i,1] =~ LocalPartSpecialChars + if comment_depth > 0 + next if local[i] =~ CTEXT + else + next if local[i,1] =~ ATEXT + end # period must be followed by something if ord == 46 return false if i == 0 or i == local.length - 1 # can't be first or last char next unless local[i+1].ord == 46 # can't be followed by a period end return false end return false if in_quoted_string # unbalanced quotes + return false unless comment_depth.zero? # unbalanced comment parens return true end def self.validate_domain_part_syntax(domain) parts = domain.downcase.split('.', -1) return false if parts.length <= 1 # Only one domain part # ipv4 return true if parts.length == 4 && parts.all? { |part| part =~ IPAddressPart && part.to_i.between?(0, 255) } # From https://datatracker.ietf.org/doc/html/rfc3696#section-2 this is the recommended, pragmatic way to validate a domain name: # # > It is likely that the better strategy has now become to make the "at least one period" test, # > to verify LDH conformance (including verification that the apparent TLD name is not all-numeric), # > and then to use the DNS to determine domain name validity, rather than trying to maintain # > a local list of valid TLD names. # # We do a little bit more but not too much and validate the tokens but do not check against a list of valid TLDs. parts.each do |part| return false if part.nil? || part.empty? return false if part.length > 63 return false unless part =~ DomainPartLabel end return false unless parts[-1] =~ DomainPartTLD return true end end require 'validates_email_format_of/active_model' if defined?(::ActiveModel) && !(ActiveModel::VERSION::MAJOR < 2 || (2 == ActiveModel::VERSION::MAJOR && ActiveModel::VERSION::MINOR < 1)) require 'validates_email_format_of/railtie' if defined?(::Rails::Railtie) diff --git a/spec/validates_email_format_of_spec.rb b/spec/validates_email_format_of_spec.rb index d07d487..f983151 100644 --- a/spec/validates_email_format_of_spec.rb +++ b/spec/validates_email_format_of_spec.rb @@ -1,328 +1,332 @@ # -*- encoding : utf-8 -*- require "#{File.expand_path(File.dirname(__FILE__))}/spec_helper" require "validates_email_format_of" RSpec.configure do |config| config.before(:suite) do ValidatesEmailFormatOf.load_i18n_locales I18n.enforce_available_locales = false end end describe ValidatesEmailFormatOf do subject do |example| if defined?(ActiveModel) user = Class.new do def initialize(email) @email = email.freeze end attr_reader :email include ActiveModel::Validations validates_email_format_of :email, example.example_group_instance.options end example.example_group_instance.class::User = user user.new(example.example_group_instance.email).tap(&:valid?).errors.full_messages else ValidatesEmailFormatOf::validate_email_format(email.freeze, options) end end let(:options) { {} } let(:email) { |example| example.example_group.description } shared_examples_for :all_specs do [ 'valid@example.com', 'Valid@test.example.com', 'valid+valid123@test.example.com', 'valid_valid123@test.example.com', 'valid-valid+123@test.example.co.uk', 'valid-valid+1.23@test.example.com.au', 'valid@example.co.uk', 'v@example.com', 'valid@example.ca', 'valid_@example.com', 'valid123.456@example.org', 'valid123.456@example.travel', 'valid123.456@example.museum', 'valid@example.mobi', 'valid@example.info', 'valid-@example.com', 'fake@p-t.k12.ok.us', # allow single character domain parts 'valid@mail.x.example.com', 'valid@x.com', 'valid@example.w-dash.sch.uk', # from RFC 3696, page 6 'customer/department=shipping@example.com', '$A12345@example.com', '!def!xyz%abc@example.com', '_somename@example.com', # apostrophes "test'test@example.com", # international domain names 'test@xn--bcher-kva.ch', 'test@example.xn--0zwm56d', 'test@192.192.192.1', # Allow quoted characters. Valid according to http://www.rfc-editor.org/errata_search.php?rfc=3696 '"Abc\@def"@example.com', '"Fred\ Bloggs"@example.com', '"Joe.\\Blow"@example.com', # Balanced quoted characters %!"example\\\\\\""@example.com!, - %!"example\\\\"@example.com! + %!"example\\\\"@example.com!, + '(leading comment)email@example.com', + '(nested (comment))email@example.com', + 'email(trailing comment)@example.com' ].each do |address| describe address do it { should_not have_errors_on_email } end end [ 'no_at_symbol', 'invalid@example-com', # period can not start local part '.invalid@example.com', # period can not end local part 'invalid.@example.com', # period can not appear twice consecutively in local part 'invali..d@example.com', # should not allow underscores in domain names 'invalid@ex_mple.com', 'invalid@e..example.com', 'invalid@p-t..example.com', 'invalid@example.com.', 'invalid@example.com_', 'invalid@example.com-', 'invalid-example.com', 'invalid@example.b#r.com', 'invalid@example.c', 'invali d@example.com', # TLD can not be only numeric 'invalid@example.123', # unclosed quote "\"a-17180061943-10618354-1993365053@example.com", # too many special chars used to cause the regexp to hang "-+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++@foo", 'invalidexample.com', # should not allow special chars after a period in the domain 'local@sub.)domain.com', 'local@sub.#domain.com', # one at a time "foo@example.com\nexample@gmail.com", 'invalid@example.', "\"foo\\\\\"\"@bar.com", "foo@mail.com\r\nfoo@mail.com", '@example.com', 'foo@', 'foo', 'Iñtërnâtiônàlizætiøn@hasnt.happened.to.email', # Escaped characters with quotes. From http://tools.ietf.org/html/rfc3696, page 5. Corrected in http://www.rfc-editor.org/errata_search.php?rfc=3696 'Fred\ Bloggs_@example.com', 'Abc\@def+@example.com', 'Joe.\\Blow@example.com', # Unbalanced quoted characters %!"example\\\\""example.com!, "\nnewline@example.com", " spacesbefore@example.com", - "spacesafter@example.com " + "spacesafter@example.com ", + "(unbalancedcomment@example.com" ].each do |address| describe address do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe do shared_examples_for :local_length_limit do |limit| describe "#{'a' * limit}@example.com" do it { should_not have_errors_on_email } end describe "#{'a' * (limit + 1)}@example.com" do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "when using default" do it_should_behave_like :local_length_limit, 64 end describe "when overriding defaults" do let(:options) { { :local_length => 20 } } it_should_behave_like :local_length_limit, 20 end end describe do shared_examples_for :domain_length_limit do |limit| describe "user@#{'a.' * (limit / 2 - 3)}com" do it { should_not have_errors_on_email } end describe "user@#{'a.' * (limit / 2 + 1)}com" do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "when using default" do it_should_behave_like :domain_length_limit, 255 end describe "when overriding defaults" do let(:options) { { :domain_length => 100 } } it_should_behave_like :domain_length_limit, 100 end end describe "custom error messages" do describe 'invalid@example.' do let(:options) { { :message => "just because I don't like you" } } it { should have_errors_on_email.because("just because I don't like you") } end end describe "mx record" do domain = "example.com" email = "valid@#{domain}" check_mx_timeout = 3 describe "when testing" do let(:dns) { double(Resolv::DNS) } let(:mx_record) { [double] } let(:a_record) { [double] } before(:each) do allow(Resolv::DNS).to receive(:open).and_yield(dns) expect(dns).to receive(:"timeouts=").with(3).once allow(dns).to receive(:getresources).with(domain, Resolv::DNS::Resource::IN::MX).once.and_return(mx_record) allow(dns).to receive(:getresources).with(domain, Resolv::DNS::Resource::IN::A).once.and_return(a_record) end let(:options) { { :check_mx => true } } describe "and only an mx record is found" do let(:a_record) { [] } describe email do it { should_not have_errors_on_email } end end describe "and only an a record is found" do let(:mx_record) { [] } describe email do it { should_not have_errors_on_email } end end describe "and both an mx record and an a record are found" do describe email do it { should_not have_errors_on_email } end end describe "and neither an mx record nor an a record is found" do let(:a_record) { [] } let(:mx_record) { [] } describe email do it { should have_errors_on_email.because("is not routable") } end describe "with a custom error message" do let(:options) { { :check_mx => true, :mx_message => "There ain't no such domain!" } } describe email do it { should have_errors_on_email.because("There ain't no such domain!") } end end describe "i18n" do before(:each) do allow(I18n.config).to receive(:locale).and_return(locale) end describe "present locale" do let(:locale) { :pl } describe email do it { should have_errors_on_email.because("jest nieosiągalny") } end end unless defined?(ActiveModel) describe email do let(:locale) { :ir } describe email do it { should have_errors_on_email.because("is not routable") } end end end end unless defined?(ActiveModel) describe "without i18n" do before(:each) { hide_const("I18n") } describe email do it { should have_errors_on_email.because("is not routable") } end end end end end describe "when not testing" do before(:each) { allow(Resolv::DNS).to receive(:open).never } describe "by default" do describe email do it { should_not have_errors_on_email } end end describe "explicitly" do describe email do let(:options) { { :check_mx => false } } it { should_not have_errors_on_email } end end end describe "without mocks" do describe email do let(:options) { { :check_mx => true } } it { should_not have_errors_on_email } end end end describe "custom regex" do let(:options) { { :with => /[0-9]+\@[0-9]+/ } } describe '012345@789' do it { should_not have_errors_on_email } end describe 'valid@example.com' do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "i18n" do before(:each) do allow(I18n.config).to receive(:locale).and_return(locale) end describe "present locale" do let(:locale) { :pl } describe "invalid@exmaple." do it { should have_errors_on_email.because("nieprawidłowy adres e-mail") } end end unless defined?(ActiveModel) describe "missing locale" do let(:locale) { :ir } describe "invalid@exmaple." do it { should have_errors_on_email.because("does not appear to be valid") } end end end end unless defined?(ActiveModel) describe "without i18n" do before(:each) { hide_const("I18n") } describe "invalid@exmaple." do it { should have_errors_on_email.because("does not appear to be valid") } end end end end it_should_behave_like :all_specs if defined?(ActiveModel) describe "shorthand ActiveModel validation" do subject do |example| user = Class.new do def initialize(email) @email = email.freeze end attr_reader :email include ActiveModel::Validations validates :email, :email_format => example.example_group_instance.options end example.example_group_instance.class::User = user user.new(example.example_group_instance.email).tap(&:valid?).errors.full_messages end it_should_behave_like :all_specs end end end
validates-email-format-of/validates_email_format_of
2554b55e547c1fae6599d13b0c99296752888c91
Tighten up domain-part syntax validation
diff --git a/lib/validates_email_format_of.rb b/lib/validates_email_format_of.rb index a43eec4..fb9bd6b 100644 --- a/lib/validates_email_format_of.rb +++ b/lib/validates_email_format_of.rb @@ -1,151 +1,186 @@ # encoding: utf-8 require 'validates_email_format_of/version' module ValidatesEmailFormatOf def self.load_i18n_locales require 'i18n' I18n.load_path += Dir.glob(File.expand_path(File.join(File.dirname(__FILE__), '..', 'config', 'locales', '*.yml'))) end require 'resolv' - LocalPartSpecialChars = /[\!\#\$\%\&\'\*\-\/\=\?\+\^\_\`\{\|\}\~]/ + LocalPartSpecialChars = /[\!\#\$\%\&\'\*\-\/\=\?\+\^\_\`\{\|\}\~]/.freeze + + # From https://datatracker.ietf.org/doc/html/rfc1035#section-2.3.1 + # + # > The labels must follow the rules for ARPANET host names. They must + # > start with a letter, end with a letter or digit, and have as interior + # > characters only letters, digits, and hyphen. There are also some + # > restrictions on the length. Labels must be 63 characters or less. + # + # <label> | <subdomain> "." <label> + # <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ] + # <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str> + # <let-dig-hyp> ::= <let-dig> | "-" + # <let-dig> ::= <letter> | <digit> + DomainPartLabel = /\A[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9]?\Z/.freeze + + IPAddressPart = /\A[0-9]+\Z/.freeze + + # From https://tools.ietf.org/id/draft-liman-tld-names-00.html#rfc.section.2 + # + # > A TLD label MUST be at least two characters long and MAY be as long as 63 characters - + # > not counting any leading or trailing periods (.). It MUST consist of only ASCII characters + # > from the groups "letters" (A-Z), "digits" (0-9) and "hyphen" (-), and it MUST start with an + # > ASCII "letter", and it MUST NOT end with a "hyphen". Upper and lower case MAY be mixed at random, + # > since DNS lookups are case-insensitive. + # + # tldlabel = ALPHA *61(ldh) ld + # ldh = ld / "-" + # ld = ALPHA / DIGIT + # ALPHA = %x41-5A / %x61-7A ; A-Z / a-z + # DIGIT = %x30-39 ; 0-9 + DomainPartTLD = /\A[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9]\Z/.freeze def self.validate_email_domain(email, check_mx_timeout: 3) domain = email.to_s.downcase.match(/\@(.+)/)[1] Resolv::DNS.open do |dns| dns.timeouts = check_mx_timeout @mx = dns.getresources(domain, Resolv::DNS::Resource::IN::MX) + dns.getresources(domain, Resolv::DNS::Resource::IN::A) end @mx.size > 0 ? true : false end DEFAULT_MESSAGE = "does not appear to be valid" DEFAULT_MX_MESSAGE = "is not routable" ERROR_MESSAGE_I18N_KEY = :invalid_email_address ERROR_MX_MESSAGE_I18N_KEY = :email_address_not_routable def self.default_message defined?(I18n) ? I18n.t(ERROR_MESSAGE_I18N_KEY, :scope => [:activemodel, :errors, :messages], :default => DEFAULT_MESSAGE) : DEFAULT_MESSAGE end # Validates whether the specified value is a valid email address. Returns nil if the value is valid, otherwise returns an array # containing one or more validation error messages. # # Configuration options: # * <tt>message</tt> - A custom error message (default is: "does not appear to be valid") # * <tt>check_mx</tt> - Check for MX records (default is false) # * <tt>check_mx_timeout</tt> - Timeout in seconds for checking MX records before a `ResolvTimeout` is raised (default is 3) # * <tt>mx_message</tt> - A custom error message when an MX record validation fails (default is: "is not routable.") # * <tt>with</tt> The regex to use for validating the format of the email address (deprecated) # * <tt>local_length</tt> Maximum number of characters allowed in the local part (default is 64) # * <tt>domain_length</tt> Maximum number of characters allowed in the domain part (default is 255) # * <tt>generate_message</tt> Return the I18n key of the error message instead of the error message itself (default is false) def self.validate_email_format(email, options={}) default_options = { :message => options[:generate_message] ? ERROR_MESSAGE_I18N_KEY : default_message, :check_mx => false, :check_mx_timeout => 3, :mx_message => options[:generate_message] ? ERROR_MX_MESSAGE_I18N_KEY : (defined?(I18n) ? I18n.t(ERROR_MX_MESSAGE_I18N_KEY, :scope => [:activemodel, :errors, :messages], :default => DEFAULT_MX_MESSAGE) : DEFAULT_MX_MESSAGE), :domain_length => 255, :local_length => 64, :generate_message => false } opts = options.merge(default_options) {|key, old, new| old} # merge the default options into the specified options, retaining all specified options begin domain, local = email.reverse.split('@', 2) rescue return [ opts[:message] ] end # need local and domain parts return [ opts[:message] ] unless local and not local.empty? and domain and not domain.empty? # check lengths return [ opts[:message] ] unless domain.length <= opts[:domain_length] and local.length <= opts[:local_length] local.reverse! domain.reverse! if opts.has_key?(:with) # holdover from versions <= 1.4.7 return [ opts[:message] ] unless email =~ opts[:with] else return [ opts[:message] ] unless self.validate_local_part_syntax(local) and self.validate_domain_part_syntax(domain) end if opts[:check_mx] and !self.validate_email_domain(email, check_mx_timeout: opts[:check_mx_timeout]) return [ opts[:mx_message] ] end return nil # represents no validation errors end def self.validate_local_part_syntax(local) in_quoted_pair = false in_quoted_string = false (0..local.length-1).each do |i| ord = local[i].ord # accept anything if it's got a backslash before it if in_quoted_pair in_quoted_pair = false next end # backslash signifies the start of a quoted pair if ord == 92 and i < local.length - 1 return false if not in_quoted_string # must be in quoted string per http://www.rfc-editor.org/errata_search.php?rfc=3696 in_quoted_pair = true next end # double quote delimits quoted strings if ord == 34 in_quoted_string = !in_quoted_string next end next if local[i,1] =~ /[a-z0-9]/i next if local[i,1] =~ LocalPartSpecialChars # period must be followed by something if ord == 46 return false if i == 0 or i == local.length - 1 # can't be first or last char next unless local[i+1].ord == 46 # can't be followed by a period end return false end return false if in_quoted_string # unbalanced quotes return true end def self.validate_domain_part_syntax(domain) parts = domain.downcase.split('.', -1) return false if parts.length <= 1 # Only one domain part - # Empty parts (double period) or invalid chars - return false if parts.any? { - |part| - part.nil? or - part.empty? or - not part =~ /\A[[:alnum:]\-]+\Z/ or - part[0,1] == '-' or part[-1,1] == '-' # hyphen at beginning or end of part - } - # ipv4 - return true if parts.length == 4 and parts.all? { |part| part =~ /\A[0-9]+\Z/ and part.to_i.between?(0, 255) } - - return false if parts[-1].length < 2 or not parts[-1] =~ /[a-z\-]/ # TLD is too short or does not contain a char or hyphen + return true if parts.length == 4 && parts.all? { |part| part =~ IPAddressPart && part.to_i.between?(0, 255) } + + # From https://datatracker.ietf.org/doc/html/rfc3696#section-2 this is the recommended, pragmatic way to validate a domain name: + # + # > It is likely that the better strategy has now become to make the "at least one period" test, + # > to verify LDH conformance (including verification that the apparent TLD name is not all-numeric), + # > and then to use the DNS to determine domain name validity, rather than trying to maintain + # > a local list of valid TLD names. + # + # We do a little bit more but not too much and validate the tokens but do not check against a list of valid TLDs. + parts.each do |part| + return false if part.nil? || part.empty? + return false if part.length > 63 + return false unless part =~ DomainPartLabel + end + return false unless parts[-1] =~ DomainPartTLD return true end end require 'validates_email_format_of/active_model' if defined?(::ActiveModel) && !(ActiveModel::VERSION::MAJOR < 2 || (2 == ActiveModel::VERSION::MAJOR && ActiveModel::VERSION::MINOR < 1)) require 'validates_email_format_of/railtie' if defined?(::Rails::Railtie) diff --git a/spec/validates_email_format_of_spec.rb b/spec/validates_email_format_of_spec.rb index d660a9c..d07d487 100644 --- a/spec/validates_email_format_of_spec.rb +++ b/spec/validates_email_format_of_spec.rb @@ -1,328 +1,328 @@ # -*- encoding : utf-8 -*- require "#{File.expand_path(File.dirname(__FILE__))}/spec_helper" require "validates_email_format_of" RSpec.configure do |config| config.before(:suite) do ValidatesEmailFormatOf.load_i18n_locales I18n.enforce_available_locales = false end end describe ValidatesEmailFormatOf do subject do |example| if defined?(ActiveModel) user = Class.new do def initialize(email) @email = email.freeze end attr_reader :email include ActiveModel::Validations validates_email_format_of :email, example.example_group_instance.options end example.example_group_instance.class::User = user user.new(example.example_group_instance.email).tap(&:valid?).errors.full_messages else ValidatesEmailFormatOf::validate_email_format(email.freeze, options) end end let(:options) { {} } let(:email) { |example| example.example_group.description } shared_examples_for :all_specs do [ 'valid@example.com', 'Valid@test.example.com', 'valid+valid123@test.example.com', 'valid_valid123@test.example.com', 'valid-valid+123@test.example.co.uk', 'valid-valid+1.23@test.example.com.au', 'valid@example.co.uk', 'v@example.com', 'valid@example.ca', 'valid_@example.com', 'valid123.456@example.org', 'valid123.456@example.travel', 'valid123.456@example.museum', 'valid@example.mobi', 'valid@example.info', 'valid-@example.com', 'fake@p-t.k12.ok.us', # allow single character domain parts 'valid@mail.x.example.com', 'valid@x.com', 'valid@example.w-dash.sch.uk', # from RFC 3696, page 6 'customer/department=shipping@example.com', '$A12345@example.com', '!def!xyz%abc@example.com', '_somename@example.com', # apostrophes "test'test@example.com", # international domain names 'test@xn--bcher-kva.ch', 'test@example.xn--0zwm56d', 'test@192.192.192.1', # Allow quoted characters. Valid according to http://www.rfc-editor.org/errata_search.php?rfc=3696 '"Abc\@def"@example.com', '"Fred\ Bloggs"@example.com', '"Joe.\\Blow"@example.com', # Balanced quoted characters %!"example\\\\\\""@example.com!, %!"example\\\\"@example.com! ].each do |address| describe address do it { should_not have_errors_on_email } end end [ 'no_at_symbol', 'invalid@example-com', # period can not start local part '.invalid@example.com', # period can not end local part 'invalid.@example.com', # period can not appear twice consecutively in local part 'invali..d@example.com', # should not allow underscores in domain names 'invalid@ex_mple.com', 'invalid@e..example.com', 'invalid@p-t..example.com', 'invalid@example.com.', 'invalid@example.com_', 'invalid@example.com-', 'invalid-example.com', 'invalid@example.b#r.com', 'invalid@example.c', 'invali d@example.com', # TLD can not be only numeric 'invalid@example.123', # unclosed quote "\"a-17180061943-10618354-1993365053@example.com", # too many special chars used to cause the regexp to hang "-+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++@foo", 'invalidexample.com', # should not allow special chars after a period in the domain 'local@sub.)domain.com', 'local@sub.#domain.com', # one at a time "foo@example.com\nexample@gmail.com", 'invalid@example.', "\"foo\\\\\"\"@bar.com", "foo@mail.com\r\nfoo@mail.com", '@example.com', 'foo@', 'foo', 'Iñtërnâtiônàlizætiøn@hasnt.happened.to.email', # Escaped characters with quotes. From http://tools.ietf.org/html/rfc3696, page 5. Corrected in http://www.rfc-editor.org/errata_search.php?rfc=3696 'Fred\ Bloggs_@example.com', 'Abc\@def+@example.com', 'Joe.\\Blow@example.com', # Unbalanced quoted characters %!"example\\\\""example.com!, "\nnewline@example.com", " spacesbefore@example.com", "spacesafter@example.com " ].each do |address| describe address do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe do shared_examples_for :local_length_limit do |limit| describe "#{'a' * limit}@example.com" do it { should_not have_errors_on_email } end describe "#{'a' * (limit + 1)}@example.com" do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "when using default" do it_should_behave_like :local_length_limit, 64 end describe "when overriding defaults" do let(:options) { { :local_length => 20 } } it_should_behave_like :local_length_limit, 20 end end describe do shared_examples_for :domain_length_limit do |limit| - describe "user@#{'a' * (limit - 4)}.com" do + describe "user@#{'a.' * (limit / 2 - 3)}com" do it { should_not have_errors_on_email } end - describe "user@#{'a' * (limit - 3)}.com" do + describe "user@#{'a.' * (limit / 2 + 1)}com" do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "when using default" do it_should_behave_like :domain_length_limit, 255 end describe "when overriding defaults" do let(:options) { { :domain_length => 100 } } it_should_behave_like :domain_length_limit, 100 end end describe "custom error messages" do describe 'invalid@example.' do let(:options) { { :message => "just because I don't like you" } } it { should have_errors_on_email.because("just because I don't like you") } end end describe "mx record" do domain = "example.com" email = "valid@#{domain}" check_mx_timeout = 3 describe "when testing" do let(:dns) { double(Resolv::DNS) } let(:mx_record) { [double] } let(:a_record) { [double] } before(:each) do allow(Resolv::DNS).to receive(:open).and_yield(dns) expect(dns).to receive(:"timeouts=").with(3).once allow(dns).to receive(:getresources).with(domain, Resolv::DNS::Resource::IN::MX).once.and_return(mx_record) allow(dns).to receive(:getresources).with(domain, Resolv::DNS::Resource::IN::A).once.and_return(a_record) end let(:options) { { :check_mx => true } } describe "and only an mx record is found" do let(:a_record) { [] } describe email do it { should_not have_errors_on_email } end end describe "and only an a record is found" do let(:mx_record) { [] } describe email do it { should_not have_errors_on_email } end end describe "and both an mx record and an a record are found" do describe email do it { should_not have_errors_on_email } end end describe "and neither an mx record nor an a record is found" do let(:a_record) { [] } let(:mx_record) { [] } describe email do it { should have_errors_on_email.because("is not routable") } end describe "with a custom error message" do let(:options) { { :check_mx => true, :mx_message => "There ain't no such domain!" } } describe email do it { should have_errors_on_email.because("There ain't no such domain!") } end end describe "i18n" do before(:each) do allow(I18n.config).to receive(:locale).and_return(locale) end describe "present locale" do let(:locale) { :pl } describe email do it { should have_errors_on_email.because("jest nieosiągalny") } end end unless defined?(ActiveModel) describe email do let(:locale) { :ir } describe email do it { should have_errors_on_email.because("is not routable") } end end end end unless defined?(ActiveModel) describe "without i18n" do before(:each) { hide_const("I18n") } describe email do it { should have_errors_on_email.because("is not routable") } end end end end end describe "when not testing" do before(:each) { allow(Resolv::DNS).to receive(:open).never } describe "by default" do describe email do it { should_not have_errors_on_email } end end describe "explicitly" do describe email do let(:options) { { :check_mx => false } } it { should_not have_errors_on_email } end end end describe "without mocks" do describe email do let(:options) { { :check_mx => true } } it { should_not have_errors_on_email } end end end describe "custom regex" do let(:options) { { :with => /[0-9]+\@[0-9]+/ } } describe '012345@789' do it { should_not have_errors_on_email } end describe 'valid@example.com' do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "i18n" do before(:each) do allow(I18n.config).to receive(:locale).and_return(locale) end describe "present locale" do let(:locale) { :pl } describe "invalid@exmaple." do it { should have_errors_on_email.because("nieprawidłowy adres e-mail") } end end unless defined?(ActiveModel) describe "missing locale" do let(:locale) { :ir } describe "invalid@exmaple." do it { should have_errors_on_email.because("does not appear to be valid") } end end end end unless defined?(ActiveModel) describe "without i18n" do before(:each) { hide_const("I18n") } describe "invalid@exmaple." do it { should have_errors_on_email.because("does not appear to be valid") } end end end end it_should_behave_like :all_specs if defined?(ActiveModel) describe "shorthand ActiveModel validation" do subject do |example| user = Class.new do def initialize(email) @email = email.freeze end attr_reader :email include ActiveModel::Validations validates :email, :email_format => example.example_group_instance.options end example.example_group_instance.class::User = user user.new(example.example_group_instance.email).tap(&:valid?).errors.full_messages end it_should_behave_like :all_specs end end end
validates-email-format-of/validates_email_format_of
20b6b1cf814602f7c85459d09490859ee2fb158a
Allow setting check_mx_timeout and reduce the default timeout to 3 seconds
diff --git a/README.rdoc b/README.rdoc index 5476fc8..1f05e9d 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,98 +1,100 @@ = validates_email_format_of Gem and Rails Plugin Validate e-mail addresses against RFC 2822 and RFC 3696. == Installation Installing as a gem: gem install validates_email_format_of Or in your Gemfile: gem 'validates_email_format_of' == Usage # Rails # I18n locales are loaded automatically. class Person < ActiveRecord::Base validates_email_format_of :email, :message => 'is not looking good' # OR validates :email, :email_format => { :message => 'is not looking good' } end # Now you can test your model using RSpec: require "validates_email_format_of/rspec_matcher" describe Person do it { should validate_email_format_of(:email).with_message('is not looking good') } end # If you're not using Rails (which really means, if you're not using ActiveModel::Validations) ValidatesEmailFormatOf::load_i18n_locales # Optional, if you want error messages to be in your language I18n.locale = :pl # If, for example, you want Polish error messages. ValidatesEmailFormatOf::validate_email_format("example@mydomain.com") # => nil ValidatesEmailFormatOf::validate_email_format("invalid_because_there_is_no_at_symbol") # => ["does not appear to be a valid e-mail address"] === Options :message String. A custom error message when the email format is invalid (default is: "does not appear to be a valid e-mail address") :check_mx Boolean. Check domain for a valid MX record (default is false) + :check_mx_timeout + Integer. Timeout in seconds for checking MX records before a `ResolvTimeout` is raised (default is 3). :mx_message String. A custom error message when the domain does not match a valid MX record (default is: "is not routable"). Ignored unless :check_mx option is true. :local_length Maximum number of characters allowed in the local part (everything before the '@') (default is 64) :domain_length Maximum number of characters allowed in the domain part (everything after the '@') (default is 255) :generate_message Boolean. Return the I18n key of the error message instead of the error message itself (default is false) :with Specify a custom Regex as the valid email format. :on, :if, :unless, :allow_nil, :allow_blank, :strict Standard ActiveModel validation options. These work in the ActiveModel/ActiveRecord/Rails syntax only. See http://api.rubyonrails.org/classes/ActiveModel/Validations/ClassMethods.html#method-i-validates for details. == Testing To execute the unit tests against [all the Rails versions we support run](gemfiles/) <tt>bundle exec appraisal rspec</tt> or run against an individual version with <tt>bundle exec appraisal rails-6.0 rspec</tt>. Tested in Ruby 1.8.7, 1.9.2, 1.9.3, 2.0.0, 2.1.2, JRuby and REE 1.8.7. == Contributing If you think we're letting some rules about valid email formats slip through the cracks, don't just update the Regex. Instead, add a failing test, and demonstrate that the described email address should be treated differently. A link to an appropriate RFC is the best way to do this. Then change the gem code to make the test pass. describe "i_think_this_is_not_a_v@lid_email_addre.ss" do # According to http://..., this email address IS NOT valid. it { should have_errors_on_email.because("does not appear to be valid") } end describe "i_think_this_is_a_v@lid_email_addre.ss" do # According to http://..., this email address IS valid. it { should_not have_errors_on_email } end Yes, our Rspec syntax is that simple! == Homepage * https://github.com/validates-email-format-of/validates_email_format_of == Credits Written by Alex Dunae (dunae.ca), 2006-11. Many thanks to the plugin's recent contributors: https://github.com/alexdunae/validates_email_format_of/contributors Thanks to Francis Hwang (http://fhwang.net/) at Diversion Media for creating the 1.1 update. Thanks to Travis Sinnott for creating the 1.3 update. Thanks to Denis Ahearn at Riverock Technologies (http://www.riverocktech.com/) for creating the 1.4 update. Thanks to George Anderson (http://github.com/george) and 'history' (http://github.com/history) for creating the 1.4.1 update. Thanks to Isaac Betesh (https://github.com/betesh) for converting tests to Rspec and refactoring for version 1.6.0. diff --git a/lib/validates_email_format_of.rb b/lib/validates_email_format_of.rb index 92e5c4b..a43eec4 100644 --- a/lib/validates_email_format_of.rb +++ b/lib/validates_email_format_of.rb @@ -1,148 +1,151 @@ # encoding: utf-8 require 'validates_email_format_of/version' module ValidatesEmailFormatOf def self.load_i18n_locales require 'i18n' I18n.load_path += Dir.glob(File.expand_path(File.join(File.dirname(__FILE__), '..', 'config', 'locales', '*.yml'))) end require 'resolv' LocalPartSpecialChars = /[\!\#\$\%\&\'\*\-\/\=\?\+\^\_\`\{\|\}\~]/ - def self.validate_email_domain(email) + def self.validate_email_domain(email, check_mx_timeout: 3) domain = email.to_s.downcase.match(/\@(.+)/)[1] Resolv::DNS.open do |dns| + dns.timeouts = check_mx_timeout @mx = dns.getresources(domain, Resolv::DNS::Resource::IN::MX) + dns.getresources(domain, Resolv::DNS::Resource::IN::A) end @mx.size > 0 ? true : false end DEFAULT_MESSAGE = "does not appear to be valid" DEFAULT_MX_MESSAGE = "is not routable" ERROR_MESSAGE_I18N_KEY = :invalid_email_address ERROR_MX_MESSAGE_I18N_KEY = :email_address_not_routable def self.default_message defined?(I18n) ? I18n.t(ERROR_MESSAGE_I18N_KEY, :scope => [:activemodel, :errors, :messages], :default => DEFAULT_MESSAGE) : DEFAULT_MESSAGE end # Validates whether the specified value is a valid email address. Returns nil if the value is valid, otherwise returns an array # containing one or more validation error messages. # # Configuration options: # * <tt>message</tt> - A custom error message (default is: "does not appear to be valid") # * <tt>check_mx</tt> - Check for MX records (default is false) + # * <tt>check_mx_timeout</tt> - Timeout in seconds for checking MX records before a `ResolvTimeout` is raised (default is 3) # * <tt>mx_message</tt> - A custom error message when an MX record validation fails (default is: "is not routable.") # * <tt>with</tt> The regex to use for validating the format of the email address (deprecated) # * <tt>local_length</tt> Maximum number of characters allowed in the local part (default is 64) # * <tt>domain_length</tt> Maximum number of characters allowed in the domain part (default is 255) # * <tt>generate_message</tt> Return the I18n key of the error message instead of the error message itself (default is false) def self.validate_email_format(email, options={}) default_options = { :message => options[:generate_message] ? ERROR_MESSAGE_I18N_KEY : default_message, :check_mx => false, + :check_mx_timeout => 3, :mx_message => options[:generate_message] ? ERROR_MX_MESSAGE_I18N_KEY : (defined?(I18n) ? I18n.t(ERROR_MX_MESSAGE_I18N_KEY, :scope => [:activemodel, :errors, :messages], :default => DEFAULT_MX_MESSAGE) : DEFAULT_MX_MESSAGE), :domain_length => 255, :local_length => 64, :generate_message => false } opts = options.merge(default_options) {|key, old, new| old} # merge the default options into the specified options, retaining all specified options begin domain, local = email.reverse.split('@', 2) rescue return [ opts[:message] ] end # need local and domain parts return [ opts[:message] ] unless local and not local.empty? and domain and not domain.empty? # check lengths return [ opts[:message] ] unless domain.length <= opts[:domain_length] and local.length <= opts[:local_length] local.reverse! domain.reverse! if opts.has_key?(:with) # holdover from versions <= 1.4.7 return [ opts[:message] ] unless email =~ opts[:with] else return [ opts[:message] ] unless self.validate_local_part_syntax(local) and self.validate_domain_part_syntax(domain) end - if opts[:check_mx] and !self.validate_email_domain(email) + if opts[:check_mx] and !self.validate_email_domain(email, check_mx_timeout: opts[:check_mx_timeout]) return [ opts[:mx_message] ] end return nil # represents no validation errors end def self.validate_local_part_syntax(local) in_quoted_pair = false in_quoted_string = false (0..local.length-1).each do |i| ord = local[i].ord # accept anything if it's got a backslash before it if in_quoted_pair in_quoted_pair = false next end # backslash signifies the start of a quoted pair if ord == 92 and i < local.length - 1 return false if not in_quoted_string # must be in quoted string per http://www.rfc-editor.org/errata_search.php?rfc=3696 in_quoted_pair = true next end # double quote delimits quoted strings if ord == 34 in_quoted_string = !in_quoted_string next end next if local[i,1] =~ /[a-z0-9]/i next if local[i,1] =~ LocalPartSpecialChars # period must be followed by something if ord == 46 return false if i == 0 or i == local.length - 1 # can't be first or last char next unless local[i+1].ord == 46 # can't be followed by a period end return false end return false if in_quoted_string # unbalanced quotes return true end def self.validate_domain_part_syntax(domain) parts = domain.downcase.split('.', -1) return false if parts.length <= 1 # Only one domain part # Empty parts (double period) or invalid chars return false if parts.any? { |part| part.nil? or part.empty? or not part =~ /\A[[:alnum:]\-]+\Z/ or part[0,1] == '-' or part[-1,1] == '-' # hyphen at beginning or end of part } # ipv4 return true if parts.length == 4 and parts.all? { |part| part =~ /\A[0-9]+\Z/ and part.to_i.between?(0, 255) } return false if parts[-1].length < 2 or not parts[-1] =~ /[a-z\-]/ # TLD is too short or does not contain a char or hyphen return true end end require 'validates_email_format_of/active_model' if defined?(::ActiveModel) && !(ActiveModel::VERSION::MAJOR < 2 || (2 == ActiveModel::VERSION::MAJOR && ActiveModel::VERSION::MINOR < 1)) require 'validates_email_format_of/railtie' if defined?(::Rails::Railtie) diff --git a/spec/validates_email_format_of_spec.rb b/spec/validates_email_format_of_spec.rb index 667586e..d660a9c 100644 --- a/spec/validates_email_format_of_spec.rb +++ b/spec/validates_email_format_of_spec.rb @@ -1,326 +1,328 @@ # -*- encoding : utf-8 -*- require "#{File.expand_path(File.dirname(__FILE__))}/spec_helper" require "validates_email_format_of" RSpec.configure do |config| config.before(:suite) do ValidatesEmailFormatOf.load_i18n_locales I18n.enforce_available_locales = false end end describe ValidatesEmailFormatOf do subject do |example| if defined?(ActiveModel) user = Class.new do def initialize(email) @email = email.freeze end attr_reader :email include ActiveModel::Validations validates_email_format_of :email, example.example_group_instance.options end example.example_group_instance.class::User = user user.new(example.example_group_instance.email).tap(&:valid?).errors.full_messages else ValidatesEmailFormatOf::validate_email_format(email.freeze, options) end end let(:options) { {} } let(:email) { |example| example.example_group.description } shared_examples_for :all_specs do [ 'valid@example.com', 'Valid@test.example.com', 'valid+valid123@test.example.com', 'valid_valid123@test.example.com', 'valid-valid+123@test.example.co.uk', 'valid-valid+1.23@test.example.com.au', 'valid@example.co.uk', 'v@example.com', 'valid@example.ca', 'valid_@example.com', 'valid123.456@example.org', 'valid123.456@example.travel', 'valid123.456@example.museum', 'valid@example.mobi', 'valid@example.info', 'valid-@example.com', 'fake@p-t.k12.ok.us', # allow single character domain parts 'valid@mail.x.example.com', 'valid@x.com', 'valid@example.w-dash.sch.uk', # from RFC 3696, page 6 'customer/department=shipping@example.com', '$A12345@example.com', '!def!xyz%abc@example.com', '_somename@example.com', # apostrophes "test'test@example.com", # international domain names 'test@xn--bcher-kva.ch', 'test@example.xn--0zwm56d', 'test@192.192.192.1', # Allow quoted characters. Valid according to http://www.rfc-editor.org/errata_search.php?rfc=3696 '"Abc\@def"@example.com', '"Fred\ Bloggs"@example.com', '"Joe.\\Blow"@example.com', # Balanced quoted characters %!"example\\\\\\""@example.com!, %!"example\\\\"@example.com! ].each do |address| describe address do it { should_not have_errors_on_email } end end [ 'no_at_symbol', 'invalid@example-com', # period can not start local part '.invalid@example.com', # period can not end local part 'invalid.@example.com', # period can not appear twice consecutively in local part 'invali..d@example.com', # should not allow underscores in domain names 'invalid@ex_mple.com', 'invalid@e..example.com', 'invalid@p-t..example.com', 'invalid@example.com.', 'invalid@example.com_', 'invalid@example.com-', 'invalid-example.com', 'invalid@example.b#r.com', 'invalid@example.c', 'invali d@example.com', # TLD can not be only numeric 'invalid@example.123', # unclosed quote "\"a-17180061943-10618354-1993365053@example.com", # too many special chars used to cause the regexp to hang "-+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++@foo", 'invalidexample.com', # should not allow special chars after a period in the domain 'local@sub.)domain.com', 'local@sub.#domain.com', # one at a time "foo@example.com\nexample@gmail.com", 'invalid@example.', "\"foo\\\\\"\"@bar.com", "foo@mail.com\r\nfoo@mail.com", '@example.com', 'foo@', 'foo', 'Iñtërnâtiônàlizætiøn@hasnt.happened.to.email', # Escaped characters with quotes. From http://tools.ietf.org/html/rfc3696, page 5. Corrected in http://www.rfc-editor.org/errata_search.php?rfc=3696 'Fred\ Bloggs_@example.com', 'Abc\@def+@example.com', 'Joe.\\Blow@example.com', # Unbalanced quoted characters %!"example\\\\""example.com!, "\nnewline@example.com", " spacesbefore@example.com", "spacesafter@example.com " ].each do |address| describe address do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe do shared_examples_for :local_length_limit do |limit| describe "#{'a' * limit}@example.com" do it { should_not have_errors_on_email } end describe "#{'a' * (limit + 1)}@example.com" do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "when using default" do it_should_behave_like :local_length_limit, 64 end describe "when overriding defaults" do let(:options) { { :local_length => 20 } } it_should_behave_like :local_length_limit, 20 end end describe do shared_examples_for :domain_length_limit do |limit| describe "user@#{'a' * (limit - 4)}.com" do it { should_not have_errors_on_email } end describe "user@#{'a' * (limit - 3)}.com" do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "when using default" do it_should_behave_like :domain_length_limit, 255 end describe "when overriding defaults" do let(:options) { { :domain_length => 100 } } it_should_behave_like :domain_length_limit, 100 end end describe "custom error messages" do describe 'invalid@example.' do let(:options) { { :message => "just because I don't like you" } } it { should have_errors_on_email.because("just because I don't like you") } end end describe "mx record" do domain = "example.com" email = "valid@#{domain}" + check_mx_timeout = 3 describe "when testing" do let(:dns) { double(Resolv::DNS) } let(:mx_record) { [double] } let(:a_record) { [double] } before(:each) do allow(Resolv::DNS).to receive(:open).and_yield(dns) + expect(dns).to receive(:"timeouts=").with(3).once allow(dns).to receive(:getresources).with(domain, Resolv::DNS::Resource::IN::MX).once.and_return(mx_record) allow(dns).to receive(:getresources).with(domain, Resolv::DNS::Resource::IN::A).once.and_return(a_record) end let(:options) { { :check_mx => true } } describe "and only an mx record is found" do let(:a_record) { [] } describe email do it { should_not have_errors_on_email } end end describe "and only an a record is found" do let(:mx_record) { [] } describe email do it { should_not have_errors_on_email } end end describe "and both an mx record and an a record are found" do describe email do it { should_not have_errors_on_email } end end describe "and neither an mx record nor an a record is found" do let(:a_record) { [] } let(:mx_record) { [] } describe email do it { should have_errors_on_email.because("is not routable") } end describe "with a custom error message" do let(:options) { { :check_mx => true, :mx_message => "There ain't no such domain!" } } describe email do it { should have_errors_on_email.because("There ain't no such domain!") } end end describe "i18n" do before(:each) do allow(I18n.config).to receive(:locale).and_return(locale) end describe "present locale" do let(:locale) { :pl } describe email do it { should have_errors_on_email.because("jest nieosiągalny") } end end unless defined?(ActiveModel) describe email do let(:locale) { :ir } describe email do it { should have_errors_on_email.because("is not routable") } end end end end unless defined?(ActiveModel) describe "without i18n" do before(:each) { hide_const("I18n") } describe email do it { should have_errors_on_email.because("is not routable") } end end end end end describe "when not testing" do before(:each) { allow(Resolv::DNS).to receive(:open).never } describe "by default" do describe email do it { should_not have_errors_on_email } end end describe "explicitly" do describe email do let(:options) { { :check_mx => false } } it { should_not have_errors_on_email } end end end describe "without mocks" do describe email do let(:options) { { :check_mx => true } } it { should_not have_errors_on_email } end end end describe "custom regex" do let(:options) { { :with => /[0-9]+\@[0-9]+/ } } describe '012345@789' do it { should_not have_errors_on_email } end describe 'valid@example.com' do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "i18n" do before(:each) do allow(I18n.config).to receive(:locale).and_return(locale) end describe "present locale" do let(:locale) { :pl } describe "invalid@exmaple." do it { should have_errors_on_email.because("nieprawidłowy adres e-mail") } end end unless defined?(ActiveModel) describe "missing locale" do let(:locale) { :ir } describe "invalid@exmaple." do it { should have_errors_on_email.because("does not appear to be valid") } end end end end unless defined?(ActiveModel) describe "without i18n" do before(:each) { hide_const("I18n") } describe "invalid@exmaple." do it { should have_errors_on_email.because("does not appear to be valid") } end end end end it_should_behave_like :all_specs if defined?(ActiveModel) describe "shorthand ActiveModel validation" do subject do |example| user = Class.new do def initialize(email) @email = email.freeze end attr_reader :email include ActiveModel::Validations validates :email, :email_format => example.example_group_instance.options end example.example_group_instance.class::User = user user.new(example.example_group_instance.email).tap(&:valid?).errors.full_messages end it_should_behave_like :all_specs end end end
validates-email-format-of/validates_email_format_of
aee22f58141952a2704d49852a3e1698be52fb98
Do not strip spaces before validating
diff --git a/lib/validates_email_format_of.rb b/lib/validates_email_format_of.rb index 6262b8f..92e5c4b 100644 --- a/lib/validates_email_format_of.rb +++ b/lib/validates_email_format_of.rb @@ -1,150 +1,148 @@ # encoding: utf-8 require 'validates_email_format_of/version' module ValidatesEmailFormatOf def self.load_i18n_locales require 'i18n' I18n.load_path += Dir.glob(File.expand_path(File.join(File.dirname(__FILE__), '..', 'config', 'locales', '*.yml'))) end require 'resolv' LocalPartSpecialChars = /[\!\#\$\%\&\'\*\-\/\=\?\+\^\_\`\{\|\}\~]/ def self.validate_email_domain(email) domain = email.to_s.downcase.match(/\@(.+)/)[1] Resolv::DNS.open do |dns| @mx = dns.getresources(domain, Resolv::DNS::Resource::IN::MX) + dns.getresources(domain, Resolv::DNS::Resource::IN::A) end @mx.size > 0 ? true : false end DEFAULT_MESSAGE = "does not appear to be valid" DEFAULT_MX_MESSAGE = "is not routable" ERROR_MESSAGE_I18N_KEY = :invalid_email_address ERROR_MX_MESSAGE_I18N_KEY = :email_address_not_routable def self.default_message defined?(I18n) ? I18n.t(ERROR_MESSAGE_I18N_KEY, :scope => [:activemodel, :errors, :messages], :default => DEFAULT_MESSAGE) : DEFAULT_MESSAGE end # Validates whether the specified value is a valid email address. Returns nil if the value is valid, otherwise returns an array # containing one or more validation error messages. # # Configuration options: # * <tt>message</tt> - A custom error message (default is: "does not appear to be valid") # * <tt>check_mx</tt> - Check for MX records (default is false) # * <tt>mx_message</tt> - A custom error message when an MX record validation fails (default is: "is not routable.") # * <tt>with</tt> The regex to use for validating the format of the email address (deprecated) # * <tt>local_length</tt> Maximum number of characters allowed in the local part (default is 64) # * <tt>domain_length</tt> Maximum number of characters allowed in the domain part (default is 255) # * <tt>generate_message</tt> Return the I18n key of the error message instead of the error message itself (default is false) def self.validate_email_format(email, options={}) default_options = { :message => options[:generate_message] ? ERROR_MESSAGE_I18N_KEY : default_message, :check_mx => false, :mx_message => options[:generate_message] ? ERROR_MX_MESSAGE_I18N_KEY : (defined?(I18n) ? I18n.t(ERROR_MX_MESSAGE_I18N_KEY, :scope => [:activemodel, :errors, :messages], :default => DEFAULT_MX_MESSAGE) : DEFAULT_MX_MESSAGE), :domain_length => 255, :local_length => 64, :generate_message => false } opts = options.merge(default_options) {|key, old, new| old} # merge the default options into the specified options, retaining all specified options - email = email.strip if email - begin domain, local = email.reverse.split('@', 2) rescue return [ opts[:message] ] end # need local and domain parts return [ opts[:message] ] unless local and not local.empty? and domain and not domain.empty? # check lengths return [ opts[:message] ] unless domain.length <= opts[:domain_length] and local.length <= opts[:local_length] local.reverse! domain.reverse! if opts.has_key?(:with) # holdover from versions <= 1.4.7 return [ opts[:message] ] unless email =~ opts[:with] else return [ opts[:message] ] unless self.validate_local_part_syntax(local) and self.validate_domain_part_syntax(domain) end if opts[:check_mx] and !self.validate_email_domain(email) return [ opts[:mx_message] ] end return nil # represents no validation errors end def self.validate_local_part_syntax(local) in_quoted_pair = false in_quoted_string = false (0..local.length-1).each do |i| ord = local[i].ord # accept anything if it's got a backslash before it if in_quoted_pair in_quoted_pair = false next end # backslash signifies the start of a quoted pair if ord == 92 and i < local.length - 1 return false if not in_quoted_string # must be in quoted string per http://www.rfc-editor.org/errata_search.php?rfc=3696 in_quoted_pair = true next end # double quote delimits quoted strings if ord == 34 in_quoted_string = !in_quoted_string next end next if local[i,1] =~ /[a-z0-9]/i next if local[i,1] =~ LocalPartSpecialChars # period must be followed by something if ord == 46 return false if i == 0 or i == local.length - 1 # can't be first or last char next unless local[i+1].ord == 46 # can't be followed by a period end return false end return false if in_quoted_string # unbalanced quotes return true end def self.validate_domain_part_syntax(domain) parts = domain.downcase.split('.', -1) return false if parts.length <= 1 # Only one domain part # Empty parts (double period) or invalid chars return false if parts.any? { |part| part.nil? or part.empty? or not part =~ /\A[[:alnum:]\-]+\Z/ or part[0,1] == '-' or part[-1,1] == '-' # hyphen at beginning or end of part } # ipv4 return true if parts.length == 4 and parts.all? { |part| part =~ /\A[0-9]+\Z/ and part.to_i.between?(0, 255) } return false if parts[-1].length < 2 or not parts[-1] =~ /[a-z\-]/ # TLD is too short or does not contain a char or hyphen return true end end require 'validates_email_format_of/active_model' if defined?(::ActiveModel) && !(ActiveModel::VERSION::MAJOR < 2 || (2 == ActiveModel::VERSION::MAJOR && ActiveModel::VERSION::MINOR < 1)) require 'validates_email_format_of/railtie' if defined?(::Rails::Railtie) diff --git a/spec/validates_email_format_of_spec.rb b/spec/validates_email_format_of_spec.rb index 733c929..667586e 100644 --- a/spec/validates_email_format_of_spec.rb +++ b/spec/validates_email_format_of_spec.rb @@ -1,323 +1,326 @@ # -*- encoding : utf-8 -*- require "#{File.expand_path(File.dirname(__FILE__))}/spec_helper" require "validates_email_format_of" RSpec.configure do |config| config.before(:suite) do ValidatesEmailFormatOf.load_i18n_locales I18n.enforce_available_locales = false end end describe ValidatesEmailFormatOf do subject do |example| if defined?(ActiveModel) user = Class.new do def initialize(email) @email = email.freeze end attr_reader :email include ActiveModel::Validations validates_email_format_of :email, example.example_group_instance.options end example.example_group_instance.class::User = user user.new(example.example_group_instance.email).tap(&:valid?).errors.full_messages else ValidatesEmailFormatOf::validate_email_format(email.freeze, options) end end let(:options) { {} } let(:email) { |example| example.example_group.description } shared_examples_for :all_specs do [ 'valid@example.com', 'Valid@test.example.com', 'valid+valid123@test.example.com', 'valid_valid123@test.example.com', 'valid-valid+123@test.example.co.uk', 'valid-valid+1.23@test.example.com.au', 'valid@example.co.uk', 'v@example.com', 'valid@example.ca', 'valid_@example.com', 'valid123.456@example.org', 'valid123.456@example.travel', 'valid123.456@example.museum', 'valid@example.mobi', 'valid@example.info', 'valid-@example.com', 'fake@p-t.k12.ok.us', # allow single character domain parts 'valid@mail.x.example.com', 'valid@x.com', 'valid@example.w-dash.sch.uk', # from RFC 3696, page 6 'customer/department=shipping@example.com', '$A12345@example.com', '!def!xyz%abc@example.com', '_somename@example.com', # apostrophes "test'test@example.com", # international domain names 'test@xn--bcher-kva.ch', 'test@example.xn--0zwm56d', 'test@192.192.192.1', # Allow quoted characters. Valid according to http://www.rfc-editor.org/errata_search.php?rfc=3696 '"Abc\@def"@example.com', '"Fred\ Bloggs"@example.com', '"Joe.\\Blow"@example.com', # Balanced quoted characters %!"example\\\\\\""@example.com!, %!"example\\\\"@example.com! ].each do |address| describe address do it { should_not have_errors_on_email } end end [ 'no_at_symbol', 'invalid@example-com', # period can not start local part '.invalid@example.com', # period can not end local part 'invalid.@example.com', # period can not appear twice consecutively in local part 'invali..d@example.com', # should not allow underscores in domain names 'invalid@ex_mple.com', 'invalid@e..example.com', 'invalid@p-t..example.com', 'invalid@example.com.', 'invalid@example.com_', 'invalid@example.com-', 'invalid-example.com', 'invalid@example.b#r.com', 'invalid@example.c', 'invali d@example.com', # TLD can not be only numeric 'invalid@example.123', # unclosed quote "\"a-17180061943-10618354-1993365053@example.com", # too many special chars used to cause the regexp to hang "-+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++@foo", 'invalidexample.com', # should not allow special chars after a period in the domain 'local@sub.)domain.com', 'local@sub.#domain.com', # one at a time "foo@example.com\nexample@gmail.com", 'invalid@example.', "\"foo\\\\\"\"@bar.com", "foo@mail.com\r\nfoo@mail.com", '@example.com', 'foo@', 'foo', 'Iñtërnâtiônàlizætiøn@hasnt.happened.to.email', # Escaped characters with quotes. From http://tools.ietf.org/html/rfc3696, page 5. Corrected in http://www.rfc-editor.org/errata_search.php?rfc=3696 'Fred\ Bloggs_@example.com', 'Abc\@def+@example.com', 'Joe.\\Blow@example.com', # Unbalanced quoted characters - %!"example\\\\""example.com! + %!"example\\\\""example.com!, + "\nnewline@example.com", + " spacesbefore@example.com", + "spacesafter@example.com " ].each do |address| describe address do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe do shared_examples_for :local_length_limit do |limit| describe "#{'a' * limit}@example.com" do it { should_not have_errors_on_email } end describe "#{'a' * (limit + 1)}@example.com" do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "when using default" do it_should_behave_like :local_length_limit, 64 end describe "when overriding defaults" do let(:options) { { :local_length => 20 } } it_should_behave_like :local_length_limit, 20 end end describe do shared_examples_for :domain_length_limit do |limit| describe "user@#{'a' * (limit - 4)}.com" do it { should_not have_errors_on_email } end describe "user@#{'a' * (limit - 3)}.com" do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "when using default" do it_should_behave_like :domain_length_limit, 255 end describe "when overriding defaults" do let(:options) { { :domain_length => 100 } } it_should_behave_like :domain_length_limit, 100 end end describe "custom error messages" do describe 'invalid@example.' do let(:options) { { :message => "just because I don't like you" } } it { should have_errors_on_email.because("just because I don't like you") } end end describe "mx record" do domain = "example.com" email = "valid@#{domain}" describe "when testing" do let(:dns) { double(Resolv::DNS) } let(:mx_record) { [double] } let(:a_record) { [double] } before(:each) do allow(Resolv::DNS).to receive(:open).and_yield(dns) allow(dns).to receive(:getresources).with(domain, Resolv::DNS::Resource::IN::MX).once.and_return(mx_record) allow(dns).to receive(:getresources).with(domain, Resolv::DNS::Resource::IN::A).once.and_return(a_record) end let(:options) { { :check_mx => true } } describe "and only an mx record is found" do let(:a_record) { [] } describe email do it { should_not have_errors_on_email } end end describe "and only an a record is found" do let(:mx_record) { [] } describe email do it { should_not have_errors_on_email } end end describe "and both an mx record and an a record are found" do describe email do it { should_not have_errors_on_email } end end describe "and neither an mx record nor an a record is found" do let(:a_record) { [] } let(:mx_record) { [] } describe email do it { should have_errors_on_email.because("is not routable") } end describe "with a custom error message" do let(:options) { { :check_mx => true, :mx_message => "There ain't no such domain!" } } describe email do it { should have_errors_on_email.because("There ain't no such domain!") } end end describe "i18n" do before(:each) do allow(I18n.config).to receive(:locale).and_return(locale) end describe "present locale" do let(:locale) { :pl } describe email do it { should have_errors_on_email.because("jest nieosiągalny") } end end unless defined?(ActiveModel) describe email do let(:locale) { :ir } describe email do it { should have_errors_on_email.because("is not routable") } end end end end unless defined?(ActiveModel) describe "without i18n" do before(:each) { hide_const("I18n") } describe email do it { should have_errors_on_email.because("is not routable") } end end end end end describe "when not testing" do before(:each) { allow(Resolv::DNS).to receive(:open).never } describe "by default" do describe email do it { should_not have_errors_on_email } end end describe "explicitly" do describe email do let(:options) { { :check_mx => false } } it { should_not have_errors_on_email } end end end describe "without mocks" do describe email do let(:options) { { :check_mx => true } } it { should_not have_errors_on_email } end end end describe "custom regex" do let(:options) { { :with => /[0-9]+\@[0-9]+/ } } describe '012345@789' do it { should_not have_errors_on_email } end describe 'valid@example.com' do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "i18n" do before(:each) do allow(I18n.config).to receive(:locale).and_return(locale) end describe "present locale" do let(:locale) { :pl } describe "invalid@exmaple." do it { should have_errors_on_email.because("nieprawidłowy adres e-mail") } end end unless defined?(ActiveModel) describe "missing locale" do let(:locale) { :ir } describe "invalid@exmaple." do it { should have_errors_on_email.because("does not appear to be valid") } end end end end unless defined?(ActiveModel) describe "without i18n" do before(:each) { hide_const("I18n") } describe "invalid@exmaple." do it { should have_errors_on_email.because("does not appear to be valid") } end end end end it_should_behave_like :all_specs if defined?(ActiveModel) describe "shorthand ActiveModel validation" do subject do |example| user = Class.new do def initialize(email) @email = email.freeze end attr_reader :email include ActiveModel::Validations validates :email, :email_format => example.example_group_instance.options end example.example_group_instance.class::User = user user.new(example.example_group_instance.email).tap(&:valid?).errors.full_messages end it_should_behave_like :all_specs end end end
validates-email-format-of/validates_email_format_of
ca1a97d1a9fe85e57f3a105ae73d6b06aad5acb2
Fix YAML quoting
diff --git a/config/locales/fr.yml b/config/locales/fr.yml index 0e38089..c303e0a 100644 --- a/config/locales/fr.yml +++ b/config/locales/fr.yml @@ -1,8 +1,8 @@ fr: activemodel: &errors errors: messages: - invalid_email_address: 'ne semble pas être une adresse email valide' - email_address_not_routable: "n'est pas routable' + invalid_email_address: "ne semble pas être une adresse email valide" + email_address_not_routable: "n'est pas routable" activerecord: <<: *errors
validates-email-format-of/validates_email_format_of
5a0f59fc6c6f109e6b024126a26b0e2bfad58ddf
Use proper test domain for MX record tests
diff --git a/spec/validates_email_format_of_spec.rb b/spec/validates_email_format_of_spec.rb index c277658..733c929 100644 --- a/spec/validates_email_format_of_spec.rb +++ b/spec/validates_email_format_of_spec.rb @@ -1,323 +1,323 @@ # -*- encoding : utf-8 -*- require "#{File.expand_path(File.dirname(__FILE__))}/spec_helper" require "validates_email_format_of" RSpec.configure do |config| config.before(:suite) do ValidatesEmailFormatOf.load_i18n_locales I18n.enforce_available_locales = false end end describe ValidatesEmailFormatOf do subject do |example| if defined?(ActiveModel) user = Class.new do def initialize(email) @email = email.freeze end attr_reader :email include ActiveModel::Validations validates_email_format_of :email, example.example_group_instance.options end example.example_group_instance.class::User = user user.new(example.example_group_instance.email).tap(&:valid?).errors.full_messages else ValidatesEmailFormatOf::validate_email_format(email.freeze, options) end end let(:options) { {} } let(:email) { |example| example.example_group.description } shared_examples_for :all_specs do [ 'valid@example.com', 'Valid@test.example.com', 'valid+valid123@test.example.com', 'valid_valid123@test.example.com', 'valid-valid+123@test.example.co.uk', 'valid-valid+1.23@test.example.com.au', 'valid@example.co.uk', 'v@example.com', 'valid@example.ca', 'valid_@example.com', 'valid123.456@example.org', 'valid123.456@example.travel', 'valid123.456@example.museum', 'valid@example.mobi', 'valid@example.info', 'valid-@example.com', 'fake@p-t.k12.ok.us', # allow single character domain parts 'valid@mail.x.example.com', 'valid@x.com', 'valid@example.w-dash.sch.uk', # from RFC 3696, page 6 'customer/department=shipping@example.com', '$A12345@example.com', '!def!xyz%abc@example.com', '_somename@example.com', # apostrophes "test'test@example.com", # international domain names 'test@xn--bcher-kva.ch', 'test@example.xn--0zwm56d', 'test@192.192.192.1', # Allow quoted characters. Valid according to http://www.rfc-editor.org/errata_search.php?rfc=3696 '"Abc\@def"@example.com', '"Fred\ Bloggs"@example.com', '"Joe.\\Blow"@example.com', # Balanced quoted characters %!"example\\\\\\""@example.com!, %!"example\\\\"@example.com! ].each do |address| describe address do it { should_not have_errors_on_email } end end [ 'no_at_symbol', 'invalid@example-com', # period can not start local part '.invalid@example.com', # period can not end local part 'invalid.@example.com', # period can not appear twice consecutively in local part 'invali..d@example.com', # should not allow underscores in domain names 'invalid@ex_mple.com', 'invalid@e..example.com', 'invalid@p-t..example.com', 'invalid@example.com.', 'invalid@example.com_', 'invalid@example.com-', 'invalid-example.com', 'invalid@example.b#r.com', 'invalid@example.c', 'invali d@example.com', # TLD can not be only numeric 'invalid@example.123', # unclosed quote "\"a-17180061943-10618354-1993365053@example.com", # too many special chars used to cause the regexp to hang "-+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++@foo", 'invalidexample.com', # should not allow special chars after a period in the domain 'local@sub.)domain.com', 'local@sub.#domain.com', # one at a time "foo@example.com\nexample@gmail.com", 'invalid@example.', "\"foo\\\\\"\"@bar.com", "foo@mail.com\r\nfoo@mail.com", '@example.com', 'foo@', 'foo', 'Iñtërnâtiônàlizætiøn@hasnt.happened.to.email', # Escaped characters with quotes. From http://tools.ietf.org/html/rfc3696, page 5. Corrected in http://www.rfc-editor.org/errata_search.php?rfc=3696 'Fred\ Bloggs_@example.com', 'Abc\@def+@example.com', 'Joe.\\Blow@example.com', # Unbalanced quoted characters %!"example\\\\""example.com! ].each do |address| describe address do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe do shared_examples_for :local_length_limit do |limit| describe "#{'a' * limit}@example.com" do it { should_not have_errors_on_email } end describe "#{'a' * (limit + 1)}@example.com" do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "when using default" do it_should_behave_like :local_length_limit, 64 end describe "when overriding defaults" do let(:options) { { :local_length => 20 } } it_should_behave_like :local_length_limit, 20 end end describe do shared_examples_for :domain_length_limit do |limit| describe "user@#{'a' * (limit - 4)}.com" do it { should_not have_errors_on_email } end describe "user@#{'a' * (limit - 3)}.com" do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "when using default" do it_should_behave_like :domain_length_limit, 255 end describe "when overriding defaults" do let(:options) { { :domain_length => 100 } } it_should_behave_like :domain_length_limit, 100 end end describe "custom error messages" do describe 'invalid@example.' do let(:options) { { :message => "just because I don't like you" } } it { should have_errors_on_email.because("just because I don't like you") } end end describe "mx record" do - domain = "stubbed.com" + domain = "example.com" email = "valid@#{domain}" describe "when testing" do let(:dns) { double(Resolv::DNS) } let(:mx_record) { [double] } let(:a_record) { [double] } before(:each) do allow(Resolv::DNS).to receive(:open).and_yield(dns) allow(dns).to receive(:getresources).with(domain, Resolv::DNS::Resource::IN::MX).once.and_return(mx_record) allow(dns).to receive(:getresources).with(domain, Resolv::DNS::Resource::IN::A).once.and_return(a_record) end let(:options) { { :check_mx => true } } describe "and only an mx record is found" do let(:a_record) { [] } describe email do it { should_not have_errors_on_email } end end describe "and only an a record is found" do let(:mx_record) { [] } describe email do it { should_not have_errors_on_email } end end describe "and both an mx record and an a record are found" do describe email do it { should_not have_errors_on_email } end end describe "and neither an mx record nor an a record is found" do let(:a_record) { [] } let(:mx_record) { [] } describe email do it { should have_errors_on_email.because("is not routable") } end describe "with a custom error message" do let(:options) { { :check_mx => true, :mx_message => "There ain't no such domain!" } } describe email do it { should have_errors_on_email.because("There ain't no such domain!") } end end describe "i18n" do before(:each) do allow(I18n.config).to receive(:locale).and_return(locale) end describe "present locale" do let(:locale) { :pl } describe email do it { should have_errors_on_email.because("jest nieosiągalny") } end end unless defined?(ActiveModel) describe email do let(:locale) { :ir } describe email do it { should have_errors_on_email.because("is not routable") } end end end end unless defined?(ActiveModel) describe "without i18n" do before(:each) { hide_const("I18n") } describe email do it { should have_errors_on_email.because("is not routable") } end end end end end describe "when not testing" do before(:each) { allow(Resolv::DNS).to receive(:open).never } describe "by default" do describe email do it { should_not have_errors_on_email } end end describe "explicitly" do describe email do let(:options) { { :check_mx => false } } it { should_not have_errors_on_email } end end end describe "without mocks" do describe email do let(:options) { { :check_mx => true } } it { should_not have_errors_on_email } end end end describe "custom regex" do let(:options) { { :with => /[0-9]+\@[0-9]+/ } } describe '012345@789' do it { should_not have_errors_on_email } end describe 'valid@example.com' do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "i18n" do before(:each) do allow(I18n.config).to receive(:locale).and_return(locale) end describe "present locale" do let(:locale) { :pl } describe "invalid@exmaple." do it { should have_errors_on_email.because("nieprawidłowy adres e-mail") } end end unless defined?(ActiveModel) describe "missing locale" do let(:locale) { :ir } describe "invalid@exmaple." do it { should have_errors_on_email.because("does not appear to be valid") } end end end end unless defined?(ActiveModel) describe "without i18n" do before(:each) { hide_const("I18n") } describe "invalid@exmaple." do it { should have_errors_on_email.because("does not appear to be valid") } end end end end it_should_behave_like :all_specs if defined?(ActiveModel) describe "shorthand ActiveModel validation" do subject do |example| user = Class.new do def initialize(email) @email = email.freeze end attr_reader :email include ActiveModel::Validations validates :email, :email_format => example.example_group_instance.options end example.example_group_instance.class::User = user user.new(example.example_group_instance.email).tap(&:valid?).errors.full_messages end it_should_behave_like :all_specs end end end
validates-email-format-of/validates_email_format_of
d5f7dd3dd9d97a1291f42b259d3b84f5319c7edb
Add pry-byebug
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index f37dab1..29cd87e 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,22 +1,24 @@ require 'active_model' if Gem.loaded_specs.keys.include?('activemodel') +require 'pry' +require 'byebug' RSpec::Matchers.define :have_errors_on_email do match do |actual| expect(actual).not_to be_nil, "#{actual} should not be nil" expect(actual).not_to be_empty, "#{actual} should not be empty" expect(actual.size).to eq(@reasons.size), "#{actual} should have #{@reasons.size} elements" @reasons.each do |reason| reason = "#{"Email " if defined?(ActiveModel)}#{reason}" expect(actual).to include(reason), "#{actual} should contain #{reason}" end end chain :because do |reason| (@reasons ||= []) << reason end chain :and_because do |reason| (@reasons ||= []) << reason end match_when_negated do |actual| expect(actual).to (defined?(ActiveModel) ? be_empty : be_nil) end end diff --git a/validates_email_format_of.gemspec b/validates_email_format_of.gemspec index 9ed09cf..a84ea26 100644 --- a/validates_email_format_of.gemspec +++ b/validates_email_format_of.gemspec @@ -1,28 +1,28 @@ # -*- encoding: utf-8 -*- $:.unshift File.expand_path('../lib', __FILE__) require 'validates_email_format_of/version' spec = Gem::Specification.new do |s| s.name = 'validates_email_format_of' s.version = ValidatesEmailFormatOf::VERSION s.summary = 'Validate e-mail addresses against RFC 2822 and RFC 3696.' s.description = s.summary s.authors = ['Alex Dunae', 'Isaac Betesh'] s.email = ['code@dunae.ca', 'iybetesh@gmail.com'] s.homepage = 'https://github.com/validates-email-format-of/validates_email_format_of' s.license = 'MIT' s.test_files = s.files.grep(%r{^test/}) s.files = `git ls-files`.split($/) s.require_paths = ['lib'] if RUBY_VERSION < "1.9.3" s.add_dependency 'i18n', '< 0.7.0' else s.add_dependency 'i18n' end s.add_development_dependency 'bundler' s.add_development_dependency 'rspec' s.add_development_dependency 'appraisal' - s.add_development_dependency 'pry' + s.add_development_dependency 'pry-byebug' end
validates-email-format-of/validates_email_format_of
d1df803172c5b09c36b7b2c614732b164cf252be
Simplify rspec matcher test
diff --git a/lib/validates_email_format_of/rspec_matcher.rb b/lib/validates_email_format_of/rspec_matcher.rb index f96a367..4ae6638 100644 --- a/lib/validates_email_format_of/rspec_matcher.rb +++ b/lib/validates_email_format_of/rspec_matcher.rb @@ -1,14 +1,14 @@ require "validates_email_format_of" RSpec::Matchers.define :validate_email_format_of do |attribute| match do actual = subject.is_a?(Class) ? subject.new : subject actual.send(:"#{attribute}=", "invalid@example.") expect(actual).to be_invalid @expected_message ||= ValidatesEmailFormatOf.default_message - expect(actual.errors.messages[attribute.to_sym]).to include(@expected_message) + expect(actual.errors.added?(attribute, :invalid_email_address)).to be_truthy end chain :with_message do |message| @expected_message = message end end
validates-email-format-of/validates_email_format_of
86ffcdeb05adb8c2765c06d293dd41181c731298
Switch to Github CI and use Appraisals to manage tests
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..1051f7d --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,64 @@ +name: CI + +on: + push: + branches: [master] + pull_request: + branches: [master] + +permissions: + contents: read + +jobs: + test: + name: "Ruby ${{ matrix.ruby }}, Rails ${{ matrix.gemfile }}" + + runs-on: ubuntu-latest + + strategy: + matrix: + ruby: ["2.6", "2.7", "3.0", "3.1"] + gemfile: ["4.2", "5.0", "5.1", "5.2", "6.0", "6.1", "7.0"] + exclude: + - gemfile: "4.2" + ruby: "3.0" + - gemfile: "4.2" + ruby: "3.1" + - gemfile: "5.0" + ruby: "3.0" + - gemfile: "5.0" + ruby: "3.1" + - gemfile: "5.1" + ruby: "3.0" + - gemfile: "5.1" + ruby: "3.1" + - gemfile: "5.2" + ruby: "3.0" + - gemfile: "5.2" + ruby: "3.1" + - gemfile: "7.0" + ruby: "2.5" + - gemfile: "7.0" + ruby: "2.6" + - gemfile: "7.0" + ruby: "2.7" + + env: + BUNDLE_GEMFILE: gemfiles/rails_${{ matrix.gemfile }}.gemfile + RAILS_ENV: test + + steps: + - uses: actions/checkout@v3 + + - name: "Install Ruby ${{ matrix.ruby }}" + # To automatically get bug fixes and new Ruby versions for ruby/setup-ruby, + # change this to (see https://github.com/ruby/setup-ruby#versioning): + # uses: ruby/setup-ruby@v1 + uses: ruby/setup-ruby@v1 + with: + bundler: 1 + ruby-version: ${{ matrix.ruby }} + bundler-cache: true # runs 'bundle install' and caches installed gems automatically + + - name: Run specs + run: bundle exec rspec diff --git a/.gitignore b/.gitignore index e948cd3..0fb9174 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,10 @@ pkg test/debug.log rdoc Gemfile.lock *.gem *.sqlite3 *.swp .ruby-version +gemfiles/.bundle +gemfiles/*.gemfile.lock diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 4276332..0000000 --- a/.travis.yml +++ /dev/null @@ -1,18 +0,0 @@ -rvm: - - 1.8.7 - - 1.9.2 - - 1.9.3 - - 2.0.0 - - 2.1.2 - - jruby - - ree -gemfile: - - Gemfile - - gemfiles/active_model_2_1 - - gemfiles/active_model_3_0 - - gemfiles/active_model_3_1 - - gemfiles/active_model_3_2 - - gemfiles/active_model_4_0 - - gemfiles/active_model_4_1 -install: bundle install -script: bundle exec rspec diff --git a/Appraisals b/Appraisals new file mode 100644 index 0000000..122b1d6 --- /dev/null +++ b/Appraisals @@ -0,0 +1,32 @@ +# run `bundle exec appraisal install` after making changes here +appraise "rails-7.0" do + gem "rails", "~> 7.0" +end + +appraise "rails-6.1" do + gem "rails", "~> 6.1.0" +end + +appraise "rails-6.0" do + gem "rails", "~> 6.0.3", '>= 6.0.3.2' +end + +appraise "rails-5.2" do + gem "rails", "~> 5.2.4", '>= 5.2.4.3' + gem "i18n", "< 1" +end + +appraise "rails-5.1" do + gem "rails", "~> 5.1.7" + gem "i18n", "< 1" +end + +appraise "rails-5.0" do + gem "rails", "~> 5.0.7", '>= 5.0.7.2' + gem "i18n", "< 1" +end + +appraise "rails-4.2" do + gem "rails", "~> 4.2.0" + gem "i18n", "< 1" +end diff --git a/README.rdoc b/README.rdoc index 3dfd1c9..5476fc8 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,98 +1,98 @@ = validates_email_format_of Gem and Rails Plugin Validate e-mail addresses against RFC 2822 and RFC 3696. == Installation Installing as a gem: gem install validates_email_format_of Or in your Gemfile: gem 'validates_email_format_of' == Usage # Rails # I18n locales are loaded automatically. class Person < ActiveRecord::Base validates_email_format_of :email, :message => 'is not looking good' # OR validates :email, :email_format => { :message => 'is not looking good' } end # Now you can test your model using RSpec: require "validates_email_format_of/rspec_matcher" describe Person do it { should validate_email_format_of(:email).with_message('is not looking good') } end # If you're not using Rails (which really means, if you're not using ActiveModel::Validations) ValidatesEmailFormatOf::load_i18n_locales # Optional, if you want error messages to be in your language I18n.locale = :pl # If, for example, you want Polish error messages. ValidatesEmailFormatOf::validate_email_format("example@mydomain.com") # => nil ValidatesEmailFormatOf::validate_email_format("invalid_because_there_is_no_at_symbol") # => ["does not appear to be a valid e-mail address"] === Options :message String. A custom error message when the email format is invalid (default is: "does not appear to be a valid e-mail address") :check_mx Boolean. Check domain for a valid MX record (default is false) :mx_message String. A custom error message when the domain does not match a valid MX record (default is: "is not routable"). Ignored unless :check_mx option is true. :local_length Maximum number of characters allowed in the local part (everything before the '@') (default is 64) :domain_length Maximum number of characters allowed in the domain part (everything after the '@') (default is 255) :generate_message Boolean. Return the I18n key of the error message instead of the error message itself (default is false) :with Specify a custom Regex as the valid email format. :on, :if, :unless, :allow_nil, :allow_blank, :strict Standard ActiveModel validation options. These work in the ActiveModel/ActiveRecord/Rails syntax only. See http://api.rubyonrails.org/classes/ActiveModel/Validations/ClassMethods.html#method-i-validates for details. == Testing -To execute the unit tests run <tt>rspec</tt>. +To execute the unit tests against [all the Rails versions we support run](gemfiles/) <tt>bundle exec appraisal rspec</tt> or run against an individual version with <tt>bundle exec appraisal rails-6.0 rspec</tt>. Tested in Ruby 1.8.7, 1.9.2, 1.9.3, 2.0.0, 2.1.2, JRuby and REE 1.8.7. == Contributing If you think we're letting some rules about valid email formats slip through the cracks, don't just update the Regex. Instead, add a failing test, and demonstrate that the described email address should be treated differently. A link to an appropriate RFC is the best way to do this. Then change the gem code to make the test pass. describe "i_think_this_is_not_a_v@lid_email_addre.ss" do # According to http://..., this email address IS NOT valid. it { should have_errors_on_email.because("does not appear to be valid") } end describe "i_think_this_is_a_v@lid_email_addre.ss" do # According to http://..., this email address IS valid. it { should_not have_errors_on_email } end Yes, our Rspec syntax is that simple! == Homepage * https://github.com/validates-email-format-of/validates_email_format_of == Credits Written by Alex Dunae (dunae.ca), 2006-11. Many thanks to the plugin's recent contributors: https://github.com/alexdunae/validates_email_format_of/contributors Thanks to Francis Hwang (http://fhwang.net/) at Diversion Media for creating the 1.1 update. Thanks to Travis Sinnott for creating the 1.3 update. Thanks to Denis Ahearn at Riverock Technologies (http://www.riverocktech.com/) for creating the 1.4 update. Thanks to George Anderson (http://github.com/george) and 'history' (http://github.com/history) for creating the 1.4.1 update. Thanks to Isaac Betesh (https://github.com/betesh) for converting tests to Rspec and refactoring for version 1.6.0. diff --git a/gemfiles/Gemfile.active_model_2_1 b/gemfiles/Gemfile.active_model_2_1 deleted file mode 100644 index 736aa95..0000000 --- a/gemfiles/Gemfile.active_model_2_1 +++ /dev/null @@ -1,5 +0,0 @@ -source "http://rubygems.org" - -gemspec - -gem 'activemodel', '= 2.1.0' diff --git a/gemfiles/Gemfile.active_model_3_0 b/gemfiles/Gemfile.active_model_3_0 deleted file mode 100644 index 736aa95..0000000 --- a/gemfiles/Gemfile.active_model_3_0 +++ /dev/null @@ -1,5 +0,0 @@ -source "http://rubygems.org" - -gemspec - -gem 'activemodel', '= 2.1.0' diff --git a/gemfiles/Gemfile.active_model_3_1 b/gemfiles/Gemfile.active_model_3_1 deleted file mode 100644 index 1b9894e..0000000 --- a/gemfiles/Gemfile.active_model_3_1 +++ /dev/null @@ -1,5 +0,0 @@ -source "http://rubygems.org" - -gemspec - -gem 'activemodel', '= 3.1.0' diff --git a/gemfiles/Gemfile.active_model_3_2 b/gemfiles/Gemfile.active_model_3_2 deleted file mode 100644 index e2c9597..0000000 --- a/gemfiles/Gemfile.active_model_3_2 +++ /dev/null @@ -1,5 +0,0 @@ -source "http://rubygems.org" - -gemspec - -gem 'activemodel', '= 3.2.0' diff --git a/gemfiles/Gemfile.active_model_3_3 b/gemfiles/Gemfile.active_model_3_3 deleted file mode 100644 index bd153a2..0000000 --- a/gemfiles/Gemfile.active_model_3_3 +++ /dev/null @@ -1,5 +0,0 @@ -source "http://rubygems.org" - -gemspec - -gem 'active_model', '= 3.3.0' diff --git a/gemfiles/Gemfile.active_model_4_0 b/gemfiles/Gemfile.active_model_4_0 deleted file mode 100644 index 9236dd7..0000000 --- a/gemfiles/Gemfile.active_model_4_0 +++ /dev/null @@ -1,5 +0,0 @@ -source "http://rubygems.org" - -gemspec - -gem 'activemodel', '= 4.0.0' diff --git a/gemfiles/Gemfile.active_model_4_1 b/gemfiles/Gemfile.active_model_4_1 deleted file mode 100644 index b97fab6..0000000 --- a/gemfiles/Gemfile.active_model_4_1 +++ /dev/null @@ -1,5 +0,0 @@ -source "http://rubygems.org" - -gemspec - -gem 'activemodel', '= 4.1.0' diff --git a/gemfiles/rails_4.2.gemfile b/gemfiles/rails_4.2.gemfile new file mode 100644 index 0000000..c8aff67 --- /dev/null +++ b/gemfiles/rails_4.2.gemfile @@ -0,0 +1,8 @@ +# This file was generated by Appraisal + +source "http://rubygems.org" + +gem "rails", "~> 4.2.0" +gem "i18n", "< 1" + +gemspec path: "../" diff --git a/gemfiles/rails_5.0.gemfile b/gemfiles/rails_5.0.gemfile new file mode 100644 index 0000000..d32321d --- /dev/null +++ b/gemfiles/rails_5.0.gemfile @@ -0,0 +1,8 @@ +# This file was generated by Appraisal + +source "http://rubygems.org" + +gem "rails", "~> 5.0.7", ">= 5.0.7.2" +gem "i18n", "< 1" + +gemspec path: "../" diff --git a/gemfiles/rails_5.1.gemfile b/gemfiles/rails_5.1.gemfile new file mode 100644 index 0000000..cf78573 --- /dev/null +++ b/gemfiles/rails_5.1.gemfile @@ -0,0 +1,8 @@ +# This file was generated by Appraisal + +source "http://rubygems.org" + +gem "rails", "~> 5.1.7" +gem "i18n", "< 1" + +gemspec path: "../" diff --git a/gemfiles/rails_5.2.gemfile b/gemfiles/rails_5.2.gemfile new file mode 100644 index 0000000..93456ef --- /dev/null +++ b/gemfiles/rails_5.2.gemfile @@ -0,0 +1,8 @@ +# This file was generated by Appraisal + +source "http://rubygems.org" + +gem "rails", "~> 5.2.4", ">= 5.2.4.3" +gem "i18n", "< 1" + +gemspec path: "../" diff --git a/gemfiles/rails_6.0.gemfile b/gemfiles/rails_6.0.gemfile new file mode 100644 index 0000000..4831699 --- /dev/null +++ b/gemfiles/rails_6.0.gemfile @@ -0,0 +1,7 @@ +# This file was generated by Appraisal + +source "http://rubygems.org" + +gem "rails", "~> 6.0.3", ">= 6.0.3.2" + +gemspec path: "../" diff --git a/gemfiles/rails_6.1.gemfile b/gemfiles/rails_6.1.gemfile new file mode 100644 index 0000000..49332d8 --- /dev/null +++ b/gemfiles/rails_6.1.gemfile @@ -0,0 +1,7 @@ +# This file was generated by Appraisal + +source "http://rubygems.org" + +gem "rails", "~> 6.1.0" + +gemspec path: "../" diff --git a/gemfiles/rails_7.0.gemfile b/gemfiles/rails_7.0.gemfile new file mode 100644 index 0000000..2486a26 --- /dev/null +++ b/gemfiles/rails_7.0.gemfile @@ -0,0 +1,7 @@ +# This file was generated by Appraisal + +source "http://rubygems.org" + +gem "rails", "~> 7.0" + +gemspec path: "../" diff --git a/validates_email_format_of.gemspec b/validates_email_format_of.gemspec index 5273197..9ed09cf 100644 --- a/validates_email_format_of.gemspec +++ b/validates_email_format_of.gemspec @@ -1,26 +1,28 @@ # -*- encoding: utf-8 -*- $:.unshift File.expand_path('../lib', __FILE__) require 'validates_email_format_of/version' spec = Gem::Specification.new do |s| s.name = 'validates_email_format_of' s.version = ValidatesEmailFormatOf::VERSION s.summary = 'Validate e-mail addresses against RFC 2822 and RFC 3696.' s.description = s.summary s.authors = ['Alex Dunae', 'Isaac Betesh'] s.email = ['code@dunae.ca', 'iybetesh@gmail.com'] s.homepage = 'https://github.com/validates-email-format-of/validates_email_format_of' s.license = 'MIT' s.test_files = s.files.grep(%r{^test/}) s.files = `git ls-files`.split($/) s.require_paths = ['lib'] if RUBY_VERSION < "1.9.3" s.add_dependency 'i18n', '< 0.7.0' else s.add_dependency 'i18n' end s.add_development_dependency 'bundler' s.add_development_dependency 'rspec' + s.add_development_dependency 'appraisal' + s.add_development_dependency 'pry' end
validates-email-format-of/validates_email_format_of
0a6193f105bcfcd65feafd2880d978b0feac3a7f
Drop now-unused directive from gemspec
diff --git a/validates_email_format_of.gemspec b/validates_email_format_of.gemspec index 5273197..3687539 100644 --- a/validates_email_format_of.gemspec +++ b/validates_email_format_of.gemspec @@ -1,26 +1,25 @@ # -*- encoding: utf-8 -*- $:.unshift File.expand_path('../lib', __FILE__) require 'validates_email_format_of/version' spec = Gem::Specification.new do |s| s.name = 'validates_email_format_of' s.version = ValidatesEmailFormatOf::VERSION s.summary = 'Validate e-mail addresses against RFC 2822 and RFC 3696.' s.description = s.summary s.authors = ['Alex Dunae', 'Isaac Betesh'] s.email = ['code@dunae.ca', 'iybetesh@gmail.com'] s.homepage = 'https://github.com/validates-email-format-of/validates_email_format_of' s.license = 'MIT' - s.test_files = s.files.grep(%r{^test/}) s.files = `git ls-files`.split($/) s.require_paths = ['lib'] if RUBY_VERSION < "1.9.3" s.add_dependency 'i18n', '< 0.7.0' else s.add_dependency 'i18n' end s.add_development_dependency 'bundler' s.add_development_dependency 'rspec' end
validates-email-format-of/validates_email_format_of
929f1d3c85aa37ac61d3a8b372f812372cce95df
Suppress warning
diff --git a/lib/validates_email_format_of.rb b/lib/validates_email_format_of.rb index ab2a6dc..6262b8f 100644 --- a/lib/validates_email_format_of.rb +++ b/lib/validates_email_format_of.rb @@ -1,150 +1,150 @@ # encoding: utf-8 require 'validates_email_format_of/version' module ValidatesEmailFormatOf def self.load_i18n_locales require 'i18n' I18n.load_path += Dir.glob(File.expand_path(File.join(File.dirname(__FILE__), '..', 'config', 'locales', '*.yml'))) end require 'resolv' - LocalPartSpecialChars = /[\!\#\$\%\&\'\*\-\/\=\?\+\-\^\_\`\{\|\}\~]/ + LocalPartSpecialChars = /[\!\#\$\%\&\'\*\-\/\=\?\+\^\_\`\{\|\}\~]/ def self.validate_email_domain(email) domain = email.to_s.downcase.match(/\@(.+)/)[1] Resolv::DNS.open do |dns| @mx = dns.getresources(domain, Resolv::DNS::Resource::IN::MX) + dns.getresources(domain, Resolv::DNS::Resource::IN::A) end @mx.size > 0 ? true : false end DEFAULT_MESSAGE = "does not appear to be valid" DEFAULT_MX_MESSAGE = "is not routable" ERROR_MESSAGE_I18N_KEY = :invalid_email_address ERROR_MX_MESSAGE_I18N_KEY = :email_address_not_routable def self.default_message defined?(I18n) ? I18n.t(ERROR_MESSAGE_I18N_KEY, :scope => [:activemodel, :errors, :messages], :default => DEFAULT_MESSAGE) : DEFAULT_MESSAGE end # Validates whether the specified value is a valid email address. Returns nil if the value is valid, otherwise returns an array # containing one or more validation error messages. # # Configuration options: # * <tt>message</tt> - A custom error message (default is: "does not appear to be valid") # * <tt>check_mx</tt> - Check for MX records (default is false) # * <tt>mx_message</tt> - A custom error message when an MX record validation fails (default is: "is not routable.") # * <tt>with</tt> The regex to use for validating the format of the email address (deprecated) # * <tt>local_length</tt> Maximum number of characters allowed in the local part (default is 64) # * <tt>domain_length</tt> Maximum number of characters allowed in the domain part (default is 255) # * <tt>generate_message</tt> Return the I18n key of the error message instead of the error message itself (default is false) def self.validate_email_format(email, options={}) default_options = { :message => options[:generate_message] ? ERROR_MESSAGE_I18N_KEY : default_message, :check_mx => false, :mx_message => options[:generate_message] ? ERROR_MX_MESSAGE_I18N_KEY : (defined?(I18n) ? I18n.t(ERROR_MX_MESSAGE_I18N_KEY, :scope => [:activemodel, :errors, :messages], :default => DEFAULT_MX_MESSAGE) : DEFAULT_MX_MESSAGE), :domain_length => 255, :local_length => 64, :generate_message => false } opts = options.merge(default_options) {|key, old, new| old} # merge the default options into the specified options, retaining all specified options email = email.strip if email begin domain, local = email.reverse.split('@', 2) rescue return [ opts[:message] ] end # need local and domain parts return [ opts[:message] ] unless local and not local.empty? and domain and not domain.empty? # check lengths return [ opts[:message] ] unless domain.length <= opts[:domain_length] and local.length <= opts[:local_length] local.reverse! domain.reverse! if opts.has_key?(:with) # holdover from versions <= 1.4.7 return [ opts[:message] ] unless email =~ opts[:with] else return [ opts[:message] ] unless self.validate_local_part_syntax(local) and self.validate_domain_part_syntax(domain) end if opts[:check_mx] and !self.validate_email_domain(email) return [ opts[:mx_message] ] end return nil # represents no validation errors end def self.validate_local_part_syntax(local) in_quoted_pair = false in_quoted_string = false (0..local.length-1).each do |i| ord = local[i].ord # accept anything if it's got a backslash before it if in_quoted_pair in_quoted_pair = false next end # backslash signifies the start of a quoted pair if ord == 92 and i < local.length - 1 return false if not in_quoted_string # must be in quoted string per http://www.rfc-editor.org/errata_search.php?rfc=3696 in_quoted_pair = true next end # double quote delimits quoted strings if ord == 34 in_quoted_string = !in_quoted_string next end next if local[i,1] =~ /[a-z0-9]/i next if local[i,1] =~ LocalPartSpecialChars # period must be followed by something if ord == 46 return false if i == 0 or i == local.length - 1 # can't be first or last char next unless local[i+1].ord == 46 # can't be followed by a period end return false end return false if in_quoted_string # unbalanced quotes return true end def self.validate_domain_part_syntax(domain) parts = domain.downcase.split('.', -1) return false if parts.length <= 1 # Only one domain part # Empty parts (double period) or invalid chars return false if parts.any? { |part| part.nil? or part.empty? or not part =~ /\A[[:alnum:]\-]+\Z/ or part[0,1] == '-' or part[-1,1] == '-' # hyphen at beginning or end of part } # ipv4 return true if parts.length == 4 and parts.all? { |part| part =~ /\A[0-9]+\Z/ and part.to_i.between?(0, 255) } return false if parts[-1].length < 2 or not parts[-1] =~ /[a-z\-]/ # TLD is too short or does not contain a char or hyphen return true end end require 'validates_email_format_of/active_model' if defined?(::ActiveModel) && !(ActiveModel::VERSION::MAJOR < 2 || (2 == ActiveModel::VERSION::MAJOR && ActiveModel::VERSION::MINOR < 1)) require 'validates_email_format_of/railtie' if defined?(::Rails::Railtie)
validates-email-format-of/validates_email_format_of
d68c82ca98ab8090d3f7f35eeb37494ce89e232b
Italian localization
diff --git a/config/locales/it.yml b/config/locales/it.yml index 9a7379c..986c64a 100644 --- a/config/locales/it.yml +++ b/config/locales/it.yml @@ -1,8 +1,8 @@ it: activemodel: &errors errors: messages: invalid_email_address: 'non sembra un indirizzo e-mail valido' - email_address_not_routable: "l'indirizzo email non è raggiungibile" + email_address_not_routable: 'dominio non raggiungibile' activerecord: <<: *errors
validates-email-format-of/validates_email_format_of
f939d17e06e7ccbbe727b76475ea5d2cfb92ffd4
Italian localization
diff --git a/config/locales/it.yml b/config/locales/it.yml new file mode 100644 index 0000000..9a7379c --- /dev/null +++ b/config/locales/it.yml @@ -0,0 +1,8 @@ +it: + activemodel: &errors + errors: + messages: + invalid_email_address: 'non sembra un indirizzo e-mail valido' + email_address_not_routable: "l'indirizzo email non è raggiungibile" + activerecord: + <<: *errors
validates-email-format-of/validates_email_format_of
b1753d30f604b00da002cf498284a89945a8592d
Use SimpleIDN gem to support international domain names
diff --git a/lib/validates_email_format_of.rb b/lib/validates_email_format_of.rb index ab2a6dc..be46527 100644 --- a/lib/validates_email_format_of.rb +++ b/lib/validates_email_format_of.rb @@ -1,150 +1,151 @@ # encoding: utf-8 require 'validates_email_format_of/version' +require 'simpleidn' module ValidatesEmailFormatOf def self.load_i18n_locales require 'i18n' I18n.load_path += Dir.glob(File.expand_path(File.join(File.dirname(__FILE__), '..', 'config', 'locales', '*.yml'))) end require 'resolv' LocalPartSpecialChars = /[\!\#\$\%\&\'\*\-\/\=\?\+\-\^\_\`\{\|\}\~]/ def self.validate_email_domain(email) - domain = email.to_s.downcase.match(/\@(.+)/)[1] + domain = SimpleIDN.to_ascii(email.to_s.downcase.match(/\@(.+)/)[1]) Resolv::DNS.open do |dns| @mx = dns.getresources(domain, Resolv::DNS::Resource::IN::MX) + dns.getresources(domain, Resolv::DNS::Resource::IN::A) end @mx.size > 0 ? true : false end DEFAULT_MESSAGE = "does not appear to be valid" DEFAULT_MX_MESSAGE = "is not routable" ERROR_MESSAGE_I18N_KEY = :invalid_email_address ERROR_MX_MESSAGE_I18N_KEY = :email_address_not_routable def self.default_message defined?(I18n) ? I18n.t(ERROR_MESSAGE_I18N_KEY, :scope => [:activemodel, :errors, :messages], :default => DEFAULT_MESSAGE) : DEFAULT_MESSAGE end # Validates whether the specified value is a valid email address. Returns nil if the value is valid, otherwise returns an array # containing one or more validation error messages. # # Configuration options: # * <tt>message</tt> - A custom error message (default is: "does not appear to be valid") # * <tt>check_mx</tt> - Check for MX records (default is false) # * <tt>mx_message</tt> - A custom error message when an MX record validation fails (default is: "is not routable.") # * <tt>with</tt> The regex to use for validating the format of the email address (deprecated) # * <tt>local_length</tt> Maximum number of characters allowed in the local part (default is 64) # * <tt>domain_length</tt> Maximum number of characters allowed in the domain part (default is 255) # * <tt>generate_message</tt> Return the I18n key of the error message instead of the error message itself (default is false) def self.validate_email_format(email, options={}) default_options = { :message => options[:generate_message] ? ERROR_MESSAGE_I18N_KEY : default_message, :check_mx => false, :mx_message => options[:generate_message] ? ERROR_MX_MESSAGE_I18N_KEY : (defined?(I18n) ? I18n.t(ERROR_MX_MESSAGE_I18N_KEY, :scope => [:activemodel, :errors, :messages], :default => DEFAULT_MX_MESSAGE) : DEFAULT_MX_MESSAGE), :domain_length => 255, :local_length => 64, :generate_message => false } opts = options.merge(default_options) {|key, old, new| old} # merge the default options into the specified options, retaining all specified options email = email.strip if email begin domain, local = email.reverse.split('@', 2) rescue return [ opts[:message] ] end # need local and domain parts return [ opts[:message] ] unless local and not local.empty? and domain and not domain.empty? # check lengths return [ opts[:message] ] unless domain.length <= opts[:domain_length] and local.length <= opts[:local_length] local.reverse! domain.reverse! if opts.has_key?(:with) # holdover from versions <= 1.4.7 return [ opts[:message] ] unless email =~ opts[:with] else return [ opts[:message] ] unless self.validate_local_part_syntax(local) and self.validate_domain_part_syntax(domain) end if opts[:check_mx] and !self.validate_email_domain(email) return [ opts[:mx_message] ] end return nil # represents no validation errors end def self.validate_local_part_syntax(local) in_quoted_pair = false in_quoted_string = false (0..local.length-1).each do |i| ord = local[i].ord # accept anything if it's got a backslash before it if in_quoted_pair in_quoted_pair = false next end # backslash signifies the start of a quoted pair if ord == 92 and i < local.length - 1 return false if not in_quoted_string # must be in quoted string per http://www.rfc-editor.org/errata_search.php?rfc=3696 in_quoted_pair = true next end # double quote delimits quoted strings if ord == 34 in_quoted_string = !in_quoted_string next end next if local[i,1] =~ /[a-z0-9]/i next if local[i,1] =~ LocalPartSpecialChars # period must be followed by something if ord == 46 return false if i == 0 or i == local.length - 1 # can't be first or last char next unless local[i+1].ord == 46 # can't be followed by a period end return false end return false if in_quoted_string # unbalanced quotes return true end def self.validate_domain_part_syntax(domain) parts = domain.downcase.split('.', -1) return false if parts.length <= 1 # Only one domain part # Empty parts (double period) or invalid chars return false if parts.any? { |part| part.nil? or part.empty? or not part =~ /\A[[:alnum:]\-]+\Z/ or part[0,1] == '-' or part[-1,1] == '-' # hyphen at beginning or end of part } # ipv4 return true if parts.length == 4 and parts.all? { |part| part =~ /\A[0-9]+\Z/ and part.to_i.between?(0, 255) } return false if parts[-1].length < 2 or not parts[-1] =~ /[a-z\-]/ # TLD is too short or does not contain a char or hyphen return true end end require 'validates_email_format_of/active_model' if defined?(::ActiveModel) && !(ActiveModel::VERSION::MAJOR < 2 || (2 == ActiveModel::VERSION::MAJOR && ActiveModel::VERSION::MINOR < 1)) require 'validates_email_format_of/railtie' if defined?(::Rails::Railtie) diff --git a/validates_email_format_of.gemspec b/validates_email_format_of.gemspec index 5273197..fe15ca0 100644 --- a/validates_email_format_of.gemspec +++ b/validates_email_format_of.gemspec @@ -1,26 +1,28 @@ # -*- encoding: utf-8 -*- $:.unshift File.expand_path('../lib', __FILE__) require 'validates_email_format_of/version' spec = Gem::Specification.new do |s| s.name = 'validates_email_format_of' s.version = ValidatesEmailFormatOf::VERSION s.summary = 'Validate e-mail addresses against RFC 2822 and RFC 3696.' s.description = s.summary s.authors = ['Alex Dunae', 'Isaac Betesh'] s.email = ['code@dunae.ca', 'iybetesh@gmail.com'] s.homepage = 'https://github.com/validates-email-format-of/validates_email_format_of' s.license = 'MIT' s.test_files = s.files.grep(%r{^test/}) s.files = `git ls-files`.split($/) s.require_paths = ['lib'] if RUBY_VERSION < "1.9.3" s.add_dependency 'i18n', '< 0.7.0' else s.add_dependency 'i18n' end s.add_development_dependency 'bundler' s.add_development_dependency 'rspec' + + s.add_dependency 'simpleidn' end
validates-email-format-of/validates_email_format_of
88a1d1e675b138f3cff80365a2f964bc64e0a9ec
Add activerecord key to FR locale
diff --git a/config/locales/fr.yml b/config/locales/fr.yml new file mode 100644 index 0000000..0e38089 --- /dev/null +++ b/config/locales/fr.yml @@ -0,0 +1,8 @@ +fr: + activemodel: &errors + errors: + messages: + invalid_email_address: 'ne semble pas être une adresse email valide' + email_address_not_routable: "n'est pas routable' + activerecord: + <<: *errors
validates-email-format-of/validates_email_format_of
6a6e9807168de0b48820a365df46a49cd3e51dd1
Creating locale messages for pt and pt-BR
diff --git a/config/locales/pt-BR.yml b/config/locales/pt-BR.yml new file mode 100644 index 0000000..73415ac --- /dev/null +++ b/config/locales/pt-BR.yml @@ -0,0 +1,8 @@ +pt-BR: + activemodel: &errors + errors: + messages: + invalid_email_address: 'não parece ser um endereço de e-mail válido' + email_address_not_routable: 'não é acessível' + activerecord: + <<: *errors diff --git a/config/locales/pt.yml b/config/locales/pt.yml new file mode 100644 index 0000000..e15c5a0 --- /dev/null +++ b/config/locales/pt.yml @@ -0,0 +1,8 @@ +pt: + activemodel: &errors + errors: + messages: + invalid_email_address: 'não parece ser um endereço de e-mail válido' + email_address_not_routable: 'não é acessível' + activerecord: + <<: *errors
validates-email-format-of/validates_email_format_of
14dd0630d21172e0a03128501a9380633226c6ff
incremented release number
diff --git a/lib/validates_email_format_of/version.rb b/lib/validates_email_format_of/version.rb index 6c6a4ab..ff8a9d4 100644 --- a/lib/validates_email_format_of/version.rb +++ b/lib/validates_email_format_of/version.rb @@ -1,3 +1,3 @@ module ValidatesEmailFormatOf - VERSION = '1.6.2' + VERSION = '1.6.3' end
validates-email-format-of/validates_email_format_of
3fdc5eeebd445e6650707769055b94eb302944f7
just because ::Rails is defined doesn't mean we should load a Railtie
diff --git a/lib/validates_email_format_of.rb b/lib/validates_email_format_of.rb index bc82732..ab2a6dc 100644 --- a/lib/validates_email_format_of.rb +++ b/lib/validates_email_format_of.rb @@ -1,150 +1,150 @@ # encoding: utf-8 require 'validates_email_format_of/version' module ValidatesEmailFormatOf def self.load_i18n_locales require 'i18n' I18n.load_path += Dir.glob(File.expand_path(File.join(File.dirname(__FILE__), '..', 'config', 'locales', '*.yml'))) end require 'resolv' LocalPartSpecialChars = /[\!\#\$\%\&\'\*\-\/\=\?\+\-\^\_\`\{\|\}\~]/ def self.validate_email_domain(email) domain = email.to_s.downcase.match(/\@(.+)/)[1] Resolv::DNS.open do |dns| @mx = dns.getresources(domain, Resolv::DNS::Resource::IN::MX) + dns.getresources(domain, Resolv::DNS::Resource::IN::A) end @mx.size > 0 ? true : false end DEFAULT_MESSAGE = "does not appear to be valid" DEFAULT_MX_MESSAGE = "is not routable" ERROR_MESSAGE_I18N_KEY = :invalid_email_address ERROR_MX_MESSAGE_I18N_KEY = :email_address_not_routable def self.default_message defined?(I18n) ? I18n.t(ERROR_MESSAGE_I18N_KEY, :scope => [:activemodel, :errors, :messages], :default => DEFAULT_MESSAGE) : DEFAULT_MESSAGE end # Validates whether the specified value is a valid email address. Returns nil if the value is valid, otherwise returns an array # containing one or more validation error messages. # # Configuration options: # * <tt>message</tt> - A custom error message (default is: "does not appear to be valid") # * <tt>check_mx</tt> - Check for MX records (default is false) # * <tt>mx_message</tt> - A custom error message when an MX record validation fails (default is: "is not routable.") # * <tt>with</tt> The regex to use for validating the format of the email address (deprecated) # * <tt>local_length</tt> Maximum number of characters allowed in the local part (default is 64) # * <tt>domain_length</tt> Maximum number of characters allowed in the domain part (default is 255) # * <tt>generate_message</tt> Return the I18n key of the error message instead of the error message itself (default is false) def self.validate_email_format(email, options={}) default_options = { :message => options[:generate_message] ? ERROR_MESSAGE_I18N_KEY : default_message, :check_mx => false, :mx_message => options[:generate_message] ? ERROR_MX_MESSAGE_I18N_KEY : (defined?(I18n) ? I18n.t(ERROR_MX_MESSAGE_I18N_KEY, :scope => [:activemodel, :errors, :messages], :default => DEFAULT_MX_MESSAGE) : DEFAULT_MX_MESSAGE), :domain_length => 255, :local_length => 64, :generate_message => false } opts = options.merge(default_options) {|key, old, new| old} # merge the default options into the specified options, retaining all specified options email = email.strip if email begin domain, local = email.reverse.split('@', 2) rescue return [ opts[:message] ] end # need local and domain parts return [ opts[:message] ] unless local and not local.empty? and domain and not domain.empty? # check lengths return [ opts[:message] ] unless domain.length <= opts[:domain_length] and local.length <= opts[:local_length] local.reverse! domain.reverse! if opts.has_key?(:with) # holdover from versions <= 1.4.7 return [ opts[:message] ] unless email =~ opts[:with] else return [ opts[:message] ] unless self.validate_local_part_syntax(local) and self.validate_domain_part_syntax(domain) end if opts[:check_mx] and !self.validate_email_domain(email) return [ opts[:mx_message] ] end return nil # represents no validation errors end def self.validate_local_part_syntax(local) in_quoted_pair = false in_quoted_string = false (0..local.length-1).each do |i| ord = local[i].ord # accept anything if it's got a backslash before it if in_quoted_pair in_quoted_pair = false next end # backslash signifies the start of a quoted pair if ord == 92 and i < local.length - 1 return false if not in_quoted_string # must be in quoted string per http://www.rfc-editor.org/errata_search.php?rfc=3696 in_quoted_pair = true next end # double quote delimits quoted strings if ord == 34 in_quoted_string = !in_quoted_string next end next if local[i,1] =~ /[a-z0-9]/i next if local[i,1] =~ LocalPartSpecialChars # period must be followed by something if ord == 46 return false if i == 0 or i == local.length - 1 # can't be first or last char next unless local[i+1].ord == 46 # can't be followed by a period end return false end return false if in_quoted_string # unbalanced quotes return true end def self.validate_domain_part_syntax(domain) parts = domain.downcase.split('.', -1) return false if parts.length <= 1 # Only one domain part # Empty parts (double period) or invalid chars return false if parts.any? { |part| part.nil? or part.empty? or not part =~ /\A[[:alnum:]\-]+\Z/ or part[0,1] == '-' or part[-1,1] == '-' # hyphen at beginning or end of part } # ipv4 return true if parts.length == 4 and parts.all? { |part| part =~ /\A[0-9]+\Z/ and part.to_i.between?(0, 255) } return false if parts[-1].length < 2 or not parts[-1] =~ /[a-z\-]/ # TLD is too short or does not contain a char or hyphen return true end end require 'validates_email_format_of/active_model' if defined?(::ActiveModel) && !(ActiveModel::VERSION::MAJOR < 2 || (2 == ActiveModel::VERSION::MAJOR && ActiveModel::VERSION::MINOR < 1)) -require 'validates_email_format_of/railtie' if defined?(::Rails) +require 'validates_email_format_of/railtie' if defined?(::Rails::Railtie)
validates-email-format-of/validates_email_format_of
b0e21e62bc8bb3858ba9b49539f5abaea1d1cbc5
Create ja.yml
diff --git a/config/locales/ja.yml b/config/locales/ja.yml new file mode 100644 index 0000000..d8226b2 --- /dev/null +++ b/config/locales/ja.yml @@ -0,0 +1,8 @@ +ja: + activemodel: &errors + errors: + messages: + invalid_email_address: 'は妥当なメールアドレスでは無いようです。' + email_address_not_routable: 'は到達不能です。' + activerecord: + <<: *errors
validates-email-format-of/validates_email_format_of
4c62754b4f31f1e9c7b9b2bf6d55185d0d8fe54c
bumped release version [ci skip]
diff --git a/lib/validates_email_format_of/version.rb b/lib/validates_email_format_of/version.rb index d9097a2..6c6a4ab 100644 --- a/lib/validates_email_format_of/version.rb +++ b/lib/validates_email_format_of/version.rb @@ -1,3 +1,3 @@ module ValidatesEmailFormatOf - VERSION = '1.6.1' + VERSION = '1.6.2' end
validates-email-format-of/validates_email_format_of
708476a6453a63a0d0f68404993074bde46221f8
restricted i18n to an allowed version for older versions of Ruby
diff --git a/validates_email_format_of.gemspec b/validates_email_format_of.gemspec index 248f355..5273197 100644 --- a/validates_email_format_of.gemspec +++ b/validates_email_format_of.gemspec @@ -1,21 +1,26 @@ # -*- encoding: utf-8 -*- $:.unshift File.expand_path('../lib', __FILE__) require 'validates_email_format_of/version' spec = Gem::Specification.new do |s| s.name = 'validates_email_format_of' s.version = ValidatesEmailFormatOf::VERSION s.summary = 'Validate e-mail addresses against RFC 2822 and RFC 3696.' s.description = s.summary s.authors = ['Alex Dunae', 'Isaac Betesh'] s.email = ['code@dunae.ca', 'iybetesh@gmail.com'] s.homepage = 'https://github.com/validates-email-format-of/validates_email_format_of' s.license = 'MIT' s.test_files = s.files.grep(%r{^test/}) s.files = `git ls-files`.split($/) s.require_paths = ['lib'] - s.add_dependency 'i18n' + if RUBY_VERSION < "1.9.3" + s.add_dependency 'i18n', '< 0.7.0' + else + s.add_dependency 'i18n' + end + s.add_development_dependency 'bundler' s.add_development_dependency 'rspec' end
validates-email-format-of/validates_email_format_of
55347a4949bb5f2d97346e9c06a8c5b9888e7f2c
made it possible to override subject when using rspec matcher
diff --git a/lib/validates_email_format_of/rspec_matcher.rb b/lib/validates_email_format_of/rspec_matcher.rb index 5b1aff6..f96a367 100644 --- a/lib/validates_email_format_of/rspec_matcher.rb +++ b/lib/validates_email_format_of/rspec_matcher.rb @@ -1,15 +1,14 @@ require "validates_email_format_of" RSpec::Matchers.define :validate_email_format_of do |attribute| match do - actual_class_name = subject.is_a?(Class) ? subject : subject.class - actual = actual_class_name.new + actual = subject.is_a?(Class) ? subject.new : subject actual.send(:"#{attribute}=", "invalid@example.") expect(actual).to be_invalid @expected_message ||= ValidatesEmailFormatOf.default_message expect(actual.errors.messages[attribute.to_sym]).to include(@expected_message) end chain :with_message do |message| @expected_message = message end end
validates-email-format-of/validates_email_format_of
22549b2a51dfa177b6e40a89bf408e4b1a190ecd
made it possible to run rspec_mathcher_spec in isolation
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 36dec55..f37dab1 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,29 +1,22 @@ require 'active_model' if Gem.loaded_specs.keys.include?('activemodel') RSpec::Matchers.define :have_errors_on_email do match do |actual| expect(actual).not_to be_nil, "#{actual} should not be nil" expect(actual).not_to be_empty, "#{actual} should not be empty" expect(actual.size).to eq(@reasons.size), "#{actual} should have #{@reasons.size} elements" @reasons.each do |reason| reason = "#{"Email " if defined?(ActiveModel)}#{reason}" expect(actual).to include(reason), "#{actual} should contain #{reason}" end end chain :because do |reason| (@reasons ||= []) << reason end chain :and_because do |reason| (@reasons ||= []) << reason end match_when_negated do |actual| expect(actual).to (defined?(ActiveModel) ? be_empty : be_nil) end end - -RSpec.configure do |config| - config.before(:suite) do - ValidatesEmailFormatOf.load_i18n_locales - I18n.enforce_available_locales = false - end -end diff --git a/spec/validates_email_format_of_spec.rb b/spec/validates_email_format_of_spec.rb index 94dc6e4..c277658 100644 --- a/spec/validates_email_format_of_spec.rb +++ b/spec/validates_email_format_of_spec.rb @@ -1,316 +1,323 @@ # -*- encoding : utf-8 -*- require "#{File.expand_path(File.dirname(__FILE__))}/spec_helper" require "validates_email_format_of" +RSpec.configure do |config| + config.before(:suite) do + ValidatesEmailFormatOf.load_i18n_locales + I18n.enforce_available_locales = false + end +end + describe ValidatesEmailFormatOf do subject do |example| if defined?(ActiveModel) user = Class.new do def initialize(email) @email = email.freeze end attr_reader :email include ActiveModel::Validations validates_email_format_of :email, example.example_group_instance.options end example.example_group_instance.class::User = user user.new(example.example_group_instance.email).tap(&:valid?).errors.full_messages else ValidatesEmailFormatOf::validate_email_format(email.freeze, options) end end let(:options) { {} } let(:email) { |example| example.example_group.description } shared_examples_for :all_specs do [ 'valid@example.com', 'Valid@test.example.com', 'valid+valid123@test.example.com', 'valid_valid123@test.example.com', 'valid-valid+123@test.example.co.uk', 'valid-valid+1.23@test.example.com.au', 'valid@example.co.uk', 'v@example.com', 'valid@example.ca', 'valid_@example.com', 'valid123.456@example.org', 'valid123.456@example.travel', 'valid123.456@example.museum', 'valid@example.mobi', 'valid@example.info', 'valid-@example.com', 'fake@p-t.k12.ok.us', # allow single character domain parts 'valid@mail.x.example.com', 'valid@x.com', 'valid@example.w-dash.sch.uk', # from RFC 3696, page 6 'customer/department=shipping@example.com', '$A12345@example.com', '!def!xyz%abc@example.com', '_somename@example.com', # apostrophes "test'test@example.com", # international domain names 'test@xn--bcher-kva.ch', 'test@example.xn--0zwm56d', 'test@192.192.192.1', # Allow quoted characters. Valid according to http://www.rfc-editor.org/errata_search.php?rfc=3696 '"Abc\@def"@example.com', '"Fred\ Bloggs"@example.com', '"Joe.\\Blow"@example.com', # Balanced quoted characters %!"example\\\\\\""@example.com!, %!"example\\\\"@example.com! ].each do |address| describe address do it { should_not have_errors_on_email } end end [ 'no_at_symbol', 'invalid@example-com', # period can not start local part '.invalid@example.com', # period can not end local part 'invalid.@example.com', # period can not appear twice consecutively in local part 'invali..d@example.com', # should not allow underscores in domain names 'invalid@ex_mple.com', 'invalid@e..example.com', 'invalid@p-t..example.com', 'invalid@example.com.', 'invalid@example.com_', 'invalid@example.com-', 'invalid-example.com', 'invalid@example.b#r.com', 'invalid@example.c', 'invali d@example.com', # TLD can not be only numeric 'invalid@example.123', # unclosed quote "\"a-17180061943-10618354-1993365053@example.com", # too many special chars used to cause the regexp to hang "-+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++@foo", 'invalidexample.com', # should not allow special chars after a period in the domain 'local@sub.)domain.com', 'local@sub.#domain.com', # one at a time "foo@example.com\nexample@gmail.com", 'invalid@example.', "\"foo\\\\\"\"@bar.com", "foo@mail.com\r\nfoo@mail.com", '@example.com', 'foo@', 'foo', 'Iñtërnâtiônàlizætiøn@hasnt.happened.to.email', # Escaped characters with quotes. From http://tools.ietf.org/html/rfc3696, page 5. Corrected in http://www.rfc-editor.org/errata_search.php?rfc=3696 'Fred\ Bloggs_@example.com', 'Abc\@def+@example.com', 'Joe.\\Blow@example.com', # Unbalanced quoted characters %!"example\\\\""example.com! ].each do |address| describe address do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe do shared_examples_for :local_length_limit do |limit| describe "#{'a' * limit}@example.com" do it { should_not have_errors_on_email } end describe "#{'a' * (limit + 1)}@example.com" do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "when using default" do it_should_behave_like :local_length_limit, 64 end describe "when overriding defaults" do let(:options) { { :local_length => 20 } } it_should_behave_like :local_length_limit, 20 end end describe do shared_examples_for :domain_length_limit do |limit| describe "user@#{'a' * (limit - 4)}.com" do it { should_not have_errors_on_email } end describe "user@#{'a' * (limit - 3)}.com" do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "when using default" do it_should_behave_like :domain_length_limit, 255 end describe "when overriding defaults" do let(:options) { { :domain_length => 100 } } it_should_behave_like :domain_length_limit, 100 end end describe "custom error messages" do describe 'invalid@example.' do let(:options) { { :message => "just because I don't like you" } } it { should have_errors_on_email.because("just because I don't like you") } end end describe "mx record" do domain = "stubbed.com" email = "valid@#{domain}" describe "when testing" do let(:dns) { double(Resolv::DNS) } let(:mx_record) { [double] } let(:a_record) { [double] } before(:each) do allow(Resolv::DNS).to receive(:open).and_yield(dns) allow(dns).to receive(:getresources).with(domain, Resolv::DNS::Resource::IN::MX).once.and_return(mx_record) allow(dns).to receive(:getresources).with(domain, Resolv::DNS::Resource::IN::A).once.and_return(a_record) end let(:options) { { :check_mx => true } } describe "and only an mx record is found" do let(:a_record) { [] } describe email do it { should_not have_errors_on_email } end end describe "and only an a record is found" do let(:mx_record) { [] } describe email do it { should_not have_errors_on_email } end end describe "and both an mx record and an a record are found" do describe email do it { should_not have_errors_on_email } end end describe "and neither an mx record nor an a record is found" do let(:a_record) { [] } let(:mx_record) { [] } describe email do it { should have_errors_on_email.because("is not routable") } end describe "with a custom error message" do let(:options) { { :check_mx => true, :mx_message => "There ain't no such domain!" } } describe email do it { should have_errors_on_email.because("There ain't no such domain!") } end end describe "i18n" do before(:each) do allow(I18n.config).to receive(:locale).and_return(locale) end describe "present locale" do let(:locale) { :pl } describe email do it { should have_errors_on_email.because("jest nieosiągalny") } end end unless defined?(ActiveModel) describe email do let(:locale) { :ir } describe email do it { should have_errors_on_email.because("is not routable") } end end end end unless defined?(ActiveModel) describe "without i18n" do before(:each) { hide_const("I18n") } describe email do it { should have_errors_on_email.because("is not routable") } end end end end end describe "when not testing" do before(:each) { allow(Resolv::DNS).to receive(:open).never } describe "by default" do describe email do it { should_not have_errors_on_email } end end describe "explicitly" do describe email do let(:options) { { :check_mx => false } } it { should_not have_errors_on_email } end end end describe "without mocks" do describe email do let(:options) { { :check_mx => true } } it { should_not have_errors_on_email } end end end describe "custom regex" do let(:options) { { :with => /[0-9]+\@[0-9]+/ } } describe '012345@789' do it { should_not have_errors_on_email } end describe 'valid@example.com' do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "i18n" do before(:each) do allow(I18n.config).to receive(:locale).and_return(locale) end describe "present locale" do let(:locale) { :pl } describe "invalid@exmaple." do it { should have_errors_on_email.because("nieprawidłowy adres e-mail") } end end unless defined?(ActiveModel) describe "missing locale" do let(:locale) { :ir } describe "invalid@exmaple." do it { should have_errors_on_email.because("does not appear to be valid") } end end end end unless defined?(ActiveModel) describe "without i18n" do before(:each) { hide_const("I18n") } describe "invalid@exmaple." do it { should have_errors_on_email.because("does not appear to be valid") } end end end end it_should_behave_like :all_specs if defined?(ActiveModel) describe "shorthand ActiveModel validation" do subject do |example| user = Class.new do def initialize(email) @email = email.freeze end attr_reader :email include ActiveModel::Validations validates :email, :email_format => example.example_group_instance.options end example.example_group_instance.class::User = user user.new(example.example_group_instance.email).tap(&:valid?).errors.full_messages end it_should_behave_like :all_specs end end end
validates-email-format-of/validates_email_format_of
9e6e3531d0d711b60032a6248180f9feaf8b7cff
added activerecord key to DE locale
diff --git a/config/locales/de.yml b/config/locales/de.yml index 9725c37..643c6cb 100644 --- a/config/locales/de.yml +++ b/config/locales/de.yml @@ -1,6 +1,8 @@ de: - activemodel: + activemodel: &errors errors: messages: invalid_email_address: 'ist offensichtlich keine gültige E-Mail-Adresse' email_address_not_routable: 'kann nicht erreicht werden' + activerecord: + <<: *errors
validates-email-format-of/validates_email_format_of
5a0a2a11aafb8eaa268a67232bbd945ba02880fe
bumped release number
diff --git a/lib/validates_email_format_of/version.rb b/lib/validates_email_format_of/version.rb index b83f3d4..d9097a2 100644 --- a/lib/validates_email_format_of/version.rb +++ b/lib/validates_email_format_of/version.rb @@ -1,3 +1,3 @@ module ValidatesEmailFormatOf - VERSION = '1.6.0' + VERSION = '1.6.1' end
validates-email-format-of/validates_email_format_of
537dc9e23174bee6c64f33dd77a5738ccd958c1c
using ActiveModel / ActiveRecord default I18n keys, to get the most out of defaults
diff --git a/CHANGELOG b/CHANGELOG new file mode 100644 index 0000000..d344bcc --- /dev/null +++ b/CHANGELOG @@ -0,0 +1,3 @@ +== 1.6.1 (8 Sept 2014) + +* In a Rails context, this gem now uses ActiveModel's default logic for constructing I18n keys, to make it easier to override them on a model/attribute basis. diff --git a/README.rdoc b/README.rdoc index a85c35e..3dfd1c9 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,96 +1,98 @@ = validates_email_format_of Gem and Rails Plugin Validate e-mail addresses against RFC 2822 and RFC 3696. == Installation Installing as a gem: gem install validates_email_format_of Or in your Gemfile: gem 'validates_email_format_of' == Usage # Rails # I18n locales are loaded automatically. class Person < ActiveRecord::Base validates_email_format_of :email, :message => 'is not looking good' # OR validates :email, :email_format => { :message => 'is not looking good' } end # Now you can test your model using RSpec: require "validates_email_format_of/rspec_matcher" describe Person do it { should validate_email_format_of(:email).with_message('is not looking good') } end # If you're not using Rails (which really means, if you're not using ActiveModel::Validations) ValidatesEmailFormatOf::load_i18n_locales # Optional, if you want error messages to be in your language I18n.locale = :pl # If, for example, you want Polish error messages. ValidatesEmailFormatOf::validate_email_format("example@mydomain.com") # => nil ValidatesEmailFormatOf::validate_email_format("invalid_because_there_is_no_at_symbol") # => ["does not appear to be a valid e-mail address"] === Options :message String. A custom error message when the email format is invalid (default is: "does not appear to be a valid e-mail address") :check_mx Boolean. Check domain for a valid MX record (default is false) :mx_message String. A custom error message when the domain does not match a valid MX record (default is: "is not routable"). Ignored unless :check_mx option is true. :local_length Maximum number of characters allowed in the local part (everything before the '@') (default is 64) :domain_length Maximum number of characters allowed in the domain part (everything after the '@') (default is 255) + :generate_message + Boolean. Return the I18n key of the error message instead of the error message itself (default is false) :with Specify a custom Regex as the valid email format. :on, :if, :unless, :allow_nil, :allow_blank, :strict Standard ActiveModel validation options. These work in the ActiveModel/ActiveRecord/Rails syntax only. See http://api.rubyonrails.org/classes/ActiveModel/Validations/ClassMethods.html#method-i-validates for details. == Testing To execute the unit tests run <tt>rspec</tt>. Tested in Ruby 1.8.7, 1.9.2, 1.9.3, 2.0.0, 2.1.2, JRuby and REE 1.8.7. == Contributing If you think we're letting some rules about valid email formats slip through the cracks, don't just update the Regex. Instead, add a failing test, and demonstrate that the described email address should be treated differently. A link to an appropriate RFC is the best way to do this. Then change the gem code to make the test pass. describe "i_think_this_is_not_a_v@lid_email_addre.ss" do # According to http://..., this email address IS NOT valid. it { should have_errors_on_email.because("does not appear to be valid") } end describe "i_think_this_is_a_v@lid_email_addre.ss" do # According to http://..., this email address IS valid. it { should_not have_errors_on_email } end Yes, our Rspec syntax is that simple! == Homepage * https://github.com/validates-email-format-of/validates_email_format_of == Credits Written by Alex Dunae (dunae.ca), 2006-11. Many thanks to the plugin's recent contributors: https://github.com/alexdunae/validates_email_format_of/contributors Thanks to Francis Hwang (http://fhwang.net/) at Diversion Media for creating the 1.1 update. Thanks to Travis Sinnott for creating the 1.3 update. Thanks to Denis Ahearn at Riverock Technologies (http://www.riverocktech.com/) for creating the 1.4 update. Thanks to George Anderson (http://github.com/george) and 'history' (http://github.com/history) for creating the 1.4.1 update. Thanks to Isaac Betesh (https://github.com/betesh) for converting tests to Rspec and refactoring for version 1.6.0. diff --git a/config/locales/en.yml b/config/locales/en.yml index 7bcb04e..529b7c9 100644 --- a/config/locales/en.yml +++ b/config/locales/en.yml @@ -1,6 +1,8 @@ en: - activemodel: + activemodel: &errors errors: messages: invalid_email_address: 'does not appear to be a valid e-mail address' email_address_not_routable: 'is not routable' + activerecord: + <<: *errors diff --git a/config/locales/pl.yml b/config/locales/pl.yml index 31b9aa7..0a03239 100644 --- a/config/locales/pl.yml +++ b/config/locales/pl.yml @@ -1,6 +1,8 @@ pl: - activemodel: + activemodel: &errors errors: messages: invalid_email_address: 'nieprawidłowy adres e-mail' email_address_not_routable: 'jest nieosiągalny' + activerecord: + <<: *errors diff --git a/lib/validates_email_format_of.rb b/lib/validates_email_format_of.rb index 78d92ab..bc82732 100644 --- a/lib/validates_email_format_of.rb +++ b/lib/validates_email_format_of.rb @@ -1,145 +1,150 @@ # encoding: utf-8 require 'validates_email_format_of/version' module ValidatesEmailFormatOf def self.load_i18n_locales require 'i18n' I18n.load_path += Dir.glob(File.expand_path(File.join(File.dirname(__FILE__), '..', 'config', 'locales', '*.yml'))) end require 'resolv' LocalPartSpecialChars = /[\!\#\$\%\&\'\*\-\/\=\?\+\-\^\_\`\{\|\}\~]/ def self.validate_email_domain(email) domain = email.to_s.downcase.match(/\@(.+)/)[1] Resolv::DNS.open do |dns| @mx = dns.getresources(domain, Resolv::DNS::Resource::IN::MX) + dns.getresources(domain, Resolv::DNS::Resource::IN::A) end @mx.size > 0 ? true : false end + DEFAULT_MESSAGE = "does not appear to be valid" + DEFAULT_MX_MESSAGE = "is not routable" + ERROR_MESSAGE_I18N_KEY = :invalid_email_address + ERROR_MX_MESSAGE_I18N_KEY = :email_address_not_routable + + def self.default_message + defined?(I18n) ? I18n.t(ERROR_MESSAGE_I18N_KEY, :scope => [:activemodel, :errors, :messages], :default => DEFAULT_MESSAGE) : DEFAULT_MESSAGE + end + # Validates whether the specified value is a valid email address. Returns nil if the value is valid, otherwise returns an array # containing one or more validation error messages. # # Configuration options: # * <tt>message</tt> - A custom error message (default is: "does not appear to be valid") # * <tt>check_mx</tt> - Check for MX records (default is false) # * <tt>mx_message</tt> - A custom error message when an MX record validation fails (default is: "is not routable.") # * <tt>with</tt> The regex to use for validating the format of the email address (deprecated) # * <tt>local_length</tt> Maximum number of characters allowed in the local part (default is 64) # * <tt>domain_length</tt> Maximum number of characters allowed in the domain part (default is 255) - DEFAULT_MESSAGE = "does not appear to be valid" - DEFAULT_MX_MESSAGE = "is not routable" - def self.default_message - defined?(I18n) ? I18n.t(:invalid_email_address, :scope => [:activemodel, :errors, :messages], :default => DEFAULT_MESSAGE) : DEFAULT_MESSAGE - end - + # * <tt>generate_message</tt> Return the I18n key of the error message instead of the error message itself (default is false) def self.validate_email_format(email, options={}) - default_options = { :message => default_message, + default_options = { :message => options[:generate_message] ? ERROR_MESSAGE_I18N_KEY : default_message, :check_mx => false, - :mx_message => defined?(I18n) ? I18n.t(:email_address_not_routable, :scope => [:activemodel, :errors, :messages], :default => DEFAULT_MX_MESSAGE) : DEFAULT_MX_MESSAGE, + :mx_message => options[:generate_message] ? ERROR_MX_MESSAGE_I18N_KEY : (defined?(I18n) ? I18n.t(ERROR_MX_MESSAGE_I18N_KEY, :scope => [:activemodel, :errors, :messages], :default => DEFAULT_MX_MESSAGE) : DEFAULT_MX_MESSAGE), :domain_length => 255, - :local_length => 64 + :local_length => 64, + :generate_message => false } opts = options.merge(default_options) {|key, old, new| old} # merge the default options into the specified options, retaining all specified options email = email.strip if email begin domain, local = email.reverse.split('@', 2) rescue return [ opts[:message] ] end # need local and domain parts return [ opts[:message] ] unless local and not local.empty? and domain and not domain.empty? # check lengths return [ opts[:message] ] unless domain.length <= opts[:domain_length] and local.length <= opts[:local_length] local.reverse! domain.reverse! if opts.has_key?(:with) # holdover from versions <= 1.4.7 return [ opts[:message] ] unless email =~ opts[:with] else return [ opts[:message] ] unless self.validate_local_part_syntax(local) and self.validate_domain_part_syntax(domain) end if opts[:check_mx] and !self.validate_email_domain(email) return [ opts[:mx_message] ] end return nil # represents no validation errors end def self.validate_local_part_syntax(local) in_quoted_pair = false in_quoted_string = false (0..local.length-1).each do |i| ord = local[i].ord # accept anything if it's got a backslash before it if in_quoted_pair in_quoted_pair = false next end # backslash signifies the start of a quoted pair if ord == 92 and i < local.length - 1 return false if not in_quoted_string # must be in quoted string per http://www.rfc-editor.org/errata_search.php?rfc=3696 in_quoted_pair = true next end # double quote delimits quoted strings if ord == 34 in_quoted_string = !in_quoted_string next end next if local[i,1] =~ /[a-z0-9]/i next if local[i,1] =~ LocalPartSpecialChars # period must be followed by something if ord == 46 return false if i == 0 or i == local.length - 1 # can't be first or last char next unless local[i+1].ord == 46 # can't be followed by a period end return false end return false if in_quoted_string # unbalanced quotes return true end def self.validate_domain_part_syntax(domain) parts = domain.downcase.split('.', -1) return false if parts.length <= 1 # Only one domain part # Empty parts (double period) or invalid chars return false if parts.any? { |part| part.nil? or part.empty? or not part =~ /\A[[:alnum:]\-]+\Z/ or part[0,1] == '-' or part[-1,1] == '-' # hyphen at beginning or end of part } # ipv4 return true if parts.length == 4 and parts.all? { |part| part =~ /\A[0-9]+\Z/ and part.to_i.between?(0, 255) } return false if parts[-1].length < 2 or not parts[-1] =~ /[a-z\-]/ # TLD is too short or does not contain a char or hyphen return true end end require 'validates_email_format_of/active_model' if defined?(::ActiveModel) && !(ActiveModel::VERSION::MAJOR < 2 || (2 == ActiveModel::VERSION::MAJOR && ActiveModel::VERSION::MINOR < 1)) require 'validates_email_format_of/railtie' if defined?(::Rails) diff --git a/lib/validates_email_format_of/active_model.rb b/lib/validates_email_format_of/active_model.rb index 14ad5d0..b9a95a7 100644 --- a/lib/validates_email_format_of/active_model.rb +++ b/lib/validates_email_format_of/active_model.rb @@ -1,24 +1,24 @@ require 'validates_email_format_of' require 'active_model' if ActiveModel::VERSION::MAJOR < 2 || (2 == ActiveModel::VERSION::MAJOR && ActiveModel::VERSION::MINOR < 1) puts "WARNING: ActiveModel validation helper methods in validates_email_format_of gem are not compatible with ActiveModel < 2.1.0. Please use ValidatesEmailFormatOf::validate_email_format(email, options) or upgrade ActiveModel" end module ActiveModel module Validations class EmailFormatValidator < EachValidator def validate_each(record, attribute, value) - (ValidatesEmailFormatOf::validate_email_format(value, options) || []).each do |error| + (ValidatesEmailFormatOf::validate_email_format(value, options.merge(:generate_message => true)) || []).each do |error| record.errors.add(attribute, error) end end end module HelperMethods def validates_email_format_of(*attr_names) validates_with EmailFormatValidator, _merge_attributes(attr_names) end end end end diff --git a/spec/validates_email_format_of_spec.rb b/spec/validates_email_format_of_spec.rb index c5e2160..94dc6e4 100644 --- a/spec/validates_email_format_of_spec.rb +++ b/spec/validates_email_format_of_spec.rb @@ -1,308 +1,316 @@ # -*- encoding : utf-8 -*- require "#{File.expand_path(File.dirname(__FILE__))}/spec_helper" require "validates_email_format_of" describe ValidatesEmailFormatOf do subject do |example| if defined?(ActiveModel) user = Class.new do def initialize(email) @email = email.freeze end attr_reader :email include ActiveModel::Validations validates_email_format_of :email, example.example_group_instance.options end example.example_group_instance.class::User = user user.new(example.example_group_instance.email).tap(&:valid?).errors.full_messages else ValidatesEmailFormatOf::validate_email_format(email.freeze, options) end end let(:options) { {} } let(:email) { |example| example.example_group.description } shared_examples_for :all_specs do [ 'valid@example.com', 'Valid@test.example.com', 'valid+valid123@test.example.com', 'valid_valid123@test.example.com', 'valid-valid+123@test.example.co.uk', 'valid-valid+1.23@test.example.com.au', 'valid@example.co.uk', 'v@example.com', 'valid@example.ca', 'valid_@example.com', 'valid123.456@example.org', 'valid123.456@example.travel', 'valid123.456@example.museum', 'valid@example.mobi', 'valid@example.info', 'valid-@example.com', 'fake@p-t.k12.ok.us', # allow single character domain parts 'valid@mail.x.example.com', 'valid@x.com', 'valid@example.w-dash.sch.uk', # from RFC 3696, page 6 'customer/department=shipping@example.com', '$A12345@example.com', '!def!xyz%abc@example.com', '_somename@example.com', # apostrophes "test'test@example.com", # international domain names 'test@xn--bcher-kva.ch', 'test@example.xn--0zwm56d', 'test@192.192.192.1', # Allow quoted characters. Valid according to http://www.rfc-editor.org/errata_search.php?rfc=3696 '"Abc\@def"@example.com', '"Fred\ Bloggs"@example.com', '"Joe.\\Blow"@example.com', # Balanced quoted characters %!"example\\\\\\""@example.com!, %!"example\\\\"@example.com! ].each do |address| describe address do it { should_not have_errors_on_email } end end [ 'no_at_symbol', 'invalid@example-com', # period can not start local part '.invalid@example.com', # period can not end local part 'invalid.@example.com', # period can not appear twice consecutively in local part 'invali..d@example.com', # should not allow underscores in domain names 'invalid@ex_mple.com', 'invalid@e..example.com', 'invalid@p-t..example.com', 'invalid@example.com.', 'invalid@example.com_', 'invalid@example.com-', 'invalid-example.com', 'invalid@example.b#r.com', 'invalid@example.c', 'invali d@example.com', # TLD can not be only numeric 'invalid@example.123', # unclosed quote "\"a-17180061943-10618354-1993365053@example.com", # too many special chars used to cause the regexp to hang "-+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++@foo", 'invalidexample.com', # should not allow special chars after a period in the domain 'local@sub.)domain.com', 'local@sub.#domain.com', # one at a time "foo@example.com\nexample@gmail.com", 'invalid@example.', "\"foo\\\\\"\"@bar.com", "foo@mail.com\r\nfoo@mail.com", '@example.com', 'foo@', 'foo', 'Iñtërnâtiônàlizætiøn@hasnt.happened.to.email', # Escaped characters with quotes. From http://tools.ietf.org/html/rfc3696, page 5. Corrected in http://www.rfc-editor.org/errata_search.php?rfc=3696 'Fred\ Bloggs_@example.com', 'Abc\@def+@example.com', 'Joe.\\Blow@example.com', # Unbalanced quoted characters %!"example\\\\""example.com! ].each do |address| describe address do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe do shared_examples_for :local_length_limit do |limit| describe "#{'a' * limit}@example.com" do it { should_not have_errors_on_email } end describe "#{'a' * (limit + 1)}@example.com" do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "when using default" do it_should_behave_like :local_length_limit, 64 end describe "when overriding defaults" do let(:options) { { :local_length => 20 } } it_should_behave_like :local_length_limit, 20 end end describe do shared_examples_for :domain_length_limit do |limit| describe "user@#{'a' * (limit - 4)}.com" do it { should_not have_errors_on_email } end describe "user@#{'a' * (limit - 3)}.com" do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "when using default" do it_should_behave_like :domain_length_limit, 255 end describe "when overriding defaults" do let(:options) { { :domain_length => 100 } } it_should_behave_like :domain_length_limit, 100 end end describe "custom error messages" do describe 'invalid@example.' do let(:options) { { :message => "just because I don't like you" } } it { should have_errors_on_email.because("just because I don't like you") } end end describe "mx record" do domain = "stubbed.com" email = "valid@#{domain}" describe "when testing" do let(:dns) { double(Resolv::DNS) } let(:mx_record) { [double] } let(:a_record) { [double] } before(:each) do allow(Resolv::DNS).to receive(:open).and_yield(dns) allow(dns).to receive(:getresources).with(domain, Resolv::DNS::Resource::IN::MX).once.and_return(mx_record) allow(dns).to receive(:getresources).with(domain, Resolv::DNS::Resource::IN::A).once.and_return(a_record) end let(:options) { { :check_mx => true } } describe "and only an mx record is found" do let(:a_record) { [] } describe email do it { should_not have_errors_on_email } end end describe "and only an a record is found" do let(:mx_record) { [] } describe email do it { should_not have_errors_on_email } end end describe "and both an mx record and an a record are found" do describe email do it { should_not have_errors_on_email } end end describe "and neither an mx record nor an a record is found" do let(:a_record) { [] } let(:mx_record) { [] } describe email do it { should have_errors_on_email.because("is not routable") } end describe "with a custom error message" do let(:options) { { :check_mx => true, :mx_message => "There ain't no such domain!" } } describe email do it { should have_errors_on_email.because("There ain't no such domain!") } end end describe "i18n" do - before(:each) { allow(I18n.config).to receive(:locale).and_return(locale) } + before(:each) do + allow(I18n.config).to receive(:locale).and_return(locale) + end describe "present locale" do let(:locale) { :pl } describe email do it { should have_errors_on_email.because("jest nieosiągalny") } end end - describe email do - let(:locale) { :ir } + unless defined?(ActiveModel) describe email do - it { should have_errors_on_email.because("is not routable") } + let(:locale) { :ir } + describe email do + it { should have_errors_on_email.because("is not routable") } + end end end end unless defined?(ActiveModel) describe "without i18n" do before(:each) { hide_const("I18n") } describe email do it { should have_errors_on_email.because("is not routable") } end end end end end describe "when not testing" do before(:each) { allow(Resolv::DNS).to receive(:open).never } describe "by default" do describe email do it { should_not have_errors_on_email } end end describe "explicitly" do describe email do let(:options) { { :check_mx => false } } it { should_not have_errors_on_email } end end end describe "without mocks" do describe email do let(:options) { { :check_mx => true } } it { should_not have_errors_on_email } end end end describe "custom regex" do let(:options) { { :with => /[0-9]+\@[0-9]+/ } } describe '012345@789' do it { should_not have_errors_on_email } end describe 'valid@example.com' do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "i18n" do - before(:each) { allow(I18n.config).to receive(:locale).and_return(locale) } + before(:each) do + allow(I18n.config).to receive(:locale).and_return(locale) + end describe "present locale" do let(:locale) { :pl } describe "invalid@exmaple." do it { should have_errors_on_email.because("nieprawidłowy adres e-mail") } end end - describe "missing locale" do - let(:locale) { :ir } - describe "invalid@exmaple." do - it { should have_errors_on_email.because("does not appear to be valid") } + unless defined?(ActiveModel) + describe "missing locale" do + let(:locale) { :ir } + describe "invalid@exmaple." do + it { should have_errors_on_email.because("does not appear to be valid") } + end end end end unless defined?(ActiveModel) describe "without i18n" do before(:each) { hide_const("I18n") } describe "invalid@exmaple." do it { should have_errors_on_email.because("does not appear to be valid") } end end end end it_should_behave_like :all_specs if defined?(ActiveModel) describe "shorthand ActiveModel validation" do subject do |example| user = Class.new do def initialize(email) @email = email.freeze end attr_reader :email include ActiveModel::Validations validates :email, :email_format => example.example_group_instance.options end example.example_group_instance.class::User = user user.new(example.example_group_instance.email).tap(&:valid?).errors.full_messages end it_should_behave_like :all_specs end end end
validates-email-format-of/validates_email_format_of
08e8af5f8355f4eb30993c8ebc5a83d69d2bf0c4
Create de.yml
diff --git a/config/locales/de.yml b/config/locales/de.yml new file mode 100644 index 0000000..9725c37 --- /dev/null +++ b/config/locales/de.yml @@ -0,0 +1,6 @@ +de: + activemodel: + errors: + messages: + invalid_email_address: 'ist offensichtlich keine gültige E-Mail-Adresse' + email_address_not_routable: 'kann nicht erreicht werden'
validates-email-format-of/validates_email_format_of
8493531b956ee51fdea38ea52bbcef81a9896104
downcasing domain name before checking MX record -- fixes #40
diff --git a/lib/validates_email_format_of.rb b/lib/validates_email_format_of.rb index e2b6bad..78d92ab 100644 --- a/lib/validates_email_format_of.rb +++ b/lib/validates_email_format_of.rb @@ -1,145 +1,145 @@ # encoding: utf-8 require 'validates_email_format_of/version' module ValidatesEmailFormatOf def self.load_i18n_locales require 'i18n' I18n.load_path += Dir.glob(File.expand_path(File.join(File.dirname(__FILE__), '..', 'config', 'locales', '*.yml'))) end require 'resolv' LocalPartSpecialChars = /[\!\#\$\%\&\'\*\-\/\=\?\+\-\^\_\`\{\|\}\~]/ def self.validate_email_domain(email) - domain = email.match(/\@(.+)/)[1] + domain = email.to_s.downcase.match(/\@(.+)/)[1] Resolv::DNS.open do |dns| @mx = dns.getresources(domain, Resolv::DNS::Resource::IN::MX) + dns.getresources(domain, Resolv::DNS::Resource::IN::A) end @mx.size > 0 ? true : false end # Validates whether the specified value is a valid email address. Returns nil if the value is valid, otherwise returns an array # containing one or more validation error messages. # # Configuration options: # * <tt>message</tt> - A custom error message (default is: "does not appear to be valid") # * <tt>check_mx</tt> - Check for MX records (default is false) # * <tt>mx_message</tt> - A custom error message when an MX record validation fails (default is: "is not routable.") # * <tt>with</tt> The regex to use for validating the format of the email address (deprecated) # * <tt>local_length</tt> Maximum number of characters allowed in the local part (default is 64) # * <tt>domain_length</tt> Maximum number of characters allowed in the domain part (default is 255) DEFAULT_MESSAGE = "does not appear to be valid" DEFAULT_MX_MESSAGE = "is not routable" def self.default_message defined?(I18n) ? I18n.t(:invalid_email_address, :scope => [:activemodel, :errors, :messages], :default => DEFAULT_MESSAGE) : DEFAULT_MESSAGE end def self.validate_email_format(email, options={}) default_options = { :message => default_message, :check_mx => false, :mx_message => defined?(I18n) ? I18n.t(:email_address_not_routable, :scope => [:activemodel, :errors, :messages], :default => DEFAULT_MX_MESSAGE) : DEFAULT_MX_MESSAGE, :domain_length => 255, :local_length => 64 } opts = options.merge(default_options) {|key, old, new| old} # merge the default options into the specified options, retaining all specified options email = email.strip if email begin domain, local = email.reverse.split('@', 2) rescue return [ opts[:message] ] end # need local and domain parts return [ opts[:message] ] unless local and not local.empty? and domain and not domain.empty? # check lengths return [ opts[:message] ] unless domain.length <= opts[:domain_length] and local.length <= opts[:local_length] local.reverse! domain.reverse! if opts.has_key?(:with) # holdover from versions <= 1.4.7 return [ opts[:message] ] unless email =~ opts[:with] else return [ opts[:message] ] unless self.validate_local_part_syntax(local) and self.validate_domain_part_syntax(domain) end if opts[:check_mx] and !self.validate_email_domain(email) return [ opts[:mx_message] ] end return nil # represents no validation errors end def self.validate_local_part_syntax(local) in_quoted_pair = false in_quoted_string = false (0..local.length-1).each do |i| ord = local[i].ord # accept anything if it's got a backslash before it if in_quoted_pair in_quoted_pair = false next end # backslash signifies the start of a quoted pair if ord == 92 and i < local.length - 1 return false if not in_quoted_string # must be in quoted string per http://www.rfc-editor.org/errata_search.php?rfc=3696 in_quoted_pair = true next end # double quote delimits quoted strings if ord == 34 in_quoted_string = !in_quoted_string next end next if local[i,1] =~ /[a-z0-9]/i next if local[i,1] =~ LocalPartSpecialChars # period must be followed by something if ord == 46 return false if i == 0 or i == local.length - 1 # can't be first or last char next unless local[i+1].ord == 46 # can't be followed by a period end return false end return false if in_quoted_string # unbalanced quotes return true end def self.validate_domain_part_syntax(domain) parts = domain.downcase.split('.', -1) return false if parts.length <= 1 # Only one domain part # Empty parts (double period) or invalid chars return false if parts.any? { |part| part.nil? or part.empty? or not part =~ /\A[[:alnum:]\-]+\Z/ or part[0,1] == '-' or part[-1,1] == '-' # hyphen at beginning or end of part } # ipv4 return true if parts.length == 4 and parts.all? { |part| part =~ /\A[0-9]+\Z/ and part.to_i.between?(0, 255) } return false if parts[-1].length < 2 or not parts[-1] =~ /[a-z\-]/ # TLD is too short or does not contain a char or hyphen return true end end require 'validates_email_format_of/active_model' if defined?(::ActiveModel) && !(ActiveModel::VERSION::MAJOR < 2 || (2 == ActiveModel::VERSION::MAJOR && ActiveModel::VERSION::MINOR < 1)) require 'validates_email_format_of/railtie' if defined?(::Rails)
validates-email-format-of/validates_email_format_of
e6c8b406cfc76122344885579520899b216dbfb7
removed unneeded code from Rakefile
diff --git a/rakefile.rb b/rakefile.rb index f0fb986..c702cfc 100644 --- a/rakefile.rb +++ b/rakefile.rb @@ -1,29 +1 @@ -require 'bundler' -Bundler::GemHelper.install_tasks - -require 'rake/testtask' -require 'rdoc/task' - -desc 'Default: run unit tests.' -task :default => [:clean_log, :test] - -desc 'Remove the old log file' -task :clean_log do - "rm -f #{File.dirname(__FILE__)}/test/debug.log" if File.exists?(File.dirname(__FILE__) + '/test/debug.log') -end - -desc 'Test the validates_email_format_of plugin.' -Rake::TestTask.new(:test) do |t| - t.libs << 'lib' - t.pattern = FileList['test/**/*_test.rb'] - t.verbose = true -end - -desc 'Generate documentation for the validates_email_format_of plugin and gem.' -RDoc::Task.new do |rdoc| - rdoc.rdoc_dir = 'rdoc' - rdoc.title = 'validates_email_format_of plugin and gem' - rdoc.options << '--line-numbers --inline-source' - rdoc.rdoc_files.include('README.rdoc') - rdoc.rdoc_files.include('lib/**/*.rb') -end +require 'bundler/gem_tasks'
validates-email-format-of/validates_email_format_of
7974daffc1971c7055874f94cc3ec087d060e202
added Rspec custom matcher -- fixes #24
diff --git a/README.rdoc b/README.rdoc index 263f0b2..a85c35e 100644 --- a/README.rdoc +++ b/README.rdoc @@ -1,90 +1,96 @@ = validates_email_format_of Gem and Rails Plugin Validate e-mail addresses against RFC 2822 and RFC 3696. == Installation Installing as a gem: gem install validates_email_format_of Or in your Gemfile: gem 'validates_email_format_of' == Usage # Rails # I18n locales are loaded automatically. class Person < ActiveRecord::Base validates_email_format_of :email, :message => 'is not looking good' # OR validates :email, :email_format => { :message => 'is not looking good' } end + # Now you can test your model using RSpec: + require "validates_email_format_of/rspec_matcher" + describe Person do + it { should validate_email_format_of(:email).with_message('is not looking good') } + end + # If you're not using Rails (which really means, if you're not using ActiveModel::Validations) ValidatesEmailFormatOf::load_i18n_locales # Optional, if you want error messages to be in your language I18n.locale = :pl # If, for example, you want Polish error messages. ValidatesEmailFormatOf::validate_email_format("example@mydomain.com") # => nil ValidatesEmailFormatOf::validate_email_format("invalid_because_there_is_no_at_symbol") # => ["does not appear to be a valid e-mail address"] === Options :message String. A custom error message when the email format is invalid (default is: "does not appear to be a valid e-mail address") :check_mx Boolean. Check domain for a valid MX record (default is false) :mx_message String. A custom error message when the domain does not match a valid MX record (default is: "is not routable"). Ignored unless :check_mx option is true. :local_length Maximum number of characters allowed in the local part (everything before the '@') (default is 64) :domain_length Maximum number of characters allowed in the domain part (everything after the '@') (default is 255) :with Specify a custom Regex as the valid email format. :on, :if, :unless, :allow_nil, :allow_blank, :strict Standard ActiveModel validation options. These work in the ActiveModel/ActiveRecord/Rails syntax only. See http://api.rubyonrails.org/classes/ActiveModel/Validations/ClassMethods.html#method-i-validates for details. == Testing To execute the unit tests run <tt>rspec</tt>. Tested in Ruby 1.8.7, 1.9.2, 1.9.3, 2.0.0, 2.1.2, JRuby and REE 1.8.7. == Contributing If you think we're letting some rules about valid email formats slip through the cracks, don't just update the Regex. Instead, add a failing test, and demonstrate that the described email address should be treated differently. A link to an appropriate RFC is the best way to do this. Then change the gem code to make the test pass. describe "i_think_this_is_not_a_v@lid_email_addre.ss" do # According to http://..., this email address IS NOT valid. it { should have_errors_on_email.because("does not appear to be valid") } end describe "i_think_this_is_a_v@lid_email_addre.ss" do # According to http://..., this email address IS valid. it { should_not have_errors_on_email } end Yes, our Rspec syntax is that simple! == Homepage * https://github.com/validates-email-format-of/validates_email_format_of == Credits Written by Alex Dunae (dunae.ca), 2006-11. Many thanks to the plugin's recent contributors: https://github.com/alexdunae/validates_email_format_of/contributors Thanks to Francis Hwang (http://fhwang.net/) at Diversion Media for creating the 1.1 update. Thanks to Travis Sinnott for creating the 1.3 update. Thanks to Denis Ahearn at Riverock Technologies (http://www.riverocktech.com/) for creating the 1.4 update. Thanks to George Anderson (http://github.com/george) and 'history' (http://github.com/history) for creating the 1.4.1 update. Thanks to Isaac Betesh (https://github.com/betesh) for converting tests to Rspec and refactoring for version 1.6.0. diff --git a/lib/validates_email_format_of/rspec_matcher.rb b/lib/validates_email_format_of/rspec_matcher.rb new file mode 100644 index 0000000..5b1aff6 --- /dev/null +++ b/lib/validates_email_format_of/rspec_matcher.rb @@ -0,0 +1,15 @@ +require "validates_email_format_of" + +RSpec::Matchers.define :validate_email_format_of do |attribute| + match do + actual_class_name = subject.is_a?(Class) ? subject : subject.class + actual = actual_class_name.new + actual.send(:"#{attribute}=", "invalid@example.") + expect(actual).to be_invalid + @expected_message ||= ValidatesEmailFormatOf.default_message + expect(actual.errors.messages[attribute.to_sym]).to include(@expected_message) + end + chain :with_message do |message| + @expected_message = message + end +end diff --git a/spec/rspec_matcher_spec.rb b/spec/rspec_matcher_spec.rb new file mode 100644 index 0000000..bc0496c --- /dev/null +++ b/spec/rspec_matcher_spec.rb @@ -0,0 +1,14 @@ +require "#{File.expand_path(File.dirname(__FILE__))}/spec_helper" +if defined?(ActiveModel) + require "validates_email_format_of/rspec_matcher" + + class Person + attr_accessor :email_address + include ::ActiveModel::Validations + validates_email_format_of :email_address + end + + describe Person do + it { should validate_email_format_of(:email_address) } + end +end
validates-email-format-of/validates_email_format_of
228c95614e9f5ac5046201289b370d05602fe832
moved loading of I18n into spec_helper so that it happens before any specs run
diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index f37dab1..36dec55 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,22 +1,29 @@ require 'active_model' if Gem.loaded_specs.keys.include?('activemodel') RSpec::Matchers.define :have_errors_on_email do match do |actual| expect(actual).not_to be_nil, "#{actual} should not be nil" expect(actual).not_to be_empty, "#{actual} should not be empty" expect(actual.size).to eq(@reasons.size), "#{actual} should have #{@reasons.size} elements" @reasons.each do |reason| reason = "#{"Email " if defined?(ActiveModel)}#{reason}" expect(actual).to include(reason), "#{actual} should contain #{reason}" end end chain :because do |reason| (@reasons ||= []) << reason end chain :and_because do |reason| (@reasons ||= []) << reason end match_when_negated do |actual| expect(actual).to (defined?(ActiveModel) ? be_empty : be_nil) end end + +RSpec.configure do |config| + config.before(:suite) do + ValidatesEmailFormatOf.load_i18n_locales + I18n.enforce_available_locales = false + end +end diff --git a/spec/validates_email_format_of_spec.rb b/spec/validates_email_format_of_spec.rb index 584a111..c5e2160 100644 --- a/spec/validates_email_format_of_spec.rb +++ b/spec/validates_email_format_of_spec.rb @@ -1,312 +1,308 @@ # -*- encoding : utf-8 -*- require "#{File.expand_path(File.dirname(__FILE__))}/spec_helper" require "validates_email_format_of" describe ValidatesEmailFormatOf do - before(:all) do - described_class.load_i18n_locales - I18n.enforce_available_locales = false - end subject do |example| if defined?(ActiveModel) user = Class.new do def initialize(email) @email = email.freeze end attr_reader :email include ActiveModel::Validations validates_email_format_of :email, example.example_group_instance.options end example.example_group_instance.class::User = user user.new(example.example_group_instance.email).tap(&:valid?).errors.full_messages else ValidatesEmailFormatOf::validate_email_format(email.freeze, options) end end let(:options) { {} } let(:email) { |example| example.example_group.description } shared_examples_for :all_specs do [ 'valid@example.com', 'Valid@test.example.com', 'valid+valid123@test.example.com', 'valid_valid123@test.example.com', 'valid-valid+123@test.example.co.uk', 'valid-valid+1.23@test.example.com.au', 'valid@example.co.uk', 'v@example.com', 'valid@example.ca', 'valid_@example.com', 'valid123.456@example.org', 'valid123.456@example.travel', 'valid123.456@example.museum', 'valid@example.mobi', 'valid@example.info', 'valid-@example.com', 'fake@p-t.k12.ok.us', # allow single character domain parts 'valid@mail.x.example.com', 'valid@x.com', 'valid@example.w-dash.sch.uk', # from RFC 3696, page 6 'customer/department=shipping@example.com', '$A12345@example.com', '!def!xyz%abc@example.com', '_somename@example.com', # apostrophes "test'test@example.com", # international domain names 'test@xn--bcher-kva.ch', 'test@example.xn--0zwm56d', 'test@192.192.192.1', # Allow quoted characters. Valid according to http://www.rfc-editor.org/errata_search.php?rfc=3696 '"Abc\@def"@example.com', '"Fred\ Bloggs"@example.com', '"Joe.\\Blow"@example.com', # Balanced quoted characters %!"example\\\\\\""@example.com!, %!"example\\\\"@example.com! ].each do |address| describe address do it { should_not have_errors_on_email } end end [ 'no_at_symbol', 'invalid@example-com', # period can not start local part '.invalid@example.com', # period can not end local part 'invalid.@example.com', # period can not appear twice consecutively in local part 'invali..d@example.com', # should not allow underscores in domain names 'invalid@ex_mple.com', 'invalid@e..example.com', 'invalid@p-t..example.com', 'invalid@example.com.', 'invalid@example.com_', 'invalid@example.com-', 'invalid-example.com', 'invalid@example.b#r.com', 'invalid@example.c', 'invali d@example.com', # TLD can not be only numeric 'invalid@example.123', # unclosed quote "\"a-17180061943-10618354-1993365053@example.com", # too many special chars used to cause the regexp to hang "-+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++@foo", 'invalidexample.com', # should not allow special chars after a period in the domain 'local@sub.)domain.com', 'local@sub.#domain.com', # one at a time "foo@example.com\nexample@gmail.com", 'invalid@example.', "\"foo\\\\\"\"@bar.com", "foo@mail.com\r\nfoo@mail.com", '@example.com', 'foo@', 'foo', 'Iñtërnâtiônàlizætiøn@hasnt.happened.to.email', # Escaped characters with quotes. From http://tools.ietf.org/html/rfc3696, page 5. Corrected in http://www.rfc-editor.org/errata_search.php?rfc=3696 'Fred\ Bloggs_@example.com', 'Abc\@def+@example.com', 'Joe.\\Blow@example.com', # Unbalanced quoted characters %!"example\\\\""example.com! ].each do |address| describe address do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe do shared_examples_for :local_length_limit do |limit| describe "#{'a' * limit}@example.com" do it { should_not have_errors_on_email } end describe "#{'a' * (limit + 1)}@example.com" do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "when using default" do it_should_behave_like :local_length_limit, 64 end describe "when overriding defaults" do let(:options) { { :local_length => 20 } } it_should_behave_like :local_length_limit, 20 end end describe do shared_examples_for :domain_length_limit do |limit| describe "user@#{'a' * (limit - 4)}.com" do it { should_not have_errors_on_email } end describe "user@#{'a' * (limit - 3)}.com" do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "when using default" do it_should_behave_like :domain_length_limit, 255 end describe "when overriding defaults" do let(:options) { { :domain_length => 100 } } it_should_behave_like :domain_length_limit, 100 end end describe "custom error messages" do describe 'invalid@example.' do let(:options) { { :message => "just because I don't like you" } } it { should have_errors_on_email.because("just because I don't like you") } end end describe "mx record" do domain = "stubbed.com" email = "valid@#{domain}" describe "when testing" do let(:dns) { double(Resolv::DNS) } let(:mx_record) { [double] } let(:a_record) { [double] } before(:each) do allow(Resolv::DNS).to receive(:open).and_yield(dns) allow(dns).to receive(:getresources).with(domain, Resolv::DNS::Resource::IN::MX).once.and_return(mx_record) allow(dns).to receive(:getresources).with(domain, Resolv::DNS::Resource::IN::A).once.and_return(a_record) end let(:options) { { :check_mx => true } } describe "and only an mx record is found" do let(:a_record) { [] } describe email do it { should_not have_errors_on_email } end end describe "and only an a record is found" do let(:mx_record) { [] } describe email do it { should_not have_errors_on_email } end end describe "and both an mx record and an a record are found" do describe email do it { should_not have_errors_on_email } end end describe "and neither an mx record nor an a record is found" do let(:a_record) { [] } let(:mx_record) { [] } describe email do it { should have_errors_on_email.because("is not routable") } end describe "with a custom error message" do let(:options) { { :check_mx => true, :mx_message => "There ain't no such domain!" } } describe email do it { should have_errors_on_email.because("There ain't no such domain!") } end end describe "i18n" do before(:each) { allow(I18n.config).to receive(:locale).and_return(locale) } describe "present locale" do let(:locale) { :pl } describe email do it { should have_errors_on_email.because("jest nieosiągalny") } end end describe email do let(:locale) { :ir } describe email do it { should have_errors_on_email.because("is not routable") } end end end unless defined?(ActiveModel) describe "without i18n" do before(:each) { hide_const("I18n") } describe email do it { should have_errors_on_email.because("is not routable") } end end end end end describe "when not testing" do before(:each) { allow(Resolv::DNS).to receive(:open).never } describe "by default" do describe email do it { should_not have_errors_on_email } end end describe "explicitly" do describe email do let(:options) { { :check_mx => false } } it { should_not have_errors_on_email } end end end describe "without mocks" do describe email do let(:options) { { :check_mx => true } } it { should_not have_errors_on_email } end end end describe "custom regex" do let(:options) { { :with => /[0-9]+\@[0-9]+/ } } describe '012345@789' do it { should_not have_errors_on_email } end describe 'valid@example.com' do it { should have_errors_on_email.because("does not appear to be a valid e-mail address") } end end describe "i18n" do before(:each) { allow(I18n.config).to receive(:locale).and_return(locale) } describe "present locale" do let(:locale) { :pl } describe "invalid@exmaple." do it { should have_errors_on_email.because("nieprawidłowy adres e-mail") } end end describe "missing locale" do let(:locale) { :ir } describe "invalid@exmaple." do it { should have_errors_on_email.because("does not appear to be valid") } end end end unless defined?(ActiveModel) describe "without i18n" do before(:each) { hide_const("I18n") } describe "invalid@exmaple." do it { should have_errors_on_email.because("does not appear to be valid") } end end end end it_should_behave_like :all_specs if defined?(ActiveModel) describe "shorthand ActiveModel validation" do subject do |example| user = Class.new do def initialize(email) @email = email.freeze end attr_reader :email include ActiveModel::Validations validates :email, :email_format => example.example_group_instance.options end example.example_group_instance.class::User = user user.new(example.example_group_instance.email).tap(&:valid?).errors.full_messages end it_should_behave_like :all_specs end end end