Proper generation of Exim domainlists
[hcoop/domtool2.git] / src / main.sml
1 (* HCoop Domtool (http://hcoop.sourceforge.net/)
2 * Copyright (c) 2006, Adam Chlipala
3 *
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version 2
7 * of the License, or (at your option) any later version.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17 *)
18
19 (* Main interface *)
20
21 structure Main :> MAIN = struct
22
23 open Ast MsgTypes Print
24
25 structure SM = StringMap
26
27 fun init () = Acl.read Config.aclFile
28
29 fun check' G fname =
30 let
31 val prog = Parse.parse fname
32 in
33 if !ErrorMsg.anyErrors then
34 G
35 else
36 Tycheck.checkFile G (Defaults.tInit ()) prog
37 end
38
39 fun basis () =
40 let
41 val dir = Posix.FileSys.opendir Config.libRoot
42
43 fun loop files =
44 case Posix.FileSys.readdir dir of
45 NONE => (Posix.FileSys.closedir dir;
46 files)
47 | SOME fname =>
48 if String.isSuffix ".dtl" fname then
49 loop (OS.Path.joinDirFile {dir = Config.libRoot,
50 file = fname}
51 :: files)
52 else
53 loop files
54
55 val files = loop []
56 val (_, files) = Order.order NONE files
57 in
58 if !ErrorMsg.anyErrors then
59 Env.empty
60 else
61 (Tycheck.allowExterns ();
62 foldl (fn (fname, G) => check' G fname) Env.empty files
63 before Tycheck.disallowExterns ())
64 end
65
66 fun check fname =
67 let
68 val _ = ErrorMsg.reset ()
69 val _ = Env.preTycheck ()
70
71 val b = basis ()
72 in
73 if !ErrorMsg.anyErrors then
74 raise ErrorMsg.Error
75 else
76 let
77 val _ = Tycheck.disallowExterns ()
78 val _ = ErrorMsg.reset ()
79 val prog = Parse.parse fname
80 in
81 if !ErrorMsg.anyErrors then
82 raise ErrorMsg.Error
83 else
84 let
85 val G' = Tycheck.checkFile b (Defaults.tInit ()) prog
86 in
87 if !ErrorMsg.anyErrors then
88 raise ErrorMsg.Error
89 else
90 (G', #3 prog)
91 end
92 end
93 end
94
95 val notTmp = CharVector.all (fn ch => Char.isAlphaNum ch orelse ch = #"." orelse ch = #"_" orelse ch = #"-")
96
97 fun checkDir dname =
98 let
99 val b = basis ()
100
101 val dir = Posix.FileSys.opendir dname
102
103 fun loop files =
104 case Posix.FileSys.readdir dir of
105 NONE => (Posix.FileSys.closedir dir;
106 files)
107 | SOME fname =>
108 if notTmp fname then
109 loop (OS.Path.joinDirFile {dir = dname,
110 file = fname}
111 :: files)
112 else
113 loop files
114
115 val files = loop []
116 val (_, files) = Order.order (SOME b) files
117 in
118 if !ErrorMsg.anyErrors then
119 raise ErrorMsg.Error
120 else
121 (foldl (fn (fname, G) => check' G fname) b files;
122 if !ErrorMsg.anyErrors then
123 raise ErrorMsg.Error
124 else
125 ())
126 end
127
128 fun reduce fname =
129 let
130 val (G, body) = check fname
131 in
132 if !ErrorMsg.anyErrors then
133 NONE
134 else
135 case body of
136 SOME body =>
137 let
138 val body' = Reduce.reduceExp G body
139 in
140 (*printd (PD.hovBox (PD.PPS.Rel 0,
141 [PD.string "Result:",
142 PD.space 1,
143 p_exp body']))*)
144 SOME body'
145 end
146 | _ => NONE
147 end
148
149 fun eval fname =
150 case reduce fname of
151 (SOME body') =>
152 if !ErrorMsg.anyErrors then
153 raise ErrorMsg.Error
154 else
155 Eval.exec (Defaults.eInit ()) body'
156 | NONE => raise ErrorMsg.Error
157
158 fun eval' fname =
159 case reduce fname of
160 (SOME body') =>
161 if !ErrorMsg.anyErrors then
162 raise ErrorMsg.Error
163 else
164 ignore (Eval.exec' (Defaults.eInit ()) body')
165 | NONE => raise ErrorMsg.Error
166
167 val dispatcher =
168 Config.dispatcher ^ ":" ^ Int.toString Config.dispatcherPort
169
170 val self =
171 "localhost:" ^ Int.toString Config.slavePort
172
173 fun requestContext f =
174 let
175 val uid = Posix.ProcEnv.getuid ()
176 val user = Posix.SysDB.Passwd.name (Posix.SysDB.getpwuid uid)
177
178 val () = Acl.read Config.aclFile
179 val () = Domain.setUser user
180
181 val () = f ()
182
183 val context = OpenSSL.context (Config.certDir ^ "/" ^ user ^ ".pem",
184 Config.keyDir ^ "/" ^ user ^ "/key.pem",
185 Config.trustStore)
186 in
187 (user, context)
188 end
189
190 fun requestBio f =
191 let
192 val (user, context) = requestContext f
193 in
194 (user, OpenSSL.connect (context, dispatcher))
195 end
196
197 fun requestSlaveBio () =
198 let
199 val (user, context) = requestContext (fn () => ())
200 in
201 (user, OpenSSL.connect (context, self))
202 end
203
204 fun request fname =
205 let
206 val (user, bio) = requestBio (fn () => ignore (check fname))
207
208 val inf = TextIO.openIn fname
209
210 fun loop lines =
211 case TextIO.inputLine inf of
212 NONE => String.concat (List.rev lines)
213 | SOME line => loop (line :: lines)
214
215 val code = loop []
216 in
217 TextIO.closeIn inf;
218 Msg.send (bio, MsgConfig code);
219 case Msg.recv bio of
220 NONE => print "Server closed connection unexpectedly.\n"
221 | SOME m =>
222 case m of
223 MsgOk => print "Configuration succeeded.\n"
224 | MsgError s => print ("Configuration failed: " ^ s ^ "\n")
225 | _ => print "Unexpected server reply.\n";
226 OpenSSL.close bio
227 end
228 handle ErrorMsg.Error => ()
229
230 fun requestDir dname =
231 let
232 val _ = ErrorMsg.reset ()
233
234 val (user, bio) = requestBio (fn () => checkDir dname)
235
236 val b = basis ()
237
238 val dir = Posix.FileSys.opendir dname
239
240 fun loop files =
241 case Posix.FileSys.readdir dir of
242 NONE => (Posix.FileSys.closedir dir;
243 files)
244 | SOME fname =>
245 if notTmp fname then
246 loop (OS.Path.joinDirFile {dir = dname,
247 file = fname}
248 :: files)
249 else
250 loop files
251
252 val files = loop []
253 val (_, files) = Order.order (SOME b) files
254
255 val _ = if !ErrorMsg.anyErrors then
256 raise ErrorMsg.Error
257 else
258 ()
259
260 val codes = map (fn fname =>
261 let
262 val inf = TextIO.openIn fname
263
264 fun loop lines =
265 case TextIO.inputLine inf of
266 NONE => String.concat (rev lines)
267 | SOME line => loop (line :: lines)
268 in
269 loop []
270 before TextIO.closeIn inf
271 end) files
272 in
273 if !ErrorMsg.anyErrors then
274 ()
275 else
276 (Msg.send (bio, MsgMultiConfig codes);
277 case Msg.recv bio of
278 NONE => print "Server closed connection unexpectedly.\n"
279 | SOME m =>
280 case m of
281 MsgOk => print "Configuration succeeded.\n"
282 | MsgError s => print ("Configuration failed: " ^ s ^ "\n")
283 | _ => print "Unexpected server reply.\n";
284 OpenSSL.close bio)
285 end
286 handle ErrorMsg.Error => ()
287
288 fun requestPing () =
289 let
290 val (_, bio) = requestBio (fn () => ())
291 in
292 OpenSSL.close bio;
293 OS.Process.success
294 end
295 handle _ => OS.Process.failure
296
297 fun requestShutdown () =
298 let
299 val (_, bio) = requestBio (fn () => ())
300 in
301 Msg.send (bio, MsgShutdown);
302 case Msg.recv bio of
303 NONE => print "Server closed connection unexpectedly.\n"
304 | SOME m =>
305 case m of
306 MsgOk => print "Shutdown begun.\n"
307 | MsgError s => print ("Shutdown failed: " ^ s ^ "\n")
308 | _ => print "Unexpected server reply.\n";
309 OpenSSL.close bio
310 end
311
312 fun requestSlavePing () =
313 let
314 val (_, bio) = requestSlaveBio ()
315 in
316 OpenSSL.close bio;
317 OS.Process.success
318 end
319 handle _ => OS.Process.failure
320
321 fun requestSlaveShutdown () =
322 let
323 val (_, bio) = requestSlaveBio ()
324 in
325 Msg.send (bio, MsgShutdown);
326 case Msg.recv bio of
327 NONE => print "Server closed connection unexpectedly.\n"
328 | SOME m =>
329 case m of
330 MsgOk => print "Shutdown begun.\n"
331 | MsgError s => print ("Shutdown failed: " ^ s ^ "\n")
332 | _ => print "Unexpected server reply.\n";
333 OpenSSL.close bio
334 end
335
336 fun requestGrant acl =
337 let
338 val (user, bio) = requestBio (fn () => ())
339 in
340 Msg.send (bio, MsgGrant acl);
341 case Msg.recv bio of
342 NONE => print "Server closed connection unexpectedly.\n"
343 | SOME m =>
344 case m of
345 MsgOk => print "Grant succeeded.\n"
346 | MsgError s => print ("Grant failed: " ^ s ^ "\n")
347 | _ => print "Unexpected server reply.\n";
348 OpenSSL.close bio
349 end
350
351 fun requestRevoke acl =
352 let
353 val (user, bio) = requestBio (fn () => ())
354 in
355 Msg.send (bio, MsgRevoke acl);
356 case Msg.recv bio of
357 NONE => print "Server closed connection unexpectedly.\n"
358 | SOME m =>
359 case m of
360 MsgOk => print "Revoke succeeded.\n"
361 | MsgError s => print ("Revoke failed: " ^ s ^ "\n")
362 | _ => print "Unexpected server reply.\n";
363 OpenSSL.close bio
364 end
365
366 fun requestListPerms user =
367 let
368 val (_, bio) = requestBio (fn () => ())
369 in
370 Msg.send (bio, MsgListPerms user);
371 (case Msg.recv bio of
372 NONE => (print "Server closed connection unexpectedly.\n";
373 NONE)
374 | SOME m =>
375 case m of
376 MsgPerms perms => SOME perms
377 | MsgError s => (print ("Listing failed: " ^ s ^ "\n");
378 NONE)
379 | _ => (print "Unexpected server reply.\n";
380 NONE))
381 before OpenSSL.close bio
382 end
383
384 fun requestWhoHas perm =
385 let
386 val (_, bio) = requestBio (fn () => ())
387 in
388 Msg.send (bio, MsgWhoHas perm);
389 (case Msg.recv bio of
390 NONE => (print "Server closed connection unexpectedly.\n";
391 NONE)
392 | SOME m =>
393 case m of
394 MsgWhoHasResponse users => SOME users
395 | MsgError s => (print ("whohas failed: " ^ s ^ "\n");
396 NONE)
397 | _ => (print "Unexpected server reply.\n";
398 NONE))
399 before OpenSSL.close bio
400 end
401
402 fun requestRegen () =
403 let
404 val (_, bio) = requestBio (fn () => ())
405 in
406 Msg.send (bio, MsgRegenerate);
407 case Msg.recv bio of
408 NONE => print "Server closed connection unexpectedly.\n"
409 | SOME m =>
410 case m of
411 MsgOk => print "Regeneration succeeded.\n"
412 | MsgError s => print ("Regeneration failed: " ^ s ^ "\n")
413 | _ => print "Unexpected server reply.\n";
414 OpenSSL.close bio
415 end
416
417 fun requestRmdom dom =
418 let
419 val (_, bio) = requestBio (fn () => ())
420 in
421 Msg.send (bio, MsgRmdom dom);
422 case Msg.recv bio of
423 NONE => print "Server closed connection unexpectedly.\n"
424 | SOME m =>
425 case m of
426 MsgOk => print "Removal succeeded.\n"
427 | MsgError s => print ("Removal failed: " ^ s ^ "\n")
428 | _ => print "Unexpected server reply.\n";
429 OpenSSL.close bio
430 end
431
432 fun requestRmuser user =
433 let
434 val (_, bio) = requestBio (fn () => ())
435 in
436 Msg.send (bio, MsgRmuser user);
437 case Msg.recv bio of
438 NONE => print "Server closed connection unexpectedly.\n"
439 | SOME m =>
440 case m of
441 MsgOk => print "Removal succeeded.\n"
442 | MsgError s => print ("Removal failed: " ^ s ^ "\n")
443 | _ => print "Unexpected server reply.\n";
444 OpenSSL.close bio
445 end
446
447 fun requestDbUser dbtype =
448 let
449 val (_, bio) = requestBio (fn () => ())
450 in
451 Msg.send (bio, MsgCreateDbUser dbtype);
452 case Msg.recv bio of
453 NONE => print "Server closed connection unexpectedly.\n"
454 | SOME m =>
455 case m of
456 MsgOk => print "Your user has been created.\n"
457 | MsgError s => print ("Creation failed: " ^ s ^ "\n")
458 | _ => print "Unexpected server reply.\n";
459 OpenSSL.close bio
460 end
461
462 fun requestDbPasswd rc =
463 let
464 val (_, bio) = requestBio (fn () => ())
465 in
466 Msg.send (bio, MsgDbPasswd rc);
467 case Msg.recv bio of
468 NONE => print "Server closed connection unexpectedly.\n"
469 | SOME m =>
470 case m of
471 MsgOk => print "Your password has been changed.\n"
472 | MsgError s => print ("Password set failed: " ^ s ^ "\n")
473 | _ => print "Unexpected server reply.\n";
474 OpenSSL.close bio
475 end
476
477 fun requestDbTable p =
478 let
479 val (user, bio) = requestBio (fn () => ())
480 in
481 Msg.send (bio, MsgCreateDbTable p);
482 case Msg.recv bio of
483 NONE => print "Server closed connection unexpectedly.\n"
484 | SOME m =>
485 case m of
486 MsgOk => print ("Your database " ^ user ^ "_" ^ #dbname p ^ " has been created.\n")
487 | MsgError s => print ("Creation failed: " ^ s ^ "\n")
488 | _ => print "Unexpected server reply.\n";
489 OpenSSL.close bio
490 end
491
492 fun requestListMailboxes domain =
493 let
494 val (_, bio) = requestBio (fn () => ())
495 in
496 Msg.send (bio, MsgListMailboxes domain);
497 (case Msg.recv bio of
498 NONE => Vmail.Error "Server closed connection unexpectedly."
499 | SOME m =>
500 case m of
501 MsgMailboxes users => (Msg.send (bio, MsgOk);
502 Vmail.Listing users)
503 | MsgError s => Vmail.Error ("Creation failed: " ^ s)
504 | _ => Vmail.Error "Unexpected server reply.")
505 before OpenSSL.close bio
506 end
507
508 fun requestNewMailbox p =
509 let
510 val (_, bio) = requestBio (fn () => ())
511 in
512 Msg.send (bio, MsgNewMailbox p);
513 case Msg.recv bio of
514 NONE => print "Server closed connection unexpectedly.\n"
515 | SOME m =>
516 case m of
517 MsgOk => print ("A mapping for " ^ #user p ^ "@" ^ #domain p ^ " has been created.\n")
518 | MsgError s => print ("Creation failed: " ^ s ^ "\n")
519 | _ => print "Unexpected server reply.\n";
520 OpenSSL.close bio
521 end
522
523 fun requestPasswdMailbox p =
524 let
525 val (_, bio) = requestBio (fn () => ())
526 in
527 Msg.send (bio, MsgPasswdMailbox p);
528 case Msg.recv bio of
529 NONE => print "Server closed connection unexpectedly.\n"
530 | SOME m =>
531 case m of
532 MsgOk => print ("The password for " ^ #user p ^ "@" ^ #domain p ^ " has been changed.\n")
533 | MsgError s => print ("Set failed: " ^ s ^ "\n")
534 | _ => print "Unexpected server reply.\n";
535 OpenSSL.close bio
536 end
537
538 fun requestRmMailbox p =
539 let
540 val (_, bio) = requestBio (fn () => ())
541 in
542 Msg.send (bio, MsgRmMailbox p);
543 case Msg.recv bio of
544 NONE => print "Server closed connection unexpectedly.\n"
545 | SOME m =>
546 case m of
547 MsgOk => print ("The mapping for mailbox " ^ #user p ^ "@" ^ #domain p ^ " has been deleted.\n")
548 | MsgError s => print ("Remove failed: " ^ s ^ "\n")
549 | _ => print "Unexpected server reply.\n";
550 OpenSSL.close bio
551 end
552
553 fun requestSaQuery addr =
554 let
555 val (_, bio) = requestBio (fn () => ())
556 in
557 Msg.send (bio, MsgSaQuery addr);
558 (case Msg.recv bio of
559 NONE => print "Server closed connection unexpectedly.\n"
560 | SOME m =>
561 case m of
562 MsgSaStatus b => (print ("SpamAssassin filtering for " ^ addr ^ " is "
563 ^ (if b then "ON" else "OFF") ^ ".\n");
564 Msg.send (bio, MsgOk))
565 | MsgError s => print ("Query failed: " ^ s ^ "\n")
566 | _ => print "Unexpected server reply.\n")
567 before OpenSSL.close bio
568 end
569
570 fun requestSaSet p =
571 let
572 val (_, bio) = requestBio (fn () => ())
573 in
574 Msg.send (bio, MsgSaSet p);
575 case Msg.recv bio of
576 NONE => print "Server closed connection unexpectedly.\n"
577 | SOME m =>
578 case m of
579 MsgOk => print ("SpamAssassin filtering for " ^ #1 p ^ " is now "
580 ^ (if #2 p then "ON" else "OFF") ^ ".\n")
581 | MsgError s => print ("Set failed: " ^ s ^ "\n")
582 | _ => print "Unexpected server reply.\n";
583 OpenSSL.close bio
584 end
585
586 fun requestSmtpLog domain =
587 let
588 val (_, bio) = requestBio (fn () => ())
589
590 val _ = Msg.send (bio, MsgSmtpLogReq domain)
591
592 fun loop () =
593 case Msg.recv bio of
594 NONE => print "Server closed connection unexpectedly.\n"
595 | SOME m =>
596 case m of
597 MsgOk => ()
598 | MsgSmtpLogRes line => (print line;
599 loop ())
600 | MsgError s => print ("Log search failed: " ^ s ^ "\n")
601 | _ => print "Unexpected server reply.\n"
602 in
603 loop ();
604 OpenSSL.close bio
605 end
606
607 fun regenerate context =
608 let
609 val b = basis ()
610 val () = Tycheck.disallowExterns ()
611
612 val () = Domain.resetGlobal ()
613
614 fun contactNode (node, ip) =
615 if node = Config.defaultNode then
616 Domain.resetLocal ()
617 else let
618 val bio = OpenSSL.connect (context,
619 ip
620 ^ ":"
621 ^ Int.toString Config.slavePort)
622 in
623 Msg.send (bio, MsgRegenerate);
624 case Msg.recv bio of
625 NONE => print "Slave closed connection unexpectedly\n"
626 | SOME m =>
627 case m of
628 MsgOk => print ("Slave " ^ node ^ " pre-regeneration finished\n")
629 | MsgError s => print ("Slave " ^ node
630 ^ " returned error: " ^
631 s ^ "\n")
632 | _ => print ("Slave " ^ node
633 ^ " returned unexpected command\n");
634 OpenSSL.close bio
635 end
636
637 fun doUser user =
638 let
639 val _ = Domain.setUser user
640 val _ = ErrorMsg.reset ()
641
642 val dname = Config.domtoolDir user
643
644 val dir = Posix.FileSys.opendir dname
645
646 fun loop files =
647 case Posix.FileSys.readdir dir of
648 NONE => (Posix.FileSys.closedir dir;
649 files)
650 | SOME fname =>
651 if notTmp fname then
652 loop (OS.Path.joinDirFile {dir = dname,
653 file = fname}
654 :: files)
655 else
656 loop files
657
658 val files = loop []
659 val (_, files) = Order.order (SOME b) files
660 in
661 if !ErrorMsg.anyErrors then
662 print ("User " ^ user ^ "'s configuration has errors!\n")
663 else
664 app eval' files
665 end
666 handle IO.Io _ => ()
667 | OS.SysErr (s, _) => print ("System error processing user " ^ user ^ ": " ^ s ^ "\n")
668 | ErrorMsg.Error => print ("User " ^ user ^ " had a compilation error.\n")
669 in
670 app contactNode Config.nodeIps;
671 Env.pre ();
672 app doUser (Acl.users ());
673 Env.post ()
674 end
675
676 fun rmuser user =
677 let
678 val doms = Acl.class {user = user, class = "domain"}
679 val doms = List.filter (fn dom =>
680 case Acl.whoHas {class = "domain", value = dom} of
681 [_] => true
682 | _ => false) (StringSet.listItems doms)
683 in
684 Acl.rmuser user;
685 Domain.rmdom doms
686 end
687
688 fun now () = Date.toString (Date.fromTimeUniv (Time.now ()))
689
690 fun service () =
691 let
692 val () = Acl.read Config.aclFile
693
694 val context = OpenSSL.context (Config.serverCert,
695 Config.serverKey,
696 Config.trustStore)
697 val _ = Domain.set_context context
698
699 val sock = OpenSSL.listen (context, Config.dispatcherPort)
700
701 fun loop () =
702 case OpenSSL.accept sock of
703 NONE => ()
704 | SOME bio =>
705 let
706 val user = OpenSSL.peerCN bio
707 val () = print ("\nConnection from " ^ user ^ " at " ^ now () ^ "\n")
708 val () = Domain.setUser user
709
710 fun doIt f cleanup =
711 ((case f () of
712 (msgLocal, SOME msgRemote) =>
713 (print msgLocal;
714 print "\n";
715 Msg.send (bio, MsgError msgRemote))
716 | (msgLocal, NONE) =>
717 (print msgLocal;
718 print "\n";
719 Msg.send (bio, MsgOk)))
720 handle OpenSSL.OpenSSL _ =>
721 print "OpenSSL error\n"
722 | OS.SysErr (s, _) =>
723 (print "System error: ";
724 print s;
725 print "\n";
726 Msg.send (bio, MsgError ("System error: " ^ s))
727 handle OpenSSL.OpenSSL _ => ())
728 | Fail s =>
729 (print "Failure: ";
730 print s;
731 print "\n";
732 Msg.send (bio, MsgError ("Failure: " ^ s))
733 handle OpenSSL.OpenSSL _ => ())
734 | ErrorMsg.Error =>
735 (print "Compilation error\n";
736 Msg.send (bio, MsgError "Error during configuration evaluation")
737 handle OpenSSL.OpenSSL _ => ());
738 (cleanup ();
739 ignore (OpenSSL.readChar bio);
740 OpenSSL.close bio)
741 handle OpenSSL.OpenSSL _ => ();
742 loop ())
743
744 fun doConfig codes =
745 let
746 val _ = print "Configuration:\n"
747 val _ = app (fn s => (print s; print "\n")) codes
748 val _ = print "\n"
749
750 val outname = OS.FileSys.tmpName ()
751
752 fun doOne code =
753 let
754 val outf = TextIO.openOut outname
755 in
756 TextIO.output (outf, code);
757 TextIO.closeOut outf;
758 eval' outname
759 end
760 in
761 doIt (fn () => (Env.pre ();
762 app doOne codes;
763 Env.post ();
764 Msg.send (bio, MsgOk);
765 ("Configuration complete.", NONE)))
766 (fn () => OS.FileSys.remove outname)
767 end
768
769 fun checkAddr s =
770 case String.fields (fn ch => ch = #"@") s of
771 [user'] =>
772 if user = user' then
773 SOME (SetSA.User s)
774 else
775 NONE
776 | [user', domain] =>
777 if Domain.validEmailUser user' andalso Domain.yourDomain domain then
778 SOME (SetSA.Email s)
779 else
780 NONE
781 | _ => NONE
782
783 fun cmdLoop () =
784 case Msg.recv bio of
785 NONE => (OpenSSL.close bio
786 handle OpenSSL.OpenSSL _ => ();
787 loop ())
788 | SOME m =>
789 case m of
790 MsgConfig code => doConfig [code]
791 | MsgMultiConfig codes => doConfig codes
792
793 | MsgShutdown =>
794 if Acl.query {user = user, class = "priv", value = "all"}
795 orelse Acl.query {user = user, class = "priv", value = "shutdown"} then
796 print ("Domtool dispatcher shutting down at " ^ now () ^ "\n\n")
797 else
798 (print "Unauthorized shutdown command!\n";
799 OpenSSL.close bio
800 handle OpenSSL.OpenSSL _ => ();
801 loop ())
802
803 | MsgGrant acl =>
804 doIt (fn () =>
805 if Acl.query {user = user, class = "priv", value = "all"} then
806 (Acl.grant acl;
807 Acl.write Config.aclFile;
808 ("Granted permission " ^ #value acl ^ " to " ^ #user acl ^ " in " ^ #class acl ^ ".",
809 NONE))
810 else
811 ("Unauthorized user asked to grant a permission!",
812 SOME "Not authorized to grant privileges"))
813 (fn () => ())
814
815 | MsgRevoke acl =>
816 doIt (fn () =>
817 if Acl.query {user = user, class = "priv", value = "all"} then
818 (Acl.revoke acl;
819 Acl.write Config.aclFile;
820 ("Revoked permission " ^ #value acl ^ " from " ^ #user acl ^ " in " ^ #class acl ^ ".",
821 NONE))
822 else
823 ("Unauthorized user asked to revoke a permission!",
824 SOME "Not authorized to revoke privileges"))
825 (fn () => ())
826
827 | MsgListPerms user =>
828 doIt (fn () =>
829 (Msg.send (bio, MsgPerms (Acl.queryAll user));
830 ("Sent permission list for user " ^ user ^ ".",
831 NONE)))
832 (fn () => ())
833
834 | MsgWhoHas perm =>
835 doIt (fn () =>
836 (Msg.send (bio, MsgWhoHasResponse (Acl.whoHas perm));
837 ("Sent whohas response for " ^ #class perm ^ " / " ^ #value perm ^ ".",
838 NONE)))
839 (fn () => ())
840
841 | MsgRmdom doms =>
842 doIt (fn () =>
843 if Acl.query {user = user, class = "priv", value = "all"}
844 orelse List.all (fn dom => Acl.query {user = user, class = "domain", value = dom}) doms then
845 (Domain.rmdom doms;
846 app (fn dom =>
847 Acl.revokeFromAll {class = "domain", value = dom}) doms;
848 Acl.write Config.aclFile;
849 ("Removed domains" ^ foldl (fn (d, s) => s ^ " " ^ d) "" doms ^ ".",
850 NONE))
851 else
852 ("Unauthorized user asked to remove a domain!",
853 SOME "Not authorized to remove that domain"))
854 (fn () => ())
855
856 | MsgRegenerate =>
857 doIt (fn () =>
858 if Acl.query {user = user, class = "priv", value = "regen"}
859 orelse Acl.query {user = user, class = "priv", value = "all"} then
860 (regenerate context;
861 ("Regenerated all configuration.",
862 NONE))
863 else
864 ("Unauthorized user asked to regenerate!",
865 SOME "Not authorized to regenerate"))
866 (fn () => ())
867
868 | MsgRmuser user' =>
869 doIt (fn () =>
870 if Acl.query {user = user, class = "priv", value = "all"} then
871 (rmuser user';
872 Acl.write Config.aclFile;
873 ("Removed user " ^ user' ^ ".",
874 NONE))
875 else
876 ("Unauthorized user asked to remove a user!",
877 SOME "Not authorized to remove users"))
878 (fn () => ())
879
880 | MsgCreateDbUser {dbtype, passwd} =>
881 doIt (fn () =>
882 case Dbms.lookup dbtype of
883 NONE => ("Database user creation request with unknown datatype type " ^ dbtype,
884 SOME ("Unknown database type " ^ dbtype))
885 | SOME handler =>
886 case #adduser handler {user = user, passwd = passwd} of
887 NONE => ("Added " ^ dbtype ^ " user " ^ user ^ ".",
888 NONE)
889 | SOME msg =>
890 ("Error adding a " ^ dbtype ^ " user " ^ user ^ ": " ^ msg,
891 SOME ("Error adding user: " ^ msg)))
892 (fn () => ())
893
894 | MsgDbPasswd {dbtype, passwd} =>
895 doIt (fn () =>
896 case Dbms.lookup dbtype of
897 NONE => ("Database passwd request with unknown datatype type " ^ dbtype,
898 SOME ("Unknown database type " ^ dbtype))
899 | SOME handler =>
900 case #passwd handler {user = user, passwd = passwd} of
901 NONE => ("Changed " ^ dbtype ^ " password of user " ^ user ^ ".",
902 NONE)
903 | SOME msg =>
904 ("Error setting " ^ dbtype ^ " password of user " ^ user ^ ": " ^ msg,
905 SOME ("Error adding user: " ^ msg)))
906 (fn () => ())
907
908 | MsgCreateDbTable {dbtype, dbname} =>
909 doIt (fn () =>
910 if Dbms.validDbname dbname then
911 case Dbms.lookup dbtype of
912 NONE => ("Database creation request with unknown datatype type " ^ dbtype,
913 SOME ("Unknown database type " ^ dbtype))
914 | SOME handler =>
915 case #createdb handler {user = user, dbname = dbname} of
916 NONE => ("Created database " ^ user ^ "_" ^ dbname ^ ".",
917 NONE)
918 | SOME msg => ("Error creating database " ^ user ^ "_" ^ dbname ^ ": " ^ msg,
919 SOME ("Error creating database: " ^ msg))
920 else
921 ("Invalid database name " ^ user ^ "_" ^ dbname,
922 SOME ("Invalid database name " ^ dbname)))
923 (fn () => ())
924
925 | MsgListMailboxes domain =>
926 doIt (fn () =>
927 if not (Domain.yourDomain domain) then
928 ("User wasn't authorized to list mailboxes for " ^ domain,
929 SOME "You're not authorized to configure that domain.")
930 else
931 case Vmail.list domain of
932 Vmail.Listing users => (Msg.send (bio, MsgMailboxes users);
933 ("Sent mailbox list for " ^ domain,
934 NONE))
935 | Vmail.Error msg => ("Error listing mailboxes for " ^ domain ^ ": " ^ msg,
936 SOME msg))
937 (fn () => ())
938
939 | MsgNewMailbox {domain, user = emailUser, passwd, mailbox} =>
940 doIt (fn () =>
941 if not (Domain.yourDomain domain) then
942 ("User wasn't authorized to add a mailbox to " ^ domain,
943 SOME "You're not authorized to configure that domain.")
944 else if not (Domain.validEmailUser emailUser) then
945 ("Invalid e-mail username " ^ emailUser,
946 SOME "Invalid e-mail username")
947 else if not (CharVector.all Char.isGraph passwd) then
948 ("Invalid password",
949 SOME "Invalid password; may only contain printable, non-space characters")
950 else if not (Domain.yourPath mailbox) then
951 ("User wasn't authorized to add a mailbox at " ^ mailbox,
952 SOME "You're not authorized to use that mailbox location.")
953 else
954 case Vmail.add {requester = user,
955 domain = domain, user = emailUser,
956 passwd = passwd, mailbox = mailbox} of
957 NONE => ("Added mailbox " ^ emailUser ^ "@" ^ domain ^ " at " ^ mailbox,
958 NONE)
959 | SOME msg => ("Error adding mailbox " ^ emailUser ^ "@" ^ domain ^ ": " ^ msg,
960 SOME msg))
961 (fn () => ())
962
963 | MsgPasswdMailbox {domain, user = emailUser, passwd} =>
964 doIt (fn () =>
965 if not (Domain.yourDomain domain) then
966 ("User wasn't authorized to change password of a mailbox for " ^ domain,
967 SOME "You're not authorized to configure that domain.")
968 else if not (Domain.validEmailUser emailUser) then
969 ("Invalid e-mail username " ^ emailUser,
970 SOME "Invalid e-mail username")
971 else if not (CharVector.all Char.isGraph passwd) then
972 ("Invalid password",
973 SOME "Invalid password; may only contain printable, non-space characters")
974 else
975 case Vmail.passwd {domain = domain, user = emailUser,
976 passwd = passwd} of
977 NONE => ("Changed password of mailbox " ^ emailUser ^ "@" ^ domain,
978 NONE)
979 | SOME msg => ("Error changing mailbox password for " ^ emailUser ^ "@" ^ domain ^ ": " ^ msg,
980 SOME msg))
981 (fn () => ())
982
983 | MsgRmMailbox {domain, user = emailUser} =>
984 doIt (fn () =>
985 if not (Domain.yourDomain domain) then
986 ("User wasn't authorized to change password of a mailbox for " ^ domain,
987 SOME "You're not authorized to configure that domain.")
988 else if not (Domain.validEmailUser emailUser) then
989 ("Invalid e-mail username " ^ emailUser,
990 SOME "Invalid e-mail username")
991 else
992 case Vmail.rm {domain = domain, user = emailUser} of
993 NONE => ("Deleted mailbox " ^ emailUser ^ "@" ^ domain,
994 NONE)
995 | SOME msg => ("Error deleting mailbox " ^ emailUser ^ "@" ^ domain ^ ": " ^ msg,
996 SOME msg))
997 (fn () => ())
998
999 | MsgSaQuery addr =>
1000 doIt (fn () =>
1001 case checkAddr addr of
1002 NONE => ("User tried to query SA filtering for " ^ addr,
1003 SOME "You aren't allowed to configure SA filtering for that recipient.")
1004 | SOME addr' => (Msg.send (bio, MsgSaStatus (SetSA.query addr'));
1005 ("Queried SA filtering status for " ^ addr,
1006 NONE)))
1007 (fn () => ())
1008
1009 | MsgSaSet (addr, b) =>
1010 doIt (fn () =>
1011 case checkAddr addr of
1012 NONE => ("User tried to set SA filtering for " ^ addr,
1013 SOME "You aren't allowed to configure SA filtering for that recipient.")
1014 | SOME addr' => (SetSA.set (addr', b);
1015 Msg.send (bio, MsgOk);
1016 ("Set SA filtering status for " ^ addr ^ " to "
1017 ^ (if b then "ON" else "OFF"),
1018 NONE)))
1019 (fn () => ())
1020
1021 | MsgSmtpLogReq domain =>
1022 doIt (fn () =>
1023 if not (Domain.yourDomain domain) then
1024 ("Unauthorized user tried to request SMTP logs for " ^ domain,
1025 SOME "You aren't authorized to configure that domain.")
1026 else
1027 (SmtpLog.search (fn line => Msg.send (bio, MsgSmtpLogRes line))
1028 domain;
1029 ("Requested SMTP logs for " ^ domain,
1030 NONE)))
1031 (fn () => ())
1032
1033 | _ =>
1034 doIt (fn () => ("Unexpected command",
1035 SOME "Unexpected command"))
1036 (fn () => ())
1037 in
1038 cmdLoop ()
1039 end
1040 handle OpenSSL.OpenSSL s =>
1041 (print ("OpenSSL error: " ^ s ^ "\n");
1042 OpenSSL.close bio
1043 handle OpenSSL.OpenSSL _ => ();
1044 loop ())
1045 | OS.SysErr (s, _) =>
1046 (print ("System error: " ^ s ^ "\n");
1047 OpenSSL.close bio
1048 handle OpenSSL.OpenSSL _ => ();
1049 loop ())
1050 in
1051 print ("Domtool dispatcher starting up at " ^ now () ^ "\n");
1052 print "Listening for connections....\n";
1053 loop ();
1054 OpenSSL.shutdown sock
1055 end
1056
1057 fun slave () =
1058 let
1059 val host = Slave.hostname ()
1060
1061 val context = OpenSSL.context (Config.certDir ^ "/" ^ host ^ ".pem",
1062 Config.keyDir ^ "/" ^ host ^ "/key.pem",
1063 Config.trustStore)
1064
1065 val sock = OpenSSL.listen (context, Config.slavePort)
1066
1067 val _ = print ("Slave server starting at " ^ now () ^ "\n")
1068
1069 fun loop () =
1070 case OpenSSL.accept sock of
1071 NONE => ()
1072 | SOME bio =>
1073 let
1074 val peer = OpenSSL.peerCN bio
1075 val () = print ("\nConnection from " ^ peer ^ " at " ^ now () ^ "\n")
1076 in
1077 if peer = Config.dispatcherName then let
1078 fun loop' files =
1079 case Msg.recv bio of
1080 NONE => print "Dispatcher closed connection unexpectedly\n"
1081 | SOME m =>
1082 case m of
1083 MsgFile file => loop' (file :: files)
1084 | MsgDoFiles => (Slave.handleChanges files;
1085 Msg.send (bio, MsgOk))
1086 | MsgRegenerate => (Domain.resetLocal ();
1087 Msg.send (bio, MsgOk))
1088 | _ => (print "Dispatcher sent unexpected command\n";
1089 Msg.send (bio, MsgError "Unexpected command"))
1090 in
1091 loop' [];
1092 ignore (OpenSSL.readChar bio);
1093 OpenSSL.close bio;
1094 loop ()
1095 end
1096 else if peer = "domtool" then
1097 case Msg.recv bio of
1098 SOME MsgShutdown => (OpenSSL.close bio;
1099 print ("Shutting down at " ^ now () ^ "\n\n"))
1100 | _ => (OpenSSL.close bio;
1101 loop ())
1102 else
1103 (print "Not authorized!\n";
1104 OpenSSL.close bio;
1105 loop ())
1106 end handle OpenSSL.OpenSSL s =>
1107 (print ("OpenSSL error: "^ s ^ "\n");
1108 OpenSSL.close bio
1109 handle OpenSSL.OpenSSL _ => ();
1110 loop ())
1111 | OS.SysErr (s, _) =>
1112 (print ("System error: "^ s ^ "\n");
1113 OpenSSL.close bio
1114 handle OpenSSL.OpenSSL _ => ();
1115 loop ())
1116 in
1117 loop ();
1118 OpenSSL.shutdown sock
1119 end
1120
1121 fun listBasis () =
1122 let
1123 val dir = Posix.FileSys.opendir Config.libRoot
1124
1125 fun loop files =
1126 case Posix.FileSys.readdir dir of
1127 NONE => (Posix.FileSys.closedir dir;
1128 files)
1129 | SOME fname =>
1130 if String.isSuffix ".dtl" fname then
1131 loop (OS.Path.joinDirFile {dir = Config.libRoot,
1132 file = fname}
1133 :: files)
1134 else
1135 loop files
1136 in
1137 loop []
1138 end
1139
1140 fun autodocBasis outdir =
1141 Autodoc.autodoc {outdir = outdir, infiles = listBasis ()}
1142
1143 end