upnp.lisp 16.2 KB
Newer Older
1 2 3 4 5 6
(in-package :xelf)

;;; Minimal UPnP support for talking to home router.
;;;  see RFC's 6970, 4787, 5405

(defparameter *upnp-udp-port* 1900)
7
(defparameter *upnp-local-host* nil)
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
(defvar *upnp-external-ip* nil)
(defvar *upnp-external-ip-requested-p* nil)
(defparameter *upnp-mapping-response* nil)
(defparameter *upnp-mapping-response-string* "u:AddPortMappingResponse")
(defparameter *upnp-gateway-search-string* "urn:schemas-upnp-org:device:InternetGatewayDevice:1")
(defparameter *upnp-service-search-string* "urn:schemas-upnp-org:service:WANIPConnection:1")
(defparameter *upnp-ok-string* "HTTP/1.1 200 OK")
(defparameter *upnp-internal-server-error-string* "HTTP/1.1 500")
(defparameter *upnp-root-device-string* "upnp:rootdevice")
(defparameter *upnp-gateway-device-urn* "urn:schemas-upnp-org:device:InternetGatewayDevice")
(defparameter *upnp-gateway-device-string* "device:InternetGatewayDevice")
(defparameter *upnp-external-ip-prefix* "<NewExternalIPAddress>")
(defparameter *upnp-error-code-prefix* "<errorCode>")
(defparameter *upnp-failure-prefix* "ActionFailed")
(defparameter *upnp-location-prefix* "Location:")
(defparameter *upnp-broadcast-address* "239.255.255.250")
(defvar *upnp-control-url* nil)
(defvar *upnp-control-url-requested-p* nil)

(defvar *upnp-host* nil)
(defvar *upnp-external-ip* nil)
(defvar *upnp-root* nil)
(defvar *upnp-root-port* nil)
(defvar *upnp-location* nil)
(defvar *upnp-mapping-requested-p* nil)

(defvar *upnp-socket* nil)
(defvar *upnp-broadcast-socket* nil)
(defvar *upnp-message* nil)
(defvar *upnp-sent-p* nil)
(defvar *upnp-received-p* nil)
(defvar *upnp-error-code* nil)

(defvar *upnp-listen-host* nil)
(defvar *upnp-listen-port* nil)

(defvar *use-upnp* nil)
(defun upnp-p ()
  *use-upnp*)

(defun reset-upnp ()
  (when *upnp-socket* 
    (usocket:socket-close *upnp-socket*))
  (setf *upnp-socket* nil)
  (when *upnp-broadcast-socket* 
    (usocket:socket-close *upnp-broadcast-socket*))
  (setf *upnp-broadcast-socket* nil)
  (setf *upnp-host* nil)
  (setf *upnp-mapping-response* nil)
  (setf *upnp-location* nil)
  (setf *upnp-listen-host* nil)
59
  (setf *upnp-local-host* nil)
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
  (setf *upnp-control-url* nil)
  (setf *upnp-control-url-requested-p* nil)
  (setf *upnp-listen-port* nil)
  (setf *upnp-root* nil)
  (setf *upnp-root-port* nil)
  (setf *upnp-message* nil)
  (setf *upnp-sent-p* nil)
  (setf *upnp-received-p* nil)
  (setf *upnp-external-ip* nil)
  (setf *upnp-external-ip-requested-p* nil)
  (setf *upnp-mapping-requested-p* nil)
  (setf *upnp-error-code* nil))

(defun scrape-string (line tag)
  (let ((p (search tag line)))
    (when (numberp p)
      (subseq line (+ p (length tag))))))

(defun scrape-message (message tag)
  (some #'(lambda (line) 
	    (scrape-string line tag))
	(split-string-on-lines message)))

(defun scrape-ok (message)
  (scrape-message message *upnp-ok-string*))

(defun register-ok (message)
  (when (scrape-ok message)
    (logging "UPnP: Received OK...")))

(defun scrape-root-device (message)
  (scrape-message message *upnp-root-device-string*))
  
(defun scrape-root-ip-and-port (message)
  (let ((location (or (scrape-message message *upnp-location-prefix*)
		      (scrape-message message "LOCATION:"))))
    (when location
David O'Toole's avatar
David O'Toole committed
97
      (let* ((digit (position-if #'digit-char-p location))
98 99 100 101 102 103 104 105 106
	     (ip+ (subseq location digit))
	     (colon (when digit (position #\: ip+)))
	     (ip (when colon (subseq ip+ 0 colon)))
	     (port+ (when colon (subseq location (+ colon digit 1))))
	     (slash (when port+ (position #\/ port+)))
	     (port (when slash (subseq port+ 0 slash)))
	     (short-url (when slash (subseq port+ slash))))
	(when (and colon slash)
	  (when port 
David O'Toole's avatar
David O'Toole committed
107
	      (let ((port-number (parse-integer port)))
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
		(when (numberp port-number)
		  (values 
		   (remove-control-characters ip)
		   port-number
		   (remove-control-characters location))))))))))

(defun clean-location-string (string)
  (let ((h (position #\h string))
	(len (length string)))
    (if h
	(subseq string h (- len 1))
	string)))

(defun register-root-device (message &optional force) 
  (let ((root (scrape-root-device message)))
    (when root 
      (when (or force 
	        (and (null *upnp-root*)
		     (not (scrape-message message "Microsoft"))))
		     ;; (scrape-message message *upnp-gateway-device-string*)))
	(multiple-value-bind (ip port location) (scrape-root-ip-and-port message)
	  (setf *upnp-root* ip 
		*upnp-root-port* port
		*upnp-location* location)
	  (logging "UPnP: Registering root device ~A port ~A..." 
		   *upnp-root* *upnp-root-port*)
	  (logging "UPnP: Server location ~A" location))))))

(defun scrape-error-code (message)
  (scrape-message message *upnp-error-code-prefix*))

(defun register-error-code (message)
  (let ((code (scrape-error-code message)))
    (when code 
      (setf *upnp-error-code*
	    (or code *upnp-error-code*))
      (logging "UPnP: Received error ~S" code))))

(defun register-external-ip (message)
  (let ((ip (scrape-external-ip message)))
    (when ip
      (setf *upnp-external-ip* ip)
      (logging "UPnP: Found external IP address: ~A" ip)))) 

(defun crlf ()
  (with-output-to-string (s) 
    (write-char #\return s)
    (write-char #\linefeed s)))

(defun terminate-line (line)
  (concatenate 'string line (crlf)))

(defun terminate-message (message)
  (concatenate 'string message (crlf)))

(defun format-upnp-message (text)
  (terminate-message
   (apply #'concatenate 'string 
	  (mapcar #'terminate-line
		  (split-string-on-lines text)))))

(defun tagify (tag value)
David O'Toole's avatar
David O'Toole committed
170
  (format nil "<~A>~A</~A>~%" tag value tag))
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294

(defun upnp-discovery-message (&optional search)
  (format nil "M-SEARCH * HTTP/1.1
Host:239.255.255.250:1900
ST:~A
Man:\"ssdp:discover\"
MX:3" search))

(defun make-discovery-request (&optional (search *upnp-root-device-string*))
  (upnp-discovery-message search))

(defun format-upnp-url (url)
  (if (scrape-string url "://") 
      url
      (format nil "http://~A:~A~A" 
	      *upnp-root*
	      *upnp-root-port*
	      url)))

(defun external-ip-request-header (host length)
  (format nil
"POST ~A HTTP/1.1
Content-Type: text/xml; charset=\"utf-8\" 
SOAPACTION: \"urn:schemas-upnp-org:service:WANIPConnection:1#GetExternalIPAddress\"
Host: ~A
Content-Length: ~A
Connection: Close
Cache-Control: no-cache"
(format-upnp-url *upnp-control-url*)
host length))

(defun external-ip-request-body ()
"<?xml version=\"1.0\"?>
<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" soap:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\">
<soap:Body>
<m:GetExternalIPAddress xmlns:m=\"urn:schemas-upnp-org:service:WANIPConnection:1\"/>
</soap:Body>
</soap:Envelope>")

(defun make-external-ip-request (host)
  (let ((body (format-upnp-message (external-ip-request-body))))
    (concatenate 'string
		 (format-upnp-message (external-ip-request-header host (length body)))
		 body)))

(defun port-mapping-request-header (host length)
  (format nil
"POST ~A HTTP/1.1
Content-Type: text/xml; charset=\"utf-8\"
SOAPACTION: \"urn:schemas-upnp-org:service:WANIPConnection:1#AddPortMapping\"
User-Agent: SBCL/1.3 UPnP/1.1 XELF/3.1
Host: ~A:~A
Content-Length: ~S
Connection: Close
Cache-Control: no-cache
"
*upnp-control-url*
host *upnp-root-port* length))

(defun port-mapping-request-body 
    (&key remote-host external-port protocol 
	  internal-port internal-client 
	  enabled-p duration description)
  (concatenate 'string
"<?xml version=\"1.0\"?>
<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">
<soap:Body>
<m:AddPortMapping xmlns:m=\"urn:schemas-upnp-org:service:WANIPConnection:1\">
"
(tagify "NewRemoteHost" remote-host)
(tagify "NewExternalPort" external-port)
(tagify "NewProtocol" protocol)
(tagify "NewInternalPort" internal-port)
(tagify "NewInternalClient" internal-client)
(tagify "NewEnabled" enabled-p)
(tagify "NewLeaseDuration" duration)
(tagify "NewPortMappingDescription" description)
"</m:AddPortMapping>
</soap:Body>
</soap:Envelope>"))

(defun make-port-mapping-request (host args)
  (let ((body (format-upnp-message (apply #'port-mapping-request-body args))))
     (concatenate 'string
		  (format-upnp-message 
		   (port-mapping-request-header host (length body)))
		  body)))

(defun describe-socket (socket &optional remotep)
  (let ((text (prin1-to-string socket)))
    (logging "Inspecting socket ~S..."
	     (subseq text 0 (min 60 (length text)))))
  (let ((local-port (usocket:get-local-port socket))
	(local-address (usocket:get-local-address socket)))
    (logging "  local-address:   ~S" local-address)
    (logging "  local-port:      ~S" local-port))
  (when remotep
    (let ((peer-port (usocket:get-peer-port socket))
	  (peer-address (usocket:get-peer-address socket)))
      (logging "  peer-address:   ~S" peer-address)
      (logging "  peer-port:      ~S" peer-port)))
  socket)

(defun open-upnp-broadcast ()
  (setf *upnp-broadcast-socket*
	(usocket:socket-connect nil nil
				:protocol :datagram
				:timeout 0
				:element-type '(unsigned-byte 8)
				:local-host usocket:*wildcard-host*))
  (setf (usocket:socket-option *upnp-broadcast-socket* :broadcast) t))

(defun send-upnp-broadcast (message)
  (usocket:socket-send *upnp-broadcast-socket*
		       message 
		       (length message) 
		       :port *upnp-udp-port*
		       :host *upnp-broadcast-address*))

(defun open-upnp-socket ()
  (setf *upnp-socket*
	(usocket:socket-connect *upnp-root* *upnp-root-port* 
				:protocol :stream
				:timeout 5
295 296 297 298 299
				:element-type 'character))
  (setf *upnp-local-host* 
	(expand-ip-vector
	 (usocket:get-local-address *upnp-socket*))))

300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
;;				:local-port *upnp-root-port*)))

(defun upnp-message-ready-p (socket)
  (when socket
    (usocket:wait-for-input socket :timeout 0 :ready-only t)))

(defun find-upnp-host () 
  (or *upnp-host* *upnp-broadcast-address*))

(defun send-upnp-message (message &optional (host (find-upnp-host)) (socket *upnp-socket*) (port *upnp-udp-port*))
  (let ((message2 (format-upnp-message message)))
    (usocket:socket-send socket message2 (length message2) :port port :host host)))

(defun send-upnp-request (message)
  (let ((stream (usocket:socket-stream *upnp-socket*)))
    (write-sequence message stream)
    (write-sequence message *standard-output*)
    (force-output stream)))
  
(defun send-discovery-request ()
  (send-upnp-message 
   (make-discovery-request)
   *upnp-broadcast-address*
   *upnp-broadcast-socket*))

(defun make-xml-request (url)
  (format-upnp-message
   (format nil "GET ~A HTTP/1.1
User-Agent: SBCL/1.3 UPnP/1.1 XELF/3.1
" url)))

(defun send-xml-request ()
  (send-upnp-request
   (make-xml-request *upnp-location*)))

(defun send-external-ip-request ()
  (send-upnp-request 
   (make-external-ip-request *upnp-root*)))

339 340 341 342 343
(defun expand-ip-vector (vector)
  (let ((octets (coerce vector 'list)))
    (destructuring-bind (a b c d) octets
      (format nil "~S.~S.~S.~S" a b c d))))

344
(defun record-upnp-message (message host port)
345 346 347
  (setf *upnp-host* (etypecase host
		      (string host)
		      (vector (expand-ip-vector host))))
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
  (setf *upnp-listen-port* port)
  (setf *upnp-message* message))

(defun scrape-control-url (message)
  (or (scrape-string message "<controlURL>")
      (scrape-string message "<controlurl>")
      (scrape-string message "<CONTROLURL>")
      (scrape-string message "<ControlUrl>")))

(defun register-xml (message)
  (let ((field (scrape-string message *upnp-service-search-string*)))
    (when field
      (logging "UPnP: Received XML with WANIPConnection service ID.")
      (when (not *upnp-external-ip-requested-p*)
	(if (scrape-message message *upnp-gateway-device-urn*)
	    (logging "UPnP: Found Gateway device URN.")
	    (logging "UPnP: Warning: Did not find Gateway device URN."))
	(when *upnp-root*
	  (if (scrape-message message *upnp-root*)
	      (logging "UPnP: Found existing root device IP here.")
	      (logging "UPnP: Warning: Did not find existing root device IP."))))
      (let ((url-begin (scrape-control-url field)))
	(when url-begin
	  (logging "Found URL begin tag.")
David O'Toole's avatar
David O'Toole committed
372 373
	  (let ((end (position-if (lambda (c) (find c #(#\< #\Return #\Newline)))
				  url-begin)))
374 375 376 377 378 379 380 381 382 383 384
	    (when end
	      (setf *upnp-control-url* 
		    (subseq url-begin 0 end))
	      (logging "Extracted ControlURL: ~A" *upnp-control-url*))))))))

(defun register-mapping-response (message)
  (when (and (scrape-message message "HTTP")
	     (scrape-message message "Error"))
    (logging "UPnP: Received HTTP Error. Text sent to stdout."))
  (when (and (scrape-message message *upnp-mapping-response-string*)
	     (scrape-message message *upnp-ok-string*))
385
    (logging "UPnP: Received <AddPortMappingResponse> OK")
David O'Toole's avatar
David O'Toole committed
386
    (logging "UPnP FINISHED. PRESS [ENTER] TO BEGIN ONLINE PLAY.")))
387 388 389 390 391 392

(defun register-external-ip-response (message)
    (when (scrape-message message *upnp-ok-string*)
      (let ((ip+ (scrape-string message *upnp-external-ip-prefix*)))
	(when ip+
	  (logging "UPnP: Found <NewExternalIpAddress> tag.")
David O'Toole's avatar
David O'Toole committed
393 394
	  (let ((end (position-if (lambda (c) (find c #(#\< #\Return #\Newline)))
				  ip+)))
395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
	    (when end
	      (logging "UPnP: Found External IP response: ~S"
		       (setf *upnp-external-ip* (subseq ip+ 0 end)))))))))

(defun process-upnp-message (message)
  (register-xml message)
  (register-root-device message)
  (register-error-code message)
  (register-ok message)
  (when *upnp-mapping-requested-p*
    (register-mapping-response message))
  (when *upnp-external-ip-requested-p*
    (register-external-ip-response message)))

(defun process-upnp-messages (socket)
  (loop while (upnp-message-ready-p socket) do
    (multiple-value-bind (octets length host port)
	(usocket:socket-receive socket *datagram* *datagram-length*)
      (record-upnp-message (babel:octets-to-string 
			    (subseq *datagram* 0 length))
			   host port)
      (process-upnp-message *upnp-message*))))

(defun snarf (stream)
  (with-output-to-string (s)
    (block reading
      (let (line)
	(loop while (setf line (read-line stream nil :eof))
	      do (if (eq :eof line)
		     (return-from reading)
		     (write-line line s)))))))

(defun process-upnp-stream (socket)
  (when (usocket:wait-for-input socket :timeout 0 :ready-only t)
    (let ((stream (usocket:socket-stream socket)))
      (let ((message (snarf stream)))
	(when (plusp (length message))
432
	  (record-upnp-message message *upnp-host* 0)
433 434 435 436 437 438 439 440
	  (process-upnp-message message))))))

(defparameter *port-mapping-duration* 0)

(defun port-mapping-arguments ()
  (list :remote-host ""
	:external-port *server-port*
	:internal-port *server-port*
441
	:internal-client *upnp-local-host*
442 443 444 445 446 447 448
	:protocol "UDP"
	:enabled-p 1
	:description "xelf:nat:upnp"
	:duration *port-mapping-duration*))

(defun send-port-mapping-request ()
  (let ((request (make-port-mapping-request
449
		  *upnp-local-host*
450
		  (port-mapping-arguments))))
David O'Toole's avatar
David O'Toole committed
451
    (prin1 request)
452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502
    (send-upnp-request request)))

(defun initialize-upnp ()
  (logging "UPnP: Initializing...")
  (reset-upnp)
  (logging "UPnP: Opening broadcast socket...")
  (open-upnp-broadcast)
  (describe-socket *upnp-broadcast-socket*)
  (logging "UPnP: Sending discovery request.")
  (send-discovery-request)
  (send-discovery-request))

(defun update-upnp ()
  (process-upnp-messages *upnp-broadcast-socket*)
  (when *upnp-socket* 
    (process-upnp-stream *upnp-socket*))
  (when (and *upnp-host* 
	     *upnp-location*
	     *upnp-socket*
	     (null *upnp-control-url-requested-p*)
	     (null *upnp-control-url*))
    (logging "UPnP: Requesting XML...")
    (send-xml-request)
    (setf *upnp-control-url-requested-p* t))
  (when (and *upnp-host*
	     (not *upnp-control-url-requested-p*)
	     (not *upnp-control-url*)
	     (not *upnp-mapping-requested-p*))
    (logging "UPnP: Opening gateway socket...")
    (when *upnp-socket* (usocket:socket-close *upnp-socket*))
    (open-upnp-socket)
    (describe-socket *upnp-socket* t))
  (when (and *upnp-host*
	     (not *upnp-external-ip-requested-p*)
	     *upnp-control-url*)
    (when *upnp-socket* (usocket:socket-close *upnp-socket*))
    (open-upnp-socket)
    (describe-socket *upnp-socket* t)
    (logging "UPnP: Sending external IP request...")
    (send-external-ip-request)
    (setf *upnp-external-ip-requested-p* t))
  (when (and *upnp-host*
	     (not *upnp-mapping-requested-p*)
	     *upnp-external-ip*)
    (when *upnp-socket* (usocket:socket-close *upnp-socket*))
    (open-upnp-socket)
    (describe-socket *upnp-socket* t)
    (logging "UPnP: Sending port map request...")
    (send-port-mapping-request)
    (setf *upnp-mapping-requested-p* t)))