summaryrefslogtreecommitdiffabout
path: root/examples/whoisd.scm
blob: 305dcba1e621dc71790a5a58aa2687e63d27763c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
#! /usr/local/bin/guile -s
!#
;;;; This is Scheme whoisd daemon
;;;; Copyright (C) 2002, 2007, 2010 Sergey Poznyakoff
;;;;
;;;; This program is free software; you can redistribute it and/or modify it
;;;; under the terms of the GNU General Public License as published by the
;;;; Free Software Foundation; either version 3 of the License, or (at your
;;;; option) any later version.
;;;;
;;;; This program is distributed in the hope that it will be useful,
;;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;;; GNU General Public License for more details.
;;;;
;;;; You should have received a copy of the GNU General Public License along
;;;; with this program. If not, see <http://www.gnu.org/licenses/>.
;;;;

(use-modules (ice-9 getopt-long)
	     (ice-9 format)
	     (ice-9 rdelim)
	     (gamma sql)
	     (gamma syslog))

;;; User-definable variables
(define sql-param
  (list
   (cons #:iface "mysql")
   (cons #:config-file "/etc/whoisd.cnf")
   (cons #:config-group "server")))

(define base-domain-list (list "domain.com" "domain.net"))
;;; End of user-definable variables

(define progname "whoisd")
(define debug-level 0)
(define debug-port (current-error-port))

(define (debug level fmt . rest)
  (if (<= level debug-level)
      (apply format debug-port fmt rest)))

(define (convert-date date)
  (string-append (substring date 0 4)
                 (substring date 5 7)
                 (substring date 8)))

(define (display-list prefix data)
  (for-each
   (lambda (x)
     (if (pair? x)
	 (display-list prefix x)
	 (begin
	   (display prefix)
	   (display ": ")
	   (display x)
	   (newline))))
   data))

(define (multiline->list str)
  (let loop ((fields '())
             (str str))
    (cond
     ((string-index str #\newline)
      => (lambda (w)
           (loop
            (append fields (list (substring str 0 w)))
            (substring str (1+ w)))))
     ((= (string-length str) 0)
      fields)
     (else
      (append fields (list str))))))

(define (whitespace? ch)
  (or
   (char=? ch #\space)
   (char=? ch #\ht)))

(define (string-empty? line)
  (do ((i 0 (+ i 1)))
      ((or
        (= i (string-length line))
        (not (whitespace? (string-ref line i))))
       (= i (string-length line)))))

(define (whitespace-index str ind)
  (let ((space (string-index str #\space ind))
        (ht (string-index str #\ht ind)))
    (if (and space ht)
        (min space ht)
        (or space ht))))

(define (word-index str ind)
  (let ((x (whitespace-index str ind)))
    (if x
        (do ((i x (+ i 1)))
            ((or
              (= i (string-length str))
              (not (whitespace? (string-ref str i))))
             i))
        ind)))

(define (string->list str)
  (let loop ((fields '())
             (ind (if (whitespace? (string-ref str 0))
                      (word-index str 0)
                      0)))
    (cond
     ((whitespace-index str ind)
      => (lambda (w)
           (loop
            (append fields (list (substring str ind w)))
            (word-index str ind))))
     ((= ind (string-length str))
      fields)
     (else
      (append fields (list (substring str ind (string-length str))))))))

(define (display-multiline prefix text)
  (if text
      (display-list prefix (multiline->list text))))

(define (whois-error code . text)
  (lambda ()
    (display-list (string-append "%ERROR:"
				 (number->string code))
		  text)))

(define (whois-warning code . text)
  (debug 1 "TEXT ~A~%" text)
  (display-list (string-append "%WARNING:"
                               (number->string code))
                text))

(define (whois-query-primitive conn key)
  (debug 2 "key ~A~%" key)
  (let ((dom-res (sql-query conn (string-append
                                  "SELECT \
domain,descr,remark,created,changed,changed_by,source \
FROM domain WHERE domain=\"" key "\"")))
        (admin-c (sql-query conn (string-append
                                  "SELECT contact FROM admin_c \
WHERE domain=\"" key "\"")))
        (tech-c (sql-query conn (string-append
                                 "SELECT contact FROM tech_c \
WHERE domain=\"" key "\"")))
        (zone-c (sql-query conn (string-append
                                 "SELECT contact FROM zone_c \
WHERE domain=\"" key "\"")))
        (nserver (sql-query conn (string-append
                                  "SELECT nserver FROM nserver \
WHERE domain=\"" key "\""))))
    (debug 2 "result: ~A~%" dom-res)
    (if (null? dom-res)
	#f
        (let ((dr (car dom-res)))
          (display "domain: ")
	  (display (car dr))
	  (newline)
	  
          (display-multiline "descr" (list-ref dr 1))
          (display-multiline "remark" (list-ref dr 2))
          (display-list "admin-c" admin-c)
          (display-list "tech-c" tech-c)
          (display-list "zone-c" zone-c)
          (display-list "nserver" nserver)
          (display (string-append
                    "changed: "
                    (list-ref dr 5)
                    " "
                    (convert-date (list-ref dr 4))))
          (newline)
          (display "source: ")
          (display (list-ref dr 6))
          (newline)
          (newline)
          (force-output)
	  #t)))) 

(define (whois-query conn key args)
  (let* ((keyval (string-downcase key))
	 (result (whois-query-primitive conn keyval)))
    (cond
     ((member #:-L args)
      (whois-warning 200
		     (string-append "Exact key " key " was not found.")
		     "Less specific matches follow")
	(if (not (do ((res (whois-query-primitive conn keyval)
			   (or (whois-query-primitive conn keyval) res)))
		     ((or (member keyval base-domain-list)
			  (begin
			    (set! keyval (strip-element keyval))
			    (not keyval)))
		      res)))
	    (whois-error 100 "No entries found")))
     ((not result)
      (whois-error 100 "No entries found")))))

(define (strip-element name)
  (let ((index (string-index name #\.)))
    (if index
	(substring name (1+ index))
	#f)))

(define log-facility LOG_DAEMON)
(define log-tag "whoisd")
(define whois-standalone #t)
(define single-process #f)
(define foreground-mode #f)
(define whois-address INADDR_ANY)
(define whois-port 43)
(define max-children 10)
(define num-children 0)

(define whoisd-idle-timeout 5)
(define whoisd-gid -1)
(define whoisd-uid -1)

(define whoisd-user "daemon")

(define (sigalrm-handler sig)
  (debug 1 "Timed out in waiting for input~%")
  (exit 1))

(define (strip-cr str)
  (let ((len (string-length str)))
    (if (char=? (string-ref str (- len 1)))
	(substring str 0 (- len 1))
	str)))

(define (read-or-timeout)
  (sigaction SIGALRM sigalrm-handler)
  (alarm whoisd-idle-timeout)
  (do ()
      ((char-ready?) #f))
  (let ((value (read-line)))
    (sigaction SIGALRM SIG_IGN)
    (strip-cr value)))

(define whoisd-grammar
  `((help (single-char #\H)
          (value #f))
    (less-specific (single-char #\L)
		   (value #f))))

(define (whoisd-help port)
  (with-output-to-port port
    (lambda ()
      (display "% WHOISD command line syntax:\n")
      (display "%\n")
      (display "% <domain-name>           Look for exact match\n")
      (display "% -L <domain-name>        Return all less-specific matches\n")
      (display "% -H                      Return this help summary\n"))))
  
(define (whoisd-run-command command-list)
  (debug 1 "whoisd-run-command ~S~%" command-list)
  
  (let ((args '())
	(key #f))
    (call-with-current-continuation
     (lambda (quit)
       (catch #t
	      (lambda ()
		(for-each
		 (lambda (x)
		   (debug 1 "Reading ~A~%" x)
		   (cond
		    ((pair? x)
		     (case (car x)
		       ((help)
			(whoisd-help)
			(quit))
		       ((less-specific)
			(set! args (append args (list #:-L))))
		       (else
			(cond
			 ((null? (car x))
			  (cond
			   (key
			    (error 'whoisd-error "whoisd-run-command"
				   "~A: ~A" (list "Extra key" key)
				   (list 512)))
			   ((null? (cdr x)) #f); Continue
			   ((= (length (cdr x)) 1)
			    (set! key (cadr x)))
			   (else
			    (error 'whoisd-error "whoisd-run-command"
				   "~A" (list "Extra key")
				   (list 512)))))
			 (else
			  (error 'whoisd-error "whoisd-run-command"
				 "~A" (list "Unknown option")
				 (list 511)))))))))
		 (getopt-long (cons "whoisd" command-list) whoisd-grammar))

		(let ((conn (sql-open-connection sql-param)))
		  (cond
		   (conn
		    (whois-query conn key args)
		    (sql-close-connection conn))
		   (else
		    (whois-error 500 "Database is not available")))))

	      (lambda (key func fmt args data)
		(debug 1 "Got error ~A ~S~%" fmt args)
		(with-output-to-port
		    (current-error-port)
		  (lambda ()
		    (apply format #t fmt args)
		    (newline)))
		(case key
		  ((whoisd-error)
		   (apply whois-error (car data) (format #f fmt args))))))))))

(define (whois-server . rest)
  (if (not (null? rest))
      (let ((conn-info (car rest)))
        (debug 1 "Connect from ~A~%" (inet-ntoa (vector-ref conn-info 1)))))
  (let ((input (read-or-timeout)))
    (if (not (string-null? input))
	(whoisd-run-command (string->list input)))))

(define (sigchld-handler sig)
  (catch 'system-error
         (lambda ()
           (do ((pid (waitpid WAIT_ANY WNOHANG) (waitpid WAIT_ANY WNOHANG)))
               ((= (car pid) 0) #f)
             (debug 1 "Child ~A terminated with code ~A~%" (car pid) (cdr pid))
             (set! num-children (1- num-children))))
         (lambda args #f)))


(define (ready-for-reading? fd)
  (catch 'system-error
         (lambda ()
           (let ((r (select (list fd) '() '()  1)))
             (member fd (car r))))
         (lambda args #f)))

(define (whois-mainloop)
  (let ((socket (socket AF_INET SOCK_STREAM 0)))
    (setsockopt socket SOL_SOCKET SO_REUSEADDR 1)
    (bind socket AF_INET whois-address whois-port)
    (if (not foreground-mode)
        (begin
         (setgid whoisd-gid)
         (setuid whoisd-uid)))
    (sigaction SIGCHLD sigchld-handler SA_RESTART)
    (listen socket 5)
    (do ()
        (#f #f)
      (if (or (= 0 num-children)
              (ready-for-reading? socket))
          (let* ((conn (accept socket))
		 (port (car conn)))
	    (with-output-to-port
		port
	      (lambda ()
		(cond
		 ((>= num-children max-children)
		  (debug 1 "Too many connections active (~A)~%" num-children)
		  (whois-error 501 "Too many connections active"))
		 (else
		  (let ((pid (primitive-fork)))
		    (cond
		     ((= pid 0)
		      (close-port socket)
		      (with-input-from-port
			  port
			(lambda ()
			  (whois-server (cdr conn))))
		      (shutdown (car conn) 2)
		      (exit 0))
		     (else
		      (set! num-children (1+ num-children))
		      (debug 1 "Child ~A started. Total children ~A~%"
			     pid num-children))))))))
            (close-port port))))))

(define (whois-daemon)
  (let ((kept-ports (list
		     debug-port
		     (current-error-port)
		     (current-output-port)
		     (current-input-port))))
    (port-for-each
     (lambda (port)
       (if (not (memq port kept-ports))
	   (close-port port)))))
  
  (sigaction SIGCHLD SIG_IGN)
  (case foreground-mode
    ((#f)
     (let ((pid (primitive-fork)))
       (cond
        ((= pid 0)
         (chdir "/")
         (setsid)
         (whois-mainloop))
        (else
         (debug 10 "Started child ~A~%" pid)
         (primitive-exit)))))
    ((#t)
     (whois-mainloop))))

(define grammar
  `((help (single-char #\h)
          (value #f))
    (single (single-char #\s)
            (value #f))
    (foreground (single-char #\f)
                (value #f))
    (debug (single-char #\x)
           (value #t))
    (tag (single-char #\L)
	 (value #t))
    (facility (single-char #\F)
	      (value #t))
    (inetd (single-char #\i)
           (value #f))
    (daemon (single-char #\d)
            (value #t))
    (ip-address (single-char #\a)
                (value #t))
    (port (single-char #\p)
          (value #t))
    (timeout (single-char #\t)
             (value #t))
    (user (single-char #\u)
          (value #t))))

(define (print-help)
  (display "\
Usage: whoisd [OPTIONS]\n\
whoisd -- The whois daemon.\n\
\n\
-h, --help               Display this help\n\
-x, --debug VALUE        Set debugging level\n\
-L, --tag TAG            Set syslog tag\n\
-F, --facility LF        Set syslog facility\n\
-t, --timeout            Set idle timeout for a request\n\
\n\
-i, --inetd              Run in inetd mode.\n\
\n\
-d, --daemon NUMBER      Run in daemon mode. Limit number of children spawned\n\
                         simultaneously to NUMBER. This is the default mode,\n\
                         NUMBER defaults to 10.\n\
\n\
The following options may be used in daemon mode only:\n\
\n\
-s, --single             Single-process mode: do not spawn children\n\
                         for handling requests.\n\
-f, --foreground         Stay in foreground.\n\
-a, --ip-address ADDRESS Listen on this IP address\n\
-p, --port NUMBER        Listen on this port number.\n\
-u, --user USER          Run with this user privileges. Default is \"daemon\"\n\
"))

;; Parse command line
(for-each
 (lambda (x)
   (cond
    ((pair? x)
     (case (car x)
       ((help)
	(print-help)
	(exit 0))
       ((port)
	(set! whois-port (string->number (cdr x))))
       ((ip-address)
	(set! whois-address (inet-aton (cdr x))))
       ((debug)
	(set! debug-level (string->number (cdr x))))
       ((daemon)
	(set! max-children (string->number (cdr x))))
       ((single)
	(set! single-process (cdr x)))
       ((foreground)
           (set! foreground-mode (cdr x)))
       ((user)
	(set! whoisd-user (cdr x)))
       ((timeout)
	(set! whoisd-idle-timeout (string->number (cdr x))))
       ((inetd)
	(set! whois-standalone (not (cdr x))))
       ((facility)
	(set! log-facility (eval-string (cdr x))))
       ((tag)
	(set! log-tag (cdr x)))
       (else
	(cond
	 ((not (null? (cdr x)))
	  (with-output-to-port
	      (current-error-port)
	    (lambda ()
	      (whois-error 500 "Command line usage")))
	  (exit 1))))))
    (else
     (with-output-to-port
	 (current-error-port)
       (lambda ()
	 (whois-error 500 "Command line usage: unexpected argument"))))))
 (getopt-long (command-line) grammar))

(let ((pwd (getpwnam whoisd-user)))
  (set! whoisd-uid (vector-ref pwd 2))
  (set! whoisd-gid (vector-ref pwd 3)))

(openlog (or log-tag (car (command-line))) LOG_PID log-facility)
(set! debug-port (open-syslog-port LOG_DEBUG))
(set-current-error-port (open-syslog-port LOG_ERR))
(set-current-output-port (open-syslog-port LOG_INFO))
(set-current-input-port (open-input-file "/dev/null"))

(if whois-standalone
    (whois-daemon)
    (whois-server))

Return to:

Send suggestions and report system problems to the System administrator.