summaryrefslogtreecommitdiffabout
path: root/examples/whoisd.scm
blob: a5bb68eb042dff5a49838ddc459bca18ca3d1146 (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
#! /usr/local/bin/guile -s
!#
;;;; This is Scheme whoisd daemon
;;;; Copyright (C) 2002, 2007, 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/>.
;;;;

(set! %load-path (append %load-path (list "/usr/local/share/guile-sql")))
(use-modules (ice-9 getopt-long))
(use-modules (ice-9 format))
(use-modules (sql))

;;; User-definable variables
(define sql-iface "mysql")
(define sql-host "")
(define sql-port 3306)
(define sql-database "whois")
(define sql-username "whois")
(define sql-password "secret")
(define base-domain-list (list "domain.com" "domain.net"))
;;; End of user-definable variables

(define progname "whoisd")
(define debug-level 0)

(define (debug level . text)
  (if (<= level debug-level)
        (map (lambda (x)
               (display x (current-error-port)))
             (append
              (list
               (if foreground-mode
                   progname
                   (strftime "%c" (localtime (current-time))))
               ":debug:" (number->string level) ": ")
              text
              (list "\n")))))

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

(define (display-list prefix data port)
  (for-each
   (lambda (x)
     (if (pair? x)
       (display-list prefix x port)
       (begin
         (display prefix port)
         (display ": " port)
         (display x port)
         (newline port))))
   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 port)
  (if text
      (display-list prefix (multiline->list text) port)))

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

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

(define (whois-query-primitive port conn key)
  (debug 2 "key " 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: " dom-res)
    (if (null? dom-res)
	#f
        (let ((dr (car dom-res)))
          (display "domain: " port)(display (car dr) port)(newline port)
          (display-multiline "descr" (list-ref dr 1) port)
          (display-multiline "remark" (list-ref dr 2) port)
          (display-list "admin-c" admin-c port)
          (display-list "tech-c" tech-c port)
          (display-list "zone-c" zone-c port)
          (display-list "nserver" nserver port)
          (display (string-append
                    "changed: "
                    (list-ref dr 5)
                    " "
                    (convert-date (list-ref dr 4))) port)
          (newline port)
          (display "source: " port)
          (display (list-ref dr 6) port)
          (newline port)
          (newline port)
          (force-output port)
	  #t)))) 

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

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

(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 port)
  (sigaction SIGALRM sigalrm-handler)
  (alarm whoisd-idle-timeout)
  (do ()
      ((char-ready? port) #f))
  (let ((value (read-line port)))
    (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 out command-list)
  (let ((args '())
	(key #f))
    (catch #t
	   (lambda ()
	     (for-each
	      (lambda (x)
		(cond
		 ((pair? x)
		  (case (car x)
		    ((help)
		     (whoisd-help out)
		     (throw 'whoisd-done))
		    ((less-specific)
		     (set! args (append args (list #:-L))))
		    (else
		     (cond
		      ((null? (car x))
		       (cond
			(key
			 (throw 'whoisd-extra-key))
			((null? (cdr x)) ); Continue
			((= (length (cdr x)) 1)
			 (set! key (cadr x)))
			(else
			 (throw 'whoisd-extra-key))))
		      (else
		       (throw 'whoisd-unknown-option))))))))
	      (getopt-long (cons "whoisd" command-list) whoisd-grammar))
	     
	     (let ((conn (sql-connect
			  sql-iface sql-host sql-port sql-database
			  sql-username sql-password)))
	       (cond
		(conn
		 (whois-query out conn key args)
		 (sql-connect-close conn))
		(else
		 (whois-error out 500 "Database is not available")))))

	   (lambda (key . args)
	     (case key
	       ((whoisd-unknown-option)
		(whois-error out 511 "Unknown option"))
	       ((whoisd-extra-key)
		(whois-error out 512 "Extra key"))
	       ((whoisd-done) ) ; Nothing
	       ('misc-error
		; FIXME:
		(whois-error out 513 (apply format args)))
	       (else
		; FIXME
		;(write key out)
		;(write args out)
		(debug 1 "EXCEPTION" args)
		(whois-error out 600 "Internal error. Please report to administrator")))))))

(define (whois-server in out . rest)
  (if (not (null? rest))
      (let ((conn-info (car rest)))
        (debug 1 "Connect from " (inet-ntoa (vector-ref conn-info 1)))))
  (let ((input (read-or-timeout in)))
    (if (not (string-null? input))
	(whoisd-run-command out (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 " (car pid) " terminated with code " (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)))
    (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)))
            (cond
             ((>= num-children max-children)
              (debug 1 "Too many connections active (" num-children ")")
              (whois-error (car conn) 501 "Too many connections active"))
             (else
              (let ((pid (primitive-fork)))
                (cond
                 ((= pid 0)
                  (close-port socket)
                  (whois-server (car conn) (car conn) (cdr conn))
                  (shutdown (car conn) 2)
                  (exit 0))
                 (else
                  (set! num-children (1+ num-children))
                  (debug 1 "Child " pid " started. Total "
                         num-children "."))))))
            (close-port (car conn)))))))

(define (whois-daemon)
  (close-all-ports-except (current-error-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 " 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))
    (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\
-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))))
       (else
	(cond
	 ((not (null? (cdr x)))
	  (whois-error (current-error-port) 500 "Command line usage")
	  (exit 1))))))
    (else
     (whois-error (current-error-port) 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)))

(if whois-standalone
   (whois-daemon)
   (whois-server (current-input-port) (current-output-port)))

Return to:

Send suggestions and report system problems to the System administrator.