File: tzc.c

package info (click to toggle)
tzc 2.6.15-5.4
  • links: PTS
  • area: main
  • in suites: bullseye, buster, sid, stretch
  • size: 240 kB
  • ctags: 361
  • sloc: ansic: 3,931; makefile: 42
file content (2101 lines) | stat: -rw-r--r-- 58,490 bytes parent folder | download
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
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
/*
   tzc.c  trivial zephyr client (once upon a time)
   Copyright (C) 1992, 1993 Scott Draves (spot@cs.cmu.edu)
   Copyright (C) 1994, 1995, 1996, 1998 Darrell Kindred (dkindred@cs.cmu.edu)

   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 2 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, write to the Free Software
   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.

   Now at version 2.6.15

   Thanks to Nick Thompson and Darrell Kindred for their contributions.

   this program is a replacement for zwgc and zwrite that talks to emacs
   in printed sexps.  Contact dkindred@cs.cmu.edu to get zephyr.el.

   Darrell Kindred <dkindred@cs.cmu.edu> is the current tzc
   maintainer.

   TODO

   - write man page
   - make check() print an error msg that zephyr.el will see, rather than
     the silent "; <error>" variety.
   - see about incorporating poole's setlocation change, activated
     by some cmd-line flag
   - allow emacs to tag outgoing zgrams with some identifier, which
     will be used in the (tzcspew . sent), (tzcspew . not-sent)
     etc. messages referring to that zgram.  This would, in principle,
     allow zephyr.el to do something more reasonable with the acks for
     multi-recipient zgrams.
   - [very old] if you get a USR1 in the middle of writing out a msg, then
     the output will not be properly formatted.  so should either
     disable the sig for this time, or set a flag in the handler and
     check at the main loop.  the same probably applies to the alarm.


   CHANGES

   15 Jun 2000  (ver 2.6.15) handle malformed (< 0) z_time.tv_usec
   30 May 2000  (ver 2.6.14) handle malformed (> 999999) z_time.tv_usec
   30 May 2000  (ver 2.6.13) change z_default_format (include time/date etc.)
   06 Mar 2000  (ver 2.6.12) support get-location
   05 Mar 2000  (ver 2.6.10) support set-location
   05 Mar 2000  (ver 2.6.04) com_err reports errors via elisp
   07 Dec 1998  (ver 2.6.03) more typechecking in send_zgram()
   16 Oct 1998  (ver 2.6.02) print feature list in startup msg
   16 Oct 1998  (ver 2.6.01) allow modifying/removing queries
   15 Oct 1998  (ver 2.6.00) support `register-query'
   29 Sep 1998  (ver 2.5.04) allow sender to be specified for outgoing z's
                             (code from poole/scottd)
   23 Sep 1998  (ver 2.5.03) replace bcopy and friends with ANSI mem*
   19 Sep 1998  (ver 2.5.02) fix fputqqs to handle symbols looking like numbers
   17 Sep 1998  (ver 2.5.01) fix gcc warnings, lread.c supports \NNN escapes
   27 Jul 1998  remove pointless forced-termination message
   14 Jan 1997  (version 2.5) support 'ayt' command
   6  Jun 1996  added #include <errno.h> for EWOULDBLOCK
   14 Mar 1994  (version 2.4) cross-realm support (#ifdef INTERREALM),
                added subscribe command (see zsubscribe), 
                added (tzcspew . start) message on startup
   18 Feb 1994  (version 2.3) provide heartbeat feature to combat
                the problem of zephyr servers which forget you exist
   12 Feb 1994  (version 2.2) provide -o flag for output-only, and
                print a machine-readable timestamp ('time-secs field)
		in addition to the 'time string.
   26 Sep 1993  print more usage info,
                exit gracefully upon EOF on stdin or socket
   9  Apr 1993  (version 2.1)
                on exit or restart: cancel subscriptions, unset
		  location, remove the -p pid-file.
		set location (for zlocate) to tzc.pid (by setting DISPLAY)
		added -l flag to explicitly set the location
		added version number to greeting
   18 Jan 1993  received -a option from hsw@cs.cmu.edu, it restarts the
                process if no messages have been received after arg seconds.
   6  Jan 1993  added p: to options string, i forgot it in the merge
   1 Jan  1993  replace ((tzcspew . sent) (to "spot"))
                with    ((tzcspew . sent) (to "PERSONAL" . "spot"))
   20 Dec 1992  removed silly old code that was forcing recip to be "" for
                non-personal instances.
   sometime     recognizes (auth . nil) to disable kerberos authentication
   16 Dec 1992  added some more error checking to send_zgram so that it
                handles garbled input without dying.
   13 Dec 1992  merged in lisp reading stuff.  no more calls to zwrite.
   25 Oct 1992  if we get a USR1 signal, then restart ourselves. added -p
                flag to write our pid into a file. this is so that kauthd
	        users can restart tzc automatically when they get new
	        tickets.
   28 Jul 1992  added wait() to subscribe_with_zctl() to prevent zombies.

   
  */

#define TZC_VERSION "2.6.15"

#include <stdarg.h>
#include <string.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <ctype.h>
#include <zephyr/zephyr.h>
#include <zephyr/zephyr_err.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <sys/file.h>
#include <signal.h>
#include <time.h>
#include <sys/time.h>
#include <fcntl.h>
#include <errno.h>
#include "lread.h"
#include <et/com_err.h>
#if USE_LIBCS
#include <libcs.h>	      /* for snprintf */
#endif
#if defined(sgi)
/* FD_ZERO needs this.  Same problem under AIX but no bstring.h exists. */
#include <bstring.h>
#endif

#ifdef INTERREALM
extern char *ZExpandRealm();
#endif

#define ZCTL_BINARY "zctl"

#define TZC_HEARTBEAT_MESSAGE  "tzc\000thump thump"
#define TZC_HEARTBEAT_CLASS    "TZC"
#define TZC_HEARTBEAT_INSTANCE "heartbeat"
#define HEARTBEAT_PERIOD_DEF   5 * 60      /* sent hearbeat after 5 minutes */
#define HEARTBEAT_TIMEOUT      45	   /* timeout if it doesn't arrive
					    * within 45 seconds */

/* these should eventually be set to 0, maybe in 2.6 */
#define TZC_CLASS_IS_SYMBOL 1
#define TZC_OPCODE_IS_SYMBOL 1

/* include kosak query-processing code */
/* #define QUERY_HELL 1 */

#if __hpux__
#define random lrand48
#define srandom srand48
#endif

#if QUERY_HELL
void *HellStartup();
void  HellShutdown(void *hellCookie);
void *HellCompileQuery (void *hellCookie, const char *queryp);
void  HellDeleteQuery (void *hellCookie, void *compiled_query);
int   HellEvaluateQuery(void *hellCookie, void *queryCookie, 
			const char *zgram, int length);
#endif

typedef struct PendingReply PendingReply;
struct PendingReply {
   char *instance;
   char *recipient;
   ZUnique_Id_t	uid;
   PendingReply *next;
};

#if QUERY_HELL
typedef struct RegisteredQuery_s {
   char *id;
   char *raw_query;
   void *compiled_query;
   struct RegisteredQuery_s *next;
} RegisteredQuery;
#endif

struct Globals {
   const char	*program;
   int          argc;
   char         **argv;

   u_short	port;
   int		use_stdin;	/* if 0, don't listen to stdin at all */
   int          ignore_eof;     /* if 1, ignore eof on stdin */
   int		stdin_flags;
   int		zfd;
   char *	pidfile;
#if 0
   char *	my_zephyr_id;	/* the user's zephyr "name" */
   char *	my_realm;	/* the user's realm */
#endif
   char *       exposure;
   char *       location;
   int		debug;

   struct {
       enum {
           HB_DISABLED, /* don't use heartbeats */
	   HB_ENABLED,  /* use heartbeat -- we're alive */
	   HB_TESTING,  /* use heartbeat -- hb sent, waiting for it to come */
	   HB_DEAD      /* use heartbeat -- server seems to have dropped us */
       } status;
       long timeout;    /* if the heartbeat doesn't arrive in this number of
			 * seconds, send the (tzcspew . cutoff) to emacs */
       long wakeup;     /* if not 0, time at which we should wake up
 		         * to see if the server has forgotten us */
       long period;     /* if no zgrams have arrived in this number of seconds,
			 * send a heartbeat */
   } heartbeat;

#if QUERY_HELL
   RegisteredQuery *queries;
   void *query_hell_cookie;
#endif

   int		ebufsiz;
   char *	ebuf;
   char *	ebufptr;

   /* linked list of messages sent which are waiting for replies */
   PendingReply *pending_replies;

   struct {
      Value *sym_class;
      Value *sym_instance;
      Value *sym_sender;
      Value *sym_recipients;
      Value *sym_message;
      Value *sym_send;
      Value *sym_tzcfodder;
      Value *sym_auth;
      Value *sym_subscribe;
      Value *sym_get_location;
      Value *sym_set_location;
      Value *sym_location;
      Value *sym_exposure;
      Value *sym_ayt;
      Value *sym_register_query;
      Value *sym_query;
      Value *sym_id;
      Value *sym_opcode;
   } constants;
};

struct Globals global_storage, *globals;

void usage() {
   fprintf(stderr, "usage: %s [options]\n", globals->program);
   fprintf(stderr, "   options:\n");
   fprintf(stderr, "      -a <nseconds>  restart tzc every <nseconds> seconds\n");
   fprintf(stderr, "      -e <exposure>  set exposure (values: NONE, OPSTAFF, REALM-VISIBLE,\n");
   fprintf(stderr, "                     REALM-ANNOUNCED, NET-VISIBLE, NET-ANNOUNCED)\n");
   fprintf(stderr, "      -l <location>  set zlocation to the given string\n");
   fprintf(stderr, "                     (default: tzc.n, where n is tzc's pid)\n");
   fprintf(stderr, "      -p <filename>  write tzc's process-id to the indicated file\n");
   fprintf(stderr, "      -s             use zctl for subscriptions (read from ~/.zephyr.subs.tzc)\n");
   fprintf(stderr, "      -t <nseconds>  if no zgrams arrive in <nseconds> seconds, send a test\n");
   fprintf(stderr, "                     msg to make sure we're alive.  Default 300, 0 disables.\n");
   fprintf(stderr, "      -o             output-only (just print zgrams, don't listen to stdin)\n");
   /* it's really time to move to long option names... */
   fprintf(stderr, "      -i             ignore eof on input\n");
   fprintf(stderr, "      -d             print debugging information\n");
}

/* warning: this uses ctime which returns a pointer to a static buffer
 * which is overwritten with each call. */
char *time_str(time_t time_num)
{
    char *now_name;
    now_name = ctime(&time_num);
    now_name[24] = '\0';	/* dump newline at end */
    return(now_name);
}

/* return time in the format "14:15:03" */
/* uses ctime, which returns a ptr to a static buffer */
char *debug_time_str(time_t time_num)
{
    char *now_name;
    now_name = ctime(&time_num);
    now_name[19] = '\0';	/* strip year */
    return now_name+11;		/* strip date */
}

#if DEBUG_LOG
void debug_log(char *s)
{
  char fname[50];
  FILE *f;
  if (globals->debug) {
    sprintf(fname, "/tmp/tzc-log.%ld", (long) getpid());
    if ((f = fopen(fname,"a")) != NULL) {
      fprintf(f, "[%s] %s\n", debug_time_str(time(NULL)), s);
      fclose(f);
    }
  }
}
#else  /* !DEBUG_LOG */
#define debug_log(s) ((void)0)
#endif

/* I'm paranoid about leaving stdin non-blocking, though I doubt it's a */
/* problem in this case. - nix */
void bail(int code) {
   debug_log("bail: start");
   if (globals->use_stdin) {
      if (-1 == fcntl(0, F_SETFL, globals->stdin_flags)) {
         perror("unable to reset stdin");
         code = 1;
      }
   }
   debug_log("bail: done");
   exit(code);
}

void unblock_signals()
{
#if USE_SIGSETMASK
   int mask = sigsetmask(0);
   (void) sigsetmask(mask & ~sigmask(SIGUSR1) & ~sigmask(SIGALRM));
#else
   sigset_t sigs;
   sigemptyset(&sigs);
   sigaddset(&sigs, SIGUSR1);
   sigaddset(&sigs, SIGALRM);
   sigprocmask(SIG_UNBLOCK, &sigs, NULL);
#endif
}

void
sign_off(msg)
char *msg;
{
        debug_log("sign_off()");

	if (globals->pidfile != NULL)
		unlink(globals->pidfile);

        ZCancelSubscriptions(0);
        if (globals->exposure != NULL)
		ZUnsetLocation();
	ZClosePort();

	printf("\n; tzc %s\n;;;\n",msg);
}

void restart_tzc(int sig) {
   unblock_signals();
   sign_off("restarting");
   execvp(globals->argv[0], globals->argv);
}

void kill_tzc(int sig) {
   unblock_signals();
   sign_off("killed");
   bail(1);
}

void exit_tzc() {
   /* graceful exit, no error */
   debug_log("exit_tzc()");
#if QUERY_HELL
   if (globals->query_hell_cookie) {
     HellShutdown(globals->query_hell_cookie);
     globals->query_hell_cookie = 0;
     debug_log("exit_tzc(): hellshutdown done");
   }
#endif
   unblock_signals();
   debug_log("exit_tzc(): signals unblocked");
   sign_off("exiting");
   debug_log("exit_tzc(): signed off");
   bail(0);
}		 

Code_t check(Code_t e, char *s) {
   if (e) {
      printf(";;; return code %d\n",(int) e);
      fflush(stdout);
      com_err(__FILE__, e, "%s", s);
      bail(1);
   }
   return e;
}

Code_t warn(Code_t e, char *s) {
   if (e)
      com_err(__FILE__, e, "%s", s);
   return e;
}

/* useful for debugging */
void list_subs() {
   int i, n, one = 1;
   ZSubscription_t sub;
   ZRetrieveSubscriptions(0, &n);
   printf(";;; subscriptions for %s:\n", ZGetSender());
   for (i = 0; i < n; i++) {
      ZGetSubscriptions(&sub, &one);
      printf(";;;    recip \"%s\", class \"%s\", inst \"%s\"\n",
#if (ZVERSIONMAJOR > 0) || (ZVERSIONMINOR >= 2)
	     sub.zsub_recipient, sub.zsub_class, sub.zsub_classinst
#else
	     sub.recipient, sub.class, sub.classinst
#endif
	     );
   }
}


void subscribe() {
   Code_t retval = ZERR_NONE;
   int retry;
   static ZSubscription_t sub[] =
   {/* recipient, class, instance -- wildcard not allowed on class */
    {"%me%", "MESSAGE", "*"},
    {"*", TZC_HEARTBEAT_CLASS, TZC_HEARTBEAT_INSTANCE},
/*    {"%me%", TZC_HEARTBEAT_CLASS, TZC_HEARTBEAT_INSTANCE}, */
#ifdef TEST_XREALM
    {"*@CS612.CMU.EDU", "MESSAGE", "*"},
    {"*@AGRABAH.CS.CMU.EDU", "MESSAGE", "*"},
    {"*@CS.CMU.EDU", "MESSAGE", "*"},
    {"*@ANDREW.CMU.EDU", "MESSAGE", "*"},
#endif
#if DK_TEST_EXTRA_CLASSES
    {"*", "GLOBAL", "*"},
    {"*", "CMU", "*"},
#endif
    {"*", "MESSAGE", "*"}
};
   int n = sizeof(sub) / sizeof(ZSubscription_t);
#if (ZVERSIONMAJOR > 0) || (ZVERSIONMINOR >= 2)
   sub[0].zsub_recipient = ZGetSender();
#else
   sub[0].recipient = ZGetSender();
#endif
   /* sometimes we get a SERVNAK while subscribing, for no apparent reason.
    * so we'll try up to three times */
   for (retry = 0; retry < 3; retry++) {
      if (retry>0) {
         sleep(2);
         printf("; retrying...\n");
	 fflush(stdout);
      }
      /* The cast is necessary for the alpha, because zephyr.h assumes
       * sizeof(int) == sizeof(long) */
      if ((retval = ZSubscribeTo(sub, n, 0)) != (Code_t) ZERR_SERVNAK)
         break;
      printf("; SERVNAK received while attempting to subscribe\n");
      fflush(stdout);
   }
   check(retval, "ZSubscribeTo");
}

void subscribe_with_zctl() {
  int pid;
  FILE *fd;
  char st[1024];
  char setwgfile[1200];
  char *portfile;
  extern char *getenv();

  portfile = getenv("WGFILE");

  if(!portfile) {
    sprintf(st,"/tmp/wg.%ld",(long) getuid());
    portfile = st;
    sprintf(setwgfile,"WGFILE=%s",st);
    if (putenv(setwgfile) != 0) {
	fprintf(stderr,"putenv(\"%s\") failed.",setwgfile);
	bail(1);
    }
  }

  fd = fopen(portfile,"w");
  if(!fd) {
    perror(portfile);
    bail(1);
  }
  fprintf(fd, "%d\n", globals->port);
  fclose(fd);

  if(!(pid = fork())) {
      char fn[1024];
      sprintf(fn,"%s/.zephyr.subs.tzc",getenv("HOME"));
      execlp(ZCTL_BINARY,"zctl","load",fn,(char *)0);
      perror("zctl exec");
      fprintf(stderr,"Unable to load subscriptions.\n");
      bail(0);
    }
  if(pid == -1) {
      perror("zctl exec");
      fprintf(stderr,"Unable to fork and load subscriptions.\n");
    }
  while (pid != wait(0));
}


/*
  like fputs, but quotes the string as necc for 
  reading as a string by gnu-emacs
  */
void fputqs(const char *s, FILE *o) {
   char c;
   putc('\"', o);
   while ((c = *s++)) {
      if (c == '\1') {
	 putc('\\', o);
	 putc('1', o);
#if 0  /* don't want to activate this until i know all the tzc-output parsers
        * out there can handle \t */
      } else if (c == '\t') {
	 /* apparently some zephyr-remote variants don't handle tabs well */
         putc('\\', o);
         putc('t', o);
#endif
      } else {
	 if (c == '\"' || c == '\\')
	    putc('\\', o);
	 putc(c, o);
      }
   }
   putc('\"', o);
}

/* like fputs, but quotes for reading as a symbol by gnu-emacs */
void fputqqs(const char *s, FILE *o) {
   char c;
   if ('\0' == *s) {
      fputs("nil", o);
   } else {
      /* these goofy (int) casts prevent gcc warnings under dux40 */
      if (isdigit((int) *s) || *s == '+' || *s == '-')
	 putc('\\', o);	      /* avoid number/symbol confusion */
      while ((c = *s++)) {
	 if (!(isalnum((int) c) || strchr("-+*/_~!@$%^&=:<>{}", c)))
	    putc('\\', o);
	 putc(c, o);
      }
   }
}

void
emacs_put_open()
{
   fputs("\001(", stdout);
}

void
emacs_put_close()
{
   putc(')', stdout);
   putc('\0', stdout);
   putc('\n', stdout);
   fflush(stdout);
}

void
emacs_put_pair_open(const char *tag)
{
   putc('(', stdout);
   fputqqs(tag, stdout);
   fputs(" . ", stdout);
}

void
emacs_put_pair_close()
{
   fputs(") ", stdout);
}

void
emacs_put_sym(const char *tag, char *sym)
{
   putc('(', stdout);
   fputqqs(tag, stdout);
   fputs(" . ", stdout);
   if (sym[0])
      fputqqs(sym, stdout);
   else
      fputs("nil", stdout);
   fputs(") ", stdout);
}

void
emacs_put_str(const char *tag, const char *str)
{
   putc('(', stdout);
   fputqqs(tag, stdout);
   fputs(" . ", stdout);
   fputqs(str, stdout);
   fputs(") ", stdout);
}

void
emacs_put_int(const char *tag, int i)
{
   putc('(', stdout);
   fputqqs(tag, stdout);
   fputs(" . ", stdout);
   printf("%d", i);
   fputs(") ", stdout);
}

void
emacs_put_str_str(const char *tag, const char *a, const char *b)
{
   putc('(', stdout);
   fputqqs(tag, stdout);
   putc(' ', stdout);
   fputqs(a, stdout);
   fputs(" . ", stdout);
   fputqs(b, stdout);
   fputs(") ", stdout);
}   

void
emacs_error(char *err)
{
   static int reentry = 0;
   if (reentry) {
      /* die a horrible death */
      printf("Looping emacs_error.  Aieee!  I perish in flames!\n");
      exit(5);
   }
   reentry = 1;
   emacs_put_open();
   emacs_put_sym("tzcspew", "error");
   emacs_put_str("message", err);
   emacs_put_close();
   reentry = 0;
}

static void tzc_com_err_hook(const char *whoami, long errcode,
			     const char *fmt, va_list ap)
{
    char buf1[4096], errmsg[4096];

    vsnprintf(buf1, sizeof(buf1), fmt, ap);
    snprintf(errmsg, sizeof(errmsg), "%s: %s %s", 
	     whoami, error_message(errcode), buf1);
    emacs_error(errmsg);
}

char *auth_string(int n) {
   switch (n) {
    case ZAUTH_YES    : return "yes";
    case ZAUTH_FAILED : return "failed";
    case ZAUTH_NO     : return "no";
    default           : return "bad-auth-value";
   }
}
 
char *kind_string(int n) {
   switch (n) {
    case UNSAFE:    return "unsafe";
    case UNACKED:   return "unacked";
    case ACKED:     return "acked";
    case HMACK:     return "hmack";
    case HMCTL:     return "hmctl";
    case SERVACK:   return "servack";
    case SERVNAK:   return "servnak";
    case CLIENTACK: return "clientack";
    case STAT:      return "stat";
    default:        return "bad-kind-value";
   }
}

/* Send a zgram with the specified parameters.
 * Note: the instance and recipient passed in will be free()'d when 
 *       the reply comes back. 
 * Returns zero on success, non-zero if there's a failure sending
 * (recipient not logged in or not subscribing is *not* a "failure sending").
 */
int
send_zgram_to_one(char *class, char *opcode, char *sender,
		  char *instance, char *recipient, 
		  char *message, int message_len, int (*auth)())
{
   ZNotice_t notice;
   int retval;
   char bfr[BUFSIZ];

   memset(&notice, '\0', sizeof(notice));

   notice.z_kind = ACKED;
   notice.z_port = 0;
   notice.z_class = class;
   notice.z_opcode = opcode;
   notice.z_sender = sender;
   notice.z_class_inst = instance;
   notice.z_recipient = recipient;
   notice.z_message = message;
   notice.z_message_len = message_len;
   if (auth == ZAUTH) {
      notice.z_default_format = "Class $class, Instance $instance:\nTo: @bold($recipient) at $time $date\nFrom: @bold($1) <$sender>\n\n$2";
   } else {
      notice.z_default_format = "@bold(UNAUTHENTIC) Class $class, Instance $instance:\nTo: @bold($recipient) at $time $date\nFrom: @bold($1) <$sender>\n\n$2";
   }
   if ((retval = ZSendNotice(&notice, auth)) != ZERR_NONE) {
      (void) sprintf(bfr, "while sending notice to %s", 
		     notice.z_recipient);
      com_err(__FILE__, retval, "%s", bfr);
      /* XXX should probably free instance & recipient here */
      return 1;
   } else {
      /* prepare for reply */
      PendingReply *reply = (PendingReply *) malloc(sizeof(PendingReply));
      reply->instance = notice.z_class_inst; /* freed when reply comes back */
      reply->recipient = notice.z_recipient; /* freed when reply comes back */
      reply->uid = notice.z_uid;
      /* any other info to save? */
      reply->next = globals->pending_replies;
      globals->pending_replies = reply;
      return 0;
   }
}

void
send_zgram(Value *spec)
{
    int (*auth)();
    Value *v;
    Value *recip_list;
    Value *message_list;
    int message_len;
    char *message = 0, *class, *instance, *sender, *recipient, *opcode;

    /* emacs sends something of the form:
     * ((class . "MESSAGE") 
     *  (auth . t)
     *  (recipients ("PERSONAL" . "bovik") ("test" . ""))
     *  (sender . "bovik")
     *  (message . ("Harry Bovik" "my zgram"))
     * )
     */
    /* pull class, sender, auth, recip_list, and message of spec */
    /* class */
    v = assqv(globals->constants.sym_class, spec);
    if (VTAG(v) != cons || VTAG(VCDR(v)) != string) {
       emacs_error("class not defined");
       goto fail;
    }
    class = vextract_string_c(VCDR(v));
    /* opcode */
    v = assqv(globals->constants.sym_opcode, spec);
    if (VTAG(v) != cons) /* ? */
      opcode = "";
    else
      opcode = vextract_string_c(VCDR(v));
    /* recipients */
    v = assqv(globals->constants.sym_recipients, spec);
    if (VTAG(v) != cons) {
       emacs_error("recipients not defined");
       goto fail;
    }
    recip_list = VCDR(v);

    /* sender */
    v = assqv(globals->constants.sym_sender, spec);
    sender = ((VTAG(v) != cons || (VTAG(VCDR(v)) != string)) ? 0 
	      : vextract_string_c(VCDR(v)));

    /* message */
    v = assqv(globals->constants.sym_message, spec);
    if (VTAG(v) != cons) {
       emacs_error("message not defined");
       goto fail;
    }
    message_list = VCDR(v);

    /* auth */
    auth = ZAUTH;
    v = assqv(globals->constants.sym_auth, spec);
    if (VTAG(v) == cons &&
	VTAG(VCDR(v)) == nil)
       auth = ZNOAUTH;

    if (1) {
       /* cdr through the message list, determining total length */
       Value *chase_message_list = message_list;
       char *buffer_mark;
       message_len = 0;
       while (VTAG(chase_message_list) == cons) {
	  Value *one_field = VCAR(chase_message_list);
	  if (VTAG(one_field) != string) {
	    emacs_error("bad (non-string) message component");
	    goto bailout;
	  }
	  message_len += VSLENGTH(one_field) + 1;
	  chase_message_list = VCDR(chase_message_list);
       }

       buffer_mark = message = (char *) malloc(message_len);
       
       /* cdr through again, this time copying strings into the buffer */
       chase_message_list = message_list;
       while (VTAG(chase_message_list) == cons) {
	  Value *one_field = VCAR(chase_message_list);
	  memcpy(buffer_mark, VSDATA(one_field), VSLENGTH(one_field));
	  buffer_mark += VSLENGTH(one_field);
	  *buffer_mark++ = 0;
	  chase_message_list = VCDR(chase_message_list);
       }
    }
    
    /* cdr through the recipient list */
    while (VTAG(recip_list) == cons) {
       Value *recip_pair = VCAR(recip_list);

       if (VTAG(recip_pair) != cons
	   || VTAG(VCAR(recip_pair)) != string
	   || VTAG(VCDR(recip_pair)) != string) {
	  emacs_error("bad recipient");
	  goto bailout;
       }

       /* these strings are freed when the reply comes back in */
       instance = vextract_string_c(VCAR(recip_pair));
       recipient = vextract_string_c(VCDR(recip_pair));
#if 0
#ifdef INTERREALM
       {
	  /* check for an instance with an @ in it */
	  char *realm, *newrecip, *rlm = rindex(instance, '@');

	  if (rlm) {
	     *rlm++ = '\0';
	     realm = ZExpandRealm(rlm);
	     newrecip = (char *) malloc(strlen(recipient)+1+strlen(realm)+1);
	     sprintf(newrecip,"%s@%s",recipient,rlm);
	     free(recipient);
	     recipient = newrecip;
	  }
       }
#endif /* INTERREALM */
#endif

       if (send_zgram_to_one(class, opcode, sender, instance, recipient,
			     message, message_len, auth) != 0)
	  break;
       recip_list = VCDR(recip_list);
    }

  bailout:
  fail:
    if (message) free(message);
}

/* emacs can send ((tzcfodder . ayt)) and tzc will respond with 
 * ((tzcspew . ayt-response))
 */
void
handle_ayt(Value *ayt_cmd)
{
   emacs_put_open();
   emacs_put_sym("tzcspew", "ayt-response");
   emacs_put_close();
}

#if QUERY_HELL
/* return 0 on success */
static int
insert_query(char *id, char *query)
{
  void *compiled_query;

  if ((globals->query_hell_cookie == NULL)
      && ((globals->query_hell_cookie = HellStartup()) == NULL)) {
    /* errmsg = "can't initialize query support"; */
    return 1;
  }
  
  if ((compiled_query = HellCompileQuery(globals->query_hell_cookie,
					 query)) == NULL) {
    /* errmsg = "invalid query"; */
    return 1;
  }

  {
    RegisteredQuery *newq = malloc(sizeof(RegisteredQuery));
    if (newq == NULL) { 
      fprintf(stderr,"tzc.c: out of memory\n");
      bail(1);
    }
    newq->id = strdup(id);
    newq->raw_query = strdup(query);
    newq->compiled_query = compiled_query;
    newq->next = globals->queries;
    globals->queries = newq;
  }
  return 0;
}

static void
free_query(RegisteredQuery *q)
{
  if (q) {
    if (q->id) 
      free(q->id);
    if (q->raw_query) 
      free(q->raw_query);
    if (q->compiled_query)
      HellDeleteQuery(globals->query_hell_cookie, q->compiled_query);
    free(q);
  }
}

/* return 1 if query was found */
static int
remove_query(char *id)
{
  RegisteredQuery **prev, *q;
  for (prev = &globals->queries, q = globals->queries; q != NULL; q=q->next) {
    if (!strcmp(id, q->id)) {
      *prev = q->next;
      free_query(q);
      return 1;
    }
  }
  return 0;
}
#endif /* QUERY_HELL */

void
register_query(Value *register_query_cmd)
{
  char *query = 0, *id = 0;
  char *errmsg = 0;

#if QUERY_HELL
  while (VTAG(register_query_cmd) == cons) {
    Value *pair = VCAR(register_query_cmd);
    Value *tag, *val;
    register_query_cmd = VCDR(register_query_cmd);

    if (VTAG(pair) != cons) {
      errmsg = "bad command format";
      goto done;
    }
    tag = VCAR(pair);
    val = VCDR(pair);
    if (eqv(tag, globals->constants.sym_query) && VTAG(val) == string) {
      query = vextract_string_c(val);
    } else if (eqv(tag, globals->constants.sym_id) && VTAG(val) == symbol) {
      id = vextract_string_c(val);
    } else {
      /* ignore tzcfodder and unknown tags */
    }
  }
  if (id == NULL) {
    errmsg = "id missing or not a symbol";
    goto done;
  }

  /* put this query in the globals->queries linked list */
  (void) remove_query(id);
  if (query && insert_query(id,query) != 0)
    errmsg = "bad query";

#else /* not QUERY_HELL */
  errmsg = "queries not supported";
  goto done;
#endif

done:
  emacs_put_open();
  emacs_put_sym("tzcspew", "register-query-response");
  if (id) emacs_put_sym("id", id);
  if (query) emacs_put_str("query", query);
  if (errmsg) {
    emacs_put_sym("status", "nil");
    emacs_put_str("message", errmsg);
  } else {
    emacs_put_sym("status", "t");
  }
  emacs_put_close();

  if (id) free(id);
  if (query) free(query);
}

void
zsubscribe(Value *subscribe_cmd)
{
   ZSubscription_t *zsubs;
   Value *subs_list, *sub;
   int i, nsubs;
   Value *recip_v, *class_v, *inst_v;
   
   /* emacs sends subscriptions in this form:
    * ((tzcfodder . subscribe)
    *  (class instance recip) (class instance recip) ... ))
    */
   subs_list = VCDR(subscribe_cmd);   /* strip off tzcfodder */

   nsubs = vlength(subs_list);
   zsubs = (ZSubscription_t *) calloc(nsubs,sizeof(ZSubscription_t));
   
   for (i=0; i<nsubs; i++, subs_list = VCDR(subs_list)) {
      sub = VCAR(subs_list);
      if (vlength(sub) != 3) {
	 emacs_error("bad subscription format (sub must have 3 parts)");
	 goto fail;
      }
      class_v = VCAR(sub);
      inst_v = VCAR(VCDR(sub));
      recip_v  = VCAR(VCDR(VCDR(sub)));
      if (VTAG(recip_v) != string ||
	  VTAG(class_v) != string ||
	  VTAG(inst_v) != string) {
	 emacs_error("bad subscription format (non-string)");
	 goto fail;
      }
#if (ZVERSIONMAJOR > 0) || (ZVERSIONMINOR >= 2)
      zsubs[i].zsub_recipient = vextract_string_c(recip_v);
      zsubs[i].zsub_class = vextract_string_c(class_v);
      zsubs[i].zsub_classinst  = vextract_string_c(inst_v);
#else
      zsubs[i].recipient = vextract_string_c(recip_v);
      zsubs[i].class = vextract_string_c(class_v);
      zsubs[i].classinst  = vextract_string_c(inst_v);
#endif
   }
   if (VTAG(subs_list) != nil) {
      emacs_error("bad subscription format");
      goto fail;
   }
   check(ZSubscribeTo(zsubs, nsubs, 0), "ZSubscribeTo");
   emacs_put_open();
   emacs_put_sym("tzcspew", "subscribed");
   emacs_put_close();
 fail:
   for (i--; i>=0; i--) {
#if (ZVERSIONMAJOR > 0) || (ZVERSIONMINOR >= 2)
      free(zsubs[i].zsub_recipient);
      free(zsubs[i].zsub_class);
      free(zsubs[i].zsub_classinst);
#else
      free(zsubs[i].recipient);
      free(zsubs[i].class);
      free(zsubs[i].classinst);
#endif
   }
   free(zsubs);
}

static int
set_location() {
   ZUnsetLocation();	      /* no error checking here */
   if (globals->exposure != NULL) {
#if 1
     /* could allow setting hostnmae too */
     int rc = check(ZInitLocationInfo(NULL, globals->location), 
		    "ZInitLocationInfo");
     if (rc != ZERR_NONE) {
       return rc;
     }
#else
     /* old libzephyr didn't support ZInitLocationInfo, so we had to	
      * resort to this: */
      char *setdisplay = malloc(strlen("DISPLAY=")
				+ strlen(globals->location)
				+ 1);
      if (setdisplay == NULL) {
         fprintf(stderr, "tzc.c: out of memory\n");
	 bail(1);
      }
      sprintf(setdisplay, "DISPLAY=%s", globals->location);
      if (putenv(setdisplay) != 0) {
         fprintf(stderr, "putenv(\"%s\") failed.", setdisplay);
	 bail(1);
      }
#endif
      return check(ZSetLocation(globals->exposure), "ZSetLocation");
   } else {
     return ZERR_NONE;
   }
}

static void
report_location()
{
   emacs_put_open();
   emacs_put_sym("tzcspew", "location");
   emacs_put_str("location", globals->location);
   emacs_put_str("exposure", 
		 globals->exposure == NULL ? "NONE" : globals->exposure);
   emacs_put_close();
}

static void
handle_get_location(Value *getloc_cmd)
{
    report_location();
}

static void
handle_set_location(Value *setloc_cmd)
{
   char *new_exposure = NULL, *new_location = NULL;
   int new_exposure_given = 0, new_location_given = 0;
   Value *exposure_v, *location_v;
   /* emacs sends subscriptions in this form:
    * ((tzcfodder . set-location)
    *    (exposure . "NET-ANNOUNCED")     ; optional - default is current exp.
    *                                     ; (value nil means no exposure)
    *    (location . "tzc.123")           ; optional - default is current loc
    *  )
    * a nil or non-existent value is interpreted as no-exposure
    */
   setloc_cmd = VCDR(setloc_cmd);   /* strip off tzcfodder */
   exposure_v = assqv(globals->constants.sym_exposure, setloc_cmd);
   location_v = assqv(globals->constants.sym_location, setloc_cmd);

   if (exposure_v != NULL) {
     Value *exposure_str = VCDR(exposure_v);
     if (exposure_str == NULL) {
       new_exposure_given = 1;
       new_exposure = NULL;
     } else if (VTAG(exposure_str) == string) {
       new_exposure_given = 1;
       if (0 == strcasecmp(globals->exposure, "NONE")) {
	 new_exposure = NULL;
       } else {
	 new_exposure = vextract_string_c(exposure_str);
       }
     } else {
       emacs_error("bad exposure argument in set-location");
       goto fail;
     }
   }

   if (location_v != NULL) {
     Value *location_str = VCDR(location_v);
     if (location_str != NULL
	 && VTAG(location_str) == string) {
       new_location_given = 1;
       new_location = vextract_string_c(location_str);
     } else {
       emacs_error("bad location argument in set-location");
       goto fail;
     }
   }

   if (new_location_given) {
     free(globals->location);
     globals->location = new_location;
   }
   if (new_exposure_given) {
     if (globals->exposure) 
       free(globals->exposure);
     globals->exposure = new_exposure;
   }

   if (new_location_given || new_exposure_given) {
     if (set_location() != ZERR_NONE) {
       return;
     }
   }
   report_location();

 fail:
   /* nothing to do */
   return;
}


void
process_sexp(Value *v)
{
   Value *pair;
   Value *key;

#if 0
   printf("read: ");
   prin(stdout, v);
   fputc('\n', stdout);
#endif

   if (VTAG(v) == cons &&
       NULL != (pair = assqv(globals->constants.sym_tzcfodder, v)) &&
       NULL != (key = VCDR(pair))) {
      if (eqv(key, globals->constants.sym_send))
	 send_zgram(v);
      else if (eqv(key, globals->constants.sym_subscribe))
	 zsubscribe(v);
      else if (eqv(key, globals->constants.sym_set_location))
	 handle_set_location(v);
      else if (eqv(key, globals->constants.sym_get_location))
	 handle_get_location(v);
      else if (eqv(key, globals->constants.sym_ayt))
	 handle_ayt(v);
      else if (eqv(key, globals->constants.sym_register_query))
	 register_query(v);
      else
	{
	  char *err = malloc(VSLENGTH(key) + 30);
	  char *key_str = vextract_string_c(key);
	  if (err && key) {
	    sprintf(err, "bad tzcfodder key: `%s'", key_str);
	    emacs_error(err);
	    free(err);
	    free(key_str);
	  } else {
	    fprintf(stderr,"tzc.c: out of memory\n");
	    bail(1);
	  }
	}
   } else {
      emacs_error("no tzcfodder key");
   }

#if 0
	 printf("parsed: ");
	 prin(stdout, v);
	 fputc('\n', stdout);
	 if (destructure(pattern, v)) {
	    printf("match_data = ");
	    prin(stdout, match_data);
	    fputc('\n', stdout);
	 }
	 else {
	    printf("destructure failed\n");
	 }
#endif
}

int
read_emacs()
{
   int ret;
   Value *v;
   
   /* if the buffer is full, expand it*/
   if (globals->ebufptr - globals->ebuf >= globals->ebufsiz) {
      char *new_buf;
      globals->ebufsiz *= 2;
      new_buf = (char *) malloc(globals->ebufsiz);
      memcpy(new_buf, globals->ebuf, globals->ebufptr - globals->ebuf);
      globals->ebufptr = new_buf + (globals->ebufptr - globals->ebuf);
      free(globals->ebuf);
      globals->ebuf = new_buf;
   }

   /* read up to size of buffer */
   ret = read(0, globals->ebufptr,
	      globals->ebufsiz - (globals->ebufptr - globals->ebuf));
   if (ret == 0) {
      return -1;
   } else if (ret < 0) {
      if (errno != EWOULDBLOCK) {
	 perror("reading from emacs");
	 bail(1);
      }
   } else {
      globals->ebufptr += ret;
   }

   /* parse & process all available input from emacs */
   do {
#if 1
#ifndef MIN
#define MIN(a,b) ((a)<(b) ? (a) : (b))
#endif
      if (globals->debug) {
	int len = globals->ebufptr - globals->ebuf;
	char thestr[4096];
	strncpy(thestr,globals->ebuf,MIN(len,4096));
	thestr[len] = '\0';
	if (thestr[len-1] == '\n')
	  thestr[len-1] = '\0';
	printf(";;; parsing string [[[%s]]]\n", thestr);
      }
#endif
      ret = parse(globals->ebufptr - globals->ebuf,
		  globals->ebuf, &v);
#if 0
      printf("parse returned %d\n",ret);
#endif
      if (ret > 0) {
	 memcpy(globals->ebuf, globals->ebuf + ret,
	       (globals->ebufptr - globals->ebuf) - ret);
	 globals->ebufptr -= ret;

	 process_sexp(v);

	 free_value(v);
      }
   } while (ret > 0);
   return 0;
}

void say_hi() {
   printf("; tzc is free software and you are welcome to distribute copies\n");
   printf("; of it under certain conditions; see the source code for details.\n");
   printf("; Version %s\n",TZC_VERSION);
   printf("; Copyright 1992, 1993 Scott Draves\n");
   printf("; Copyright 1994, 1995, 1996, 1998, 2000 Darrell Kindred\n");
   printf("; Started: %s\n\n", time_str(time(0)));
   fflush(stdout);
}

void reset_heartbeat() {
   int fuzz;
   globals->heartbeat.status = HB_ENABLED;
   /* add +/- 20% random fuzz to the period to prevent everyone from 
    * pounding the server at once */
   fuzz = globals->heartbeat.period / 5;
   globals->heartbeat.wakeup = time(0) + globals->heartbeat.period + 
                        (random() % 1000 - 500) * fuzz / 500;
   if (globals->debug) {
      printf(";;; %s ",debug_time_str(time(0)));
      printf("reset heartbeat (will wake up at %s)\n",
             debug_time_str(globals->heartbeat.wakeup));
      fflush(stdout);
   }
}

void
setup(int use_zctl)
{
   /* set stdin up for nonblocking reads, saving previous flags so we can */
   /* restore them later */
   if (globals->use_stdin) {
      if (-1 == (globals->stdin_flags = fcntl(0, F_GETFL, 0))) {
         perror("fcntl(0, F_GETFL)");
         exit(1);
      }
      if (-1 == (fcntl(0, F_SETFL, globals->stdin_flags | FNDELAY))) {
         perror("fcntl(0, F_SETFL)");
         bail(1);
      }
   }

   /* if there were an easy way to block-buffer stdout
      i'd do it here */

   /* have com_err send elisp errors rather than just printing to stderr */
   set_com_err_hook(tzc_com_err_hook);

   check(ZInitialize(), "ZInitialize");
   globals->port = 0;
   check(ZOpenPort(&globals->port), "ZOpenPort");

   if ((globals->zfd= ZGetFD()) < 0) {
      perror("ZGetFD");
      bail(1);
   }

   if (use_zctl)
      subscribe_with_zctl();
   else
      subscribe();
   if (globals->debug) {
      printf(";;; %s done with zsubscribe\n",debug_time_str(time(0)));
      list_subs();
      fflush(stdout);
   }

#if QUERY_HELL
   globals->queries = NULL;
   globals->query_hell_cookie = NULL;
#endif

   globals->ebufsiz = 256;
   globals->ebuf = (char *) malloc(globals->ebufsiz);
   globals->ebufptr = globals->ebuf;

   if (globals->heartbeat.status != HB_DISABLED) {
     reset_heartbeat();
   }

   globals->pending_replies = NULL;

   globals->constants.sym_class = vmake_symbol_c("class");
   globals->constants.sym_instance = vmake_symbol_c("instance");
   globals->constants.sym_recipients = vmake_symbol_c("recipients");
   globals->constants.sym_sender = vmake_symbol_c("sender");
   globals->constants.sym_message = vmake_symbol_c("message");
   globals->constants.sym_send = vmake_symbol_c("send");
   globals->constants.sym_tzcfodder = vmake_symbol_c("tzcfodder");
   globals->constants.sym_auth = vmake_symbol_c("auth");
   globals->constants.sym_subscribe = vmake_symbol_c("subscribe");
   globals->constants.sym_set_location = vmake_symbol_c("set-location");
   globals->constants.sym_exposure = vmake_symbol_c("exposure");
   globals->constants.sym_location = vmake_symbol_c("location");
   globals->constants.sym_ayt = vmake_symbol_c("ayt");
   globals->constants.sym_register_query = vmake_symbol_c("register-query");
   globals->constants.sym_query = vmake_symbol_c("query");
   globals->constants.sym_id = vmake_symbol_c("id");
   globals->constants.sym_opcode = vmake_symbol_c("opcode");
}

void
await_input(int *emacs_in, int *zephyr_in)
{
   struct timeval t, *timeout;
   fd_set fdset;

   *emacs_in = *zephyr_in = 0;

   if (ZPending() > 0) {
      *zephyr_in = 1;
      return;
   }

   FD_ZERO(&fdset);
   if (globals->use_stdin)
      FD_SET(0, &fdset);		/* stdin from emacs */
   FD_SET(globals->zfd, &fdset);	/* Zephyr incoming */

   if (globals->heartbeat.status == HB_ENABLED ||
       globals->heartbeat.status == HB_TESTING) {
#if 0
      /* If we print stuff here, zephyr.el can get confused and think
       * we've printed an error message because of the
       *  (if (not (equal log-buffer-size (buffer-size)))
       * test in zephyr-send. */
      if (globals->debug) {
	 printf(";;; %s doing select,", debug_time_str(time(0)));
	 printf(" will wake up at %s (%d secs)\n", 
		debug_time_str(globals->heartbeat.wakeup),
		globals->heartbeat.wakeup - time(0));
	 fflush(stdout);
      }
#endif
      /* add 2s just to be sure we don't wake up too soon. */
      t.tv_sec = globals->heartbeat.wakeup - time(0) + 2;
      t.tv_usec = 0;
      timeout = &t;
   } else {
      timeout = NULL;
   }
   
   if (select(globals->zfd + 1, &fdset, NULL, NULL, timeout) < 0) {
      perror("select");
   } else {
      *emacs_in = globals->use_stdin ? FD_ISSET(0, &fdset) : 0;
      *zephyr_in = FD_ISSET(globals->zfd, &fdset);
      /* this didn't work - we'll just assume that a whole packet
       * will arrive soon after anything shows up on the input
       if (*zephyr_in)
       if (warn(ZPending(), "ZPending") < 1)
       *zephyr_in = 0;
       */
   }
}

#if QUERY_HELL
/* This produces the following format (from the zarchive server spec):
     Each zephyrgram consists of these
     seven fields in the given order, each terminated by an ASCII 0 (NUL):
        sender, signature, timestring, instance, body, timesecs, archived
     The whole zephyrgram is terminated by an ASCII 1 (^A).
   The "archived" flag is always set to 1.
   The returned value should be freed by the caller.
 */
int zgram_to_zarchive_format (ZNotice_t *notice, char **zgram) 
{
  int total_len;
  char *time_string = time_str(notice->z_time.tv_sec);
  char time_secs[20];
  char *archived = "1";
  char *sig = "", *body = "";
  int sig_len, body_len;

  sprintf(time_secs, "%d", notice->z_time.tv_sec);

  for (sig_len = 0; sig_len < notice->z_message_len; sig_len++)
    if (notice->z_message[sig_len] == '\0')
      break;
  sig = notice->z_message;

  for (body_len=0; sig_len + 1 + body_len < notice->z_message_len; body_len++)
    if (notice->z_message[sig_len + 1 + body_len] == '\0') 
      break;
  body = notice->z_message + sig_len + 1;

  total_len = (strlen(notice->z_sender)       + 1
	       + sig_len                      + 1
	       + strlen(time_string)          + 1
	       + strlen(notice->z_class_inst) + 1
	       + body_len                     + 1
	       + strlen(time_secs)	      + 1
	       + strlen(archived)             + 1
	       + 1  /* for the \001 */
	       );

  if ((*zgram = malloc(total_len)) == NULL) {
    fprintf(stderr,"tzc.c: out of memory\n");
    bail(1);
  }
  {
    char *p = *zgram;
    memset(p, 0, total_len);

    strcpy(p, notice->z_sender);
    p += strlen(notice->z_sender) + 1;

    strncpy(p, sig, sig_len);
    p += sig_len + 1;

    strcpy(p, time_string);
    p += strlen(time_string) + 1;
    
    strcpy(p, notice->z_class_inst);
    p += strlen(notice->z_class_inst) + 1;

    strncpy(p, body, body_len);
    p += body_len + 1; 

    strcpy(p, time_secs);
    p += strlen(time_secs) + 1;

    strcpy(p, archived);
    p += strlen(archived) + 1;

    *p++ = '\001';

    if (p - *zgram != total_len) {
      fprintf(stderr,"tzc.c: internal bug #24601 (%d/%d)\n",
	      (int) (p - *zgram), total_len);
      bail(1);
    }
  }

  return total_len;
}

/* this will print (query . ((q1 . nil) (q2 . t) (q3 . t)))
 * to indicate the queries matched and not matched by this zgram
 */
void 
check_queries(ZNotice_t *notice) {
  RegisteredQuery *q = globals->queries;
  if (q) {
    char *zgram;
    int zgram_len = zgram_to_zarchive_format (notice, &zgram);

    /* XXX debug */
    emacs_put_int("encoded-zgram-len", zgram_len);
#if 0
    printf("\nzgram: ");
    fwrite(zgram, zgram_len, 1, stdout);
    printf("\n");
#endif      
    emacs_put_pair_open("queries");
    putc('(', stdout);
    while (q) {
      int match = HellEvaluateQuery(globals->query_hell_cookie, 
				    q->compiled_query,
				    zgram, zgram_len);
      emacs_put_sym(q->id, match ? "t" : "nil");
      q = q->next;
    }
    putc(')', stdout);
    emacs_put_pair_close();
  }
}
#endif /* QUERY_HELL */

void
report_zgram(ZNotice_t *notice, int auth)
{
      int i, len, forced_termination;
      const char *from_host;
      char *p, *instance, *recipient;
      struct hostent *hst;
      int lag = 0, lag_valid = 0;

      /* convert IP# of sender into ascii name */
      hst = gethostbyaddr((char *)&notice->z_sender_addr,
			  sizeof(notice->z_sender_addr), AF_INET);
      from_host = hst ? hst->h_name : inet_ntoa(notice->z_sender_addr);

      /* abbreviate sender by throwing away realm if it's local */
      p = strchr(notice->z_sender, '@');
      if (p && !strcmp(p+1, ZGetRealm()))
	 *p = '\0';

      /* ditto for recipient */
      p = strchr(notice->z_recipient, '@');
      if (p && !strcmp(p+1, ZGetRealm()))
	 *p = '\0';

      /* Class is supposed to be case-insensitive, so we could
       * convert to upper-case here, but we'll leave it to emacs
       * to decide what to do.  It's a bit inconvenient that we
       * send class as a symbol rather than a string, but emacs
       * can use symbol-name and then convert to uppercase. */
#if 0
      for (p = notice->z_class; *p != '\0'; p++) {
         if (islower(*p))
            (*p) = toupper(*p);
      }
#endif

      if (globals->debug) {
	 if (globals->heartbeat.status == HB_TESTING) {
	    lag = HEARTBEAT_TIMEOUT - (globals->heartbeat.wakeup - time(0));
	    lag_valid = 1;
	 } else {
	    lag_valid = 0;
         }
      }

      /* zephyr server is still talking to us, so reset the heartbeat */
      if (globals->heartbeat.status != HB_DISABLED) {
        reset_heartbeat();
      }

      /* if this is a heartbeat zgram, don't report it */
      if (!strcasecmp(notice->z_class, TZC_HEARTBEAT_CLASS) &&
	  !strcasecmp(notice->z_class_inst, TZC_HEARTBEAT_INSTANCE)) {
	 if (globals->debug) {
	    printf(";;; %s received heartbeat zgram from %s on %s",
		   debug_time_str(time(0)),
		   notice->z_sender, from_host);
	    if (lag_valid) {
		    printf(" after %d seconds",lag);
	    }
	    printf("\n");
	    fflush(stdout);
	 }
         return;
      }
      /* XXX one of these days we need to check return values from all
       * these mallocs */
      /* XXX can we assume that z_recipient and z_class_inst are not NULL? */
#ifdef INTERREALM
#if 0
      /* if recipient is "@SOMEREALM" then use empty recipient & 
       * add "@SOMEREALM" to the instance */
      if (notice->z_recipient[0]=='@') {
	 instance = (char *) malloc(strlen(notice->z_class_inst)+
				    strlen(notice->z_recipient)+1);
	 strcpy(instance, notice->z_class_inst);
	 strcat(instance, notice->z_recipient);
	 recipient = (char *) malloc(1);
	 recipient[0] = '\0';
      } else
#endif
#endif /* INTERREALM */
      {
	 instance = (char *) malloc(strlen(notice->z_class_inst)+1);
	 strcpy(instance, notice->z_class_inst);
	 recipient = (char *) malloc(strlen(notice->z_recipient)+1);
	 strcpy(recipient, notice->z_recipient);
      }

      emacs_put_open();
      emacs_put_sym("tzcspew", "message");
      emacs_put_sym("kind", kind_string(notice->z_kind));

#if QUERY_HELL
      check_queries(notice);
#endif

#if TZC_CLASS_IS_SYMBOL
      emacs_put_sym
#else
      emacs_put_str
#endif
	           ("class", notice->z_class);
      emacs_put_str("instance", instance);
#if TZC_OPCODE_IS_SYMBOL
      emacs_put_sym
#else
      emacs_put_str
#endif
                   ("opcode", notice->z_opcode);
      emacs_put_str("sender", notice->z_sender);
      emacs_put_str("recipient", recipient);
      emacs_put_int("port", notice->z_port);
      emacs_put_sym("auth", auth_string(auth));
      emacs_put_str("time", time_str(notice->z_time.tv_sec));
      if (notice->z_time.tv_usec > 999999
	  || notice->z_time.tv_usec < 0) {
	  char buf[80];
	  sprintf(buf, "tv_sec=%lu tv_usec=%lu", 
		  (unsigned long) notice->z_time.tv_sec,
		  (unsigned long) notice->z_time.tv_usec);
	  emacs_put_str("malformed-time-stamp", buf);
          notice->z_time.tv_usec = 0;
      }
      emacs_put_pair_open("time-secs");
      fprintf(stdout, "(%d %d %d)", 
	      (int) (notice->z_time.tv_sec >> 16),
	      (int) (notice->z_time.tv_sec & 0xffff), 
	      (int) notice->z_time.tv_usec);
      emacs_put_pair_close();
#if 1
/* dsk### just for timing tests */
      {
	      struct timeval tv;
	      double latency;
	      gettimeofday(&tv, NULL);
	      latency = tv.tv_sec - notice->z_time.tv_sec +
		        (tv.tv_usec - notice->z_time.tv_usec) / 1000000.0;
	      emacs_put_pair_open("latency");
	      fprintf(stdout, "\"%.2f\"", latency);
	      emacs_put_pair_close();
      }
#endif
      emacs_put_str("fromhost", from_host);

      emacs_put_pair_open("message");
      putc('(', stdout);

      p = notice->z_message;
      len = notice->z_message_len;
      forced_termination = 0;
      
      if (p[len-1]) {
	 /* force null termination */
	 p = (char *) malloc(len+1);
	 memcpy(p, notice->z_message, len);
	 p[len] = '\0';
	 len += 1;
	 forced_termination = 1;
      }
      for (i = 0; i < len; i++) {
#if 0
      {
	 FILE *f = fopen("/tmp/blah","a");
	 fprintf(f,"[[message part: %s]]\n",p+i);
	 fclose(f);
      }		
#endif
	 fputqs(p+i, stdout);
	 putc(' ', stdout);
	 i += strlen(p+i);
      }
      putc(')', stdout);
      emacs_put_pair_close();

      if (forced_termination) {
 	 /* no real need to report this.
	    emacs_put_sym("forced-termination", "t"); */
	 free(p);
      }

      emacs_put_close();

      free(instance);
      free(recipient);

#if 0
      fputs("(kind . ", stdout);
      fputs(kind_string(notice->z_kind), stdout);
      fputs(") (class . ", stdout);
      fputqqs(notice->z_class, stdout);
      fputs(") (instance . ", stdout);
      fputqs(notice->z_class_inst, stdout);
      fputs(") (opcode . ", stdout);
      fputqqs(notice->z_opcode, stdout);
      fputs(") (sender . ", stdout);
      fputqs(notice->z_sender, stdout);
      fputs(") (recipient . ", stdout);
      if (notice->z_recipient[0])
	 fputqs(notice->z_recipient, stdout);
      else
	 fputs("nil", stdout);
      fprintf(stdout,
	      ") (port . %d) (auth . %s) (time . \"%s\") (fromhost . ",
	      notice->z_port, auth_string(auth), 
	      time_str(notice->z_time.tv_sec));
      fputqs(from_host, stdout);
      fputs(") (message . (", stdout);
#endif
}

void
process_reply(ZNotice_t *notice, int auth)
{
   PendingReply **link;
   PendingReply *reply = NULL;

   /* remove from the pending reply list */
   link = &globals->pending_replies;
   while (*link != NULL) {
      if (ZCompareUID(&notice->z_uid, &(*link)->uid)) {
	 reply = *link;
	 *link = (*link)->next;
	 break;
      }
      link = &(*link)->next;
   }

   if (NULL == reply)
      /* who called us, anyway ? */
      return;

   /* ignore replies to heartbeat zgrams */
   if (!strcmp(notice->z_class, TZC_HEARTBEAT_CLASS) &&
       !strcmp(notice->z_class_inst, TZC_HEARTBEAT_INSTANCE)) {
      /* it's a reply to a heartbeat zgram--ignore it */
      if (globals->debug) {
         printf(";;; %s received %s for heartbeat zgram\n",
		debug_time_str(time(0)),
		strcmp(notice->z_message, ZSRVACK_SENT) ? "NACK" : "ACK");
	 fflush(stdout);
      }
   } else {
      /* genuine reply, deal with it */
      switch (notice->z_kind) {
       case SERVACK:
	 if (!strcmp(notice->z_message, ZSRVACK_SENT)) {
	    /* tell emacs message sent successfully */
	    emacs_put_open();
	    emacs_put_sym("tzcspew", "sent");
	    emacs_put_str_str("to", reply->instance, reply->recipient);
	    emacs_put_close();
	 } else if (!strcmp(notice->z_message, ZSRVACK_NOTSENT)) {
	    emacs_put_open();
	    emacs_put_sym("tzcspew", "not-sent");
	    emacs_put_str_str("to", reply->instance, reply->recipient);
	    emacs_put_close();
	 } else {
	    /* oh nooooo! */
	    emacs_put_open();
	    emacs_put_sym("tzcspew", "error");
	    emacs_put_str("message", "bad reply code");
	    emacs_put_int("code", notice->z_kind);
	    emacs_put_close();
	 }
	 break;

       case SERVNAK:
	 /* tell emacs authorization failure */
	 emacs_error("authorization failure");
	 break;

       default:
	 /* server failure when receiving acknowledgement */
	 emacs_error("server failure when processing acknowledgement");
	 break;
      }
   }

   free(reply->instance);
   free(reply->recipient);
   free(reply);
}

void
read_zephyr()
{
   ZNotice_t notice;
   struct sockaddr_in from;
   int auth;
   int expected_reply;
   PendingReply *reply;

   while (ZPending() > 0) {
      expected_reply = 0;

      warn(ZReceiveNotice(&notice, &from), "ZReceiveNotice");
      auth = ZCheckAuthentication(&notice, &from);

      if (notice.z_kind != ACKED) {
	 /* check to see whether this is an ack/nak or whether it is new
	  * incoming info */
	 reply = globals->pending_replies;
	 while (reply != NULL) {
	    if (ZCompareUID(&notice.z_uid, &reply->uid)) {
	       expected_reply = 1;
	       break;
	    }
	    reply = reply->next;
	 }
      }

      if (expected_reply)
	 process_reply(&notice, auth);
      else
	 report_zgram(&notice, auth);

      (void) ZFreeNotice(&notice);
   }
}

void
send_heartbeat_zgram()
{
   /* send a zgram on a special class/instance to see if the zephyr
    * server is still talking to us. */

   char *recipient, *instance;
   
   instance = malloc(sizeof(TZC_HEARTBEAT_INSTANCE));
   strcpy(instance, TZC_HEARTBEAT_INSTANCE);

   /* broadcast the heartbeat */
   recipient = strcpy(malloc(sizeof("")),"");

   if (send_zgram_to_one(TZC_HEARTBEAT_CLASS, "", NULL,
			 instance, recipient,
                         TZC_HEARTBEAT_MESSAGE,
			 sizeof(TZC_HEARTBEAT_MESSAGE), ZNOAUTH) != 0) {
      /* failed, but we don't care. */
   }
}


void check_heartbeat() {
   if (time(0) >= globals->heartbeat.wakeup) {
      if (globals->heartbeat.status == HB_TESTING) {
	 /* Looks like the server has forgotten about us. */
	 /* We could automatically resubscribe here, but we'll just
	  * let emacs decide what to do. */

	 /* Send the warning message */
	 emacs_put_open();
	 emacs_put_sym("tzcspew", "cutoff");
	 emacs_put_close();
	 /* reset flags */
	 reset_heartbeat();
      } else if (globals->heartbeat.status == HB_ENABLED) {
	 send_heartbeat_zgram();
	 globals->heartbeat.status = HB_TESTING;
	 globals->heartbeat.wakeup = time(0) + globals->heartbeat.timeout;
	 if (globals->debug) {
		 printf(";;; %s ",debug_time_str(time(0)));
		 printf("sent heartbeat zgram, will timeout at %s\n",
			debug_time_str(globals->heartbeat.wakeup));
	 }
      }
   }
}

void reset_alarm(long alarm_rate) {
   if (alarm_rate > 0) {
      struct itimerval value;
      value.it_interval.tv_usec = 0;
      value.it_interval.tv_sec = alarm_rate;
      value.it_value.tv_usec = 0;
      value.it_value.tv_sec = alarm_rate;
      setitimer(ITIMER_REAL, &value, (struct itimerval *)0);
   }
}

int main(int argc, char *argv[]) {
   const char *program;
   int use_zctl = 0, sw;
   extern char *optarg;
   long restart_rate = 0;	/* In seconds; zero disables auto restart */

   globals = &global_storage;
   program = strrchr(argv[0], '/');
   if (program == NULL)
      program = argv[0];
   else
      program++;
   globals->program = program;
   globals->argc = argc;
   globals->argv = argv;
   globals->pidfile = NULL;
   globals->exposure = NULL;
   globals->use_stdin = 1;
   globals->ignore_eof = 0;
   globals->heartbeat.status = HB_ENABLED;
   globals->heartbeat.period = HEARTBEAT_PERIOD_DEF;
   globals->heartbeat.timeout = HEARTBEAT_TIMEOUT;

   globals->debug = 0;

   srandom(time(0)+getpid());

   globals->location = malloc(strlen("tzc.")+16+1);
   if (globals->location == NULL) {
     fprintf(stderr,"tzc.c: out of memory\n");
     bail(1);
   }
   sprintf(globals->location,"tzc.%d",(int) getpid());

   say_hi();

   signal(SIGUSR1, restart_tzc);
   signal(SIGALRM, restart_tzc);
   signal(SIGINT, kill_tzc);
   signal(SIGHUP, kill_tzc);
   signal(SIGTERM, kill_tzc);
   signal(SIGQUIT, kill_tzc);

   while ((sw = getopt(argc, argv, "sa:e:p:l:noidt:")) != EOF)
      switch (sw) {
       case 's':
	 use_zctl = 1;
	 /* XXX we can't guarantee that the user has subscribed to
	  *     the heartbeat class/inst, so disable it to be safe.
          *     Could check it with ZGetSubscriptions(). */
	 globals->heartbeat.status = HB_DISABLED;
	 break;
       case 'e':
	 if (globals->exposure) {
	   free(globals->exposure);
	 }
	 globals->exposure = strdup(optarg);
	 break;
       case 'a':
	 restart_rate = atoi(optarg);
	 break;
       case 't':
	 globals->heartbeat.period = atoi(optarg);
	 if (globals->heartbeat.period == 0)
	    globals->heartbeat.status = HB_DISABLED;
         break;
       case 'd':
	 globals->debug = 1;
	 break;
       case 'p':
	 if (1) {
	    FILE *f = fopen(optarg, "w");
	    globals->pidfile = optarg;
	    if (f) {
	       fprintf(f, "%d\n", (int) getpid());
	       fclose(f);
	    } else {
	       perror(optarg);
	       exit(1);
	    }
	 }
	 break;
       case 'l':
	 free(globals->location);
	 globals->location = strdup(optarg);
	 break;
       case 'o':
	 globals->use_stdin = 0;
	 break;
       case 'i':
	 globals->ignore_eof = 1;
	 break;
       case '?':
       default:
	 usage();
	 bail(1);
      }

   setup(use_zctl);

   set_location();

   reset_alarm(restart_rate);

   emacs_put_open();
   emacs_put_sym("tzcspew", "start");
   emacs_put_str("version", TZC_VERSION);
   emacs_put_int("pid",getpid());
   emacs_put_str("zephyrid", ZGetSender());
   emacs_put_str("exposure", globals->exposure==NULL?"NONE":globals->exposure);
   emacs_put_sym("heartbeat", globals->heartbeat.status == HB_DISABLED ?
		 "nil" : "t");
   emacs_put_str("time" , time_str(time(0)));
   emacs_put_pair_open("features");
   putc('(', stdout);
#if QUERY_HELL
   fputqqs("queries", stdout);	putc(' ', stdout);
#endif   
   putc(')', stdout);   
   emacs_put_pair_close();

   emacs_put_close();

   while (1) {
      int emacs_in, zephyr_in;

      await_input(&emacs_in, &zephyr_in);

      /* if emacs input ready, add it to a buffer */
      if (emacs_in) {
 	 if (read_emacs() != 0) {
	    if (globals->ignore_eof) {
               emacs_in = 0;
	       globals->use_stdin = 0;
	    } else {
	       exit_tzc();	/* EOF: emacs or socket disappeared. */
	    }
	 }
      }
      if (zephyr_in) {
	 reset_alarm(restart_rate);
	 read_zephyr();
      }

      check_heartbeat();
   }
}