]> asedeno.scripts.mit.edu Git - 1ts-debian.git/blob - zephyr/lib/Zinternal.c
57ee9b3bd7d51ec81c7ec2e391aeb3b4a79e87db
[1ts-debian.git] / zephyr / lib / Zinternal.c
1 /* This file is part of the Project Athena Zephyr Notification System.
2  * It contains source for the internal Zephyr routines.
3  *
4  *      Created by:     Robert French
5  *
6  *      $Id: Zinternal.c,v 1.41 2000/01/27 03:48:53 ghudson Exp $
7  *
8  *      Copyright (c) 1987,1988,1991 by the Massachusetts Institute of
9  *      Technology.
10  *      For copying and distribution information, see the file
11  *      "mit-copyright.h". 
12  */
13
14 #include <internal.h>
15 #include <arpa/inet.h>
16 #include <sys/socket.h>
17 #include <utmp.h>
18
19 #ifndef lint
20 static const char rcsid_Zinternal_c[] =
21   "$Id: Zinternal.c,v 1.41 2000/01/27 03:48:53 ghudson Exp $";
22 static const char copyright[] =
23   "Copyright (c) 1987,1988,1991 by the Massachusetts Institute of Technology.";
24 #endif
25
26 extern char *inet_ntoa ();
27
28 int __Zephyr_fd = -1;
29 int __Zephyr_open;
30 int __Zephyr_port = -1;
31 struct in_addr __My_addr;
32 int __Q_CompleteLength;
33 int __Q_Size;
34 struct _Z_InputQ *__Q_Head, *__Q_Tail;
35 struct sockaddr_in __HM_addr;
36 struct sockaddr_in __HM_addr_real;
37 int __HM_set;
38 int __Zephyr_server;
39 ZLocations_t *__locate_list;
40 int __locate_num;
41 int __locate_next;
42 ZSubscription_t *__subscriptions_list;
43 int __subscriptions_num;
44 int __subscriptions_next;
45 int Z_discarded_packets = 0;
46
47 #ifdef HAVE_KRB4
48 C_Block __Zephyr_session;
49 #endif
50 char __Zephyr_realm[REALM_SZ];
51
52 #ifdef Z_DEBUG
53 void (*__Z_debug_print) __P((const char *fmt, va_list args, void *closure));
54 void *__Z_debug_print_closure;
55 #endif
56
57 #define min(a,b) ((a)<(b)?(a):(b))
58
59 static int Z_AddField __P((char **ptr, char *field, char *end));
60 static int find_or_insert_uid __P((ZUnique_Id_t *uid, ZNotice_Kind_t kind));
61
62 /* Find or insert uid in the old uids buffer.  The buffer is a sorted
63  * circular queue.  We make the assumption that most packets arrive in
64  * order, so we can usually search for a uid or insert it into the buffer
65  * by looking back just a few entries from the end.  Since this code is
66  * only executed by the client, the implementation isn't microoptimized. */
67 static int find_or_insert_uid(uid, kind)
68     ZUnique_Id_t *uid;
69     ZNotice_Kind_t kind;
70 {
71     static struct _filter {
72         ZUnique_Id_t    uid;
73         ZNotice_Kind_t  kind;
74         time_t          t;
75     } *buffer;
76     static long size;
77     static long start;
78     static long num;
79
80     time_t now;
81     struct _filter *new;
82     long i, j, new_size;
83     int result;
84
85     /* Initialize the uid buffer if it hasn't been done already. */
86     if (!buffer) {
87         size = Z_INITFILTERSIZE;
88         buffer = (struct _filter *) malloc(size * sizeof(*buffer));
89         if (!buffer)
90             return 0;
91     }
92
93     /* Age the uid buffer, discarding any uids older than the clock skew. */
94     time(&now);
95     while (num && (now - buffer[start % size].t) > CLOCK_SKEW)
96         start++, num--;
97     start %= size;
98
99     /* Make room for a new uid, since we'll probably have to insert one. */
100     if (num == size) {
101         new_size = size * 2 + 2;
102         new = (struct _filter *) malloc(new_size * sizeof(*new));
103         if (!new)
104             return 0;
105         for (i = 0; i < num; i++)
106             new[i] = buffer[(start + i) % size];
107         free(buffer);
108         buffer = new;
109         size = new_size;
110         start = 0;
111     }
112
113     /* Search for this uid in the buffer, starting from the end. */
114     for (i = start + num - 1; i >= start; i--) {
115         result = memcmp(uid, &buffer[i % size].uid, sizeof(*uid));
116         if (result == 0 && buffer[i % size].kind == kind)
117             return 1;
118         if (result > 0)
119             break;
120     }
121
122     /* We didn't find it; insert the uid into the buffer after i. */
123     i++;
124     for (j = start + num; j > i; j--)
125         buffer[j % size] = buffer[(j - 1) % size];
126     buffer[i % size].uid = *uid;
127     buffer[i % size].kind = kind;
128     buffer[i % size].t = now;
129     num++;
130
131     return 0;
132 }
133
134
135 /* Return 1 if there is a packet waiting, 0 otherwise */
136
137 int Z_PacketWaiting()
138 {
139     struct timeval tv;
140     fd_set read;
141
142     tv.tv_sec = tv.tv_usec = 0;
143     FD_ZERO(&read);
144     FD_SET(ZGetFD(), &read);
145     return (select(ZGetFD() + 1, &read, NULL, NULL, &tv));
146
147
148
149 /* Wait for a complete notice to become available */
150
151 Code_t Z_WaitForComplete()
152 {
153     Code_t retval;
154
155     if (__Q_CompleteLength)
156         return (Z_ReadEnqueue());
157
158     while (!__Q_CompleteLength)
159         if ((retval = Z_ReadWait()) != ZERR_NONE)
160             return (retval);
161
162     return (ZERR_NONE);
163 }
164
165
166 /* Read any available packets and enqueue them */
167
168 Code_t Z_ReadEnqueue()
169 {
170     Code_t retval;
171
172     if (ZGetFD() < 0)
173         return (ZERR_NOPORT);
174     
175     while (Z_PacketWaiting())
176         if ((retval = Z_ReadWait()) != ZERR_NONE)
177             return (retval);
178
179     return (ZERR_NONE);
180 }
181
182
183 /*
184  * Search the queue for a notice with the proper multiuid - remove any
185  * notices that haven't been touched in a while
186  */
187
188 struct _Z_InputQ *Z_SearchQueue(uid, kind)
189     ZUnique_Id_t *uid;
190     ZNotice_Kind_t kind;
191 {
192     register struct _Z_InputQ *qptr;
193     struct _Z_InputQ *next;
194     struct timeval tv;
195
196     (void) gettimeofday(&tv, (struct timezone *)0);
197
198     qptr = __Q_Head;
199
200     while (qptr) {
201         if (ZCompareUID(uid, &qptr->uid) && qptr->kind == kind)
202             return (qptr);
203         next = qptr->next;
204         if (qptr->timep && (qptr->timep+Z_NOTICETIMELIMIT < tv.tv_sec))
205             Z_RemQueue(qptr);
206         qptr = next;
207     }
208     return (NULL);
209 }
210
211 /*
212  * Now we delve into really convoluted queue handling and
213  * fragmentation reassembly algorithms and other stuff you probably
214  * don't want to look at...
215  *
216  * This routine does NOT guarantee a complete packet will be ready when it
217  * returns.
218  */
219
220 Code_t Z_ReadWait()
221 {
222     register struct _Z_InputQ *qptr;
223     ZNotice_t notice;
224     ZPacket_t packet;
225     struct sockaddr_in olddest, from;
226     int from_len, packet_len, zvlen, part, partof;
227     char *slash;
228     Code_t retval;
229     fd_set fds;
230     struct timeval tv;
231
232     if (ZGetFD() < 0)
233         return (ZERR_NOPORT);
234         
235     FD_ZERO(&fds);
236     FD_SET(ZGetFD(), &fds);
237     tv.tv_sec = 60;
238     tv.tv_usec = 0;
239
240     if (select(ZGetFD() + 1, &fds, NULL, NULL, &tv) < 0)
241       return (errno);
242     if (!FD_ISSET(ZGetFD(), &fds))
243       return ETIMEDOUT;
244
245     from_len = sizeof(struct sockaddr_in);
246
247     packet_len = recvfrom(ZGetFD(), packet, sizeof(packet), 0, 
248                           (struct sockaddr *)&from, &from_len);
249
250     if (packet_len < 0)
251         return (errno);
252
253     if (!packet_len)
254         return (ZERR_EOF);
255
256     /* Ignore obviously non-Zephyr packets. */
257     zvlen = sizeof(ZVERSIONHDR) - 1;
258     if (packet_len < zvlen || memcmp(packet, ZVERSIONHDR, zvlen) != 0) {
259         Z_discarded_packets++;
260         return (ZERR_NONE);
261     }   
262
263     /* Parse the notice */
264     if ((retval = ZParseNotice(packet, packet_len, &notice)) != ZERR_NONE)
265         return (retval);
266
267     /*
268      * If we're not a server and the notice is of an appropriate kind,
269      * send back a CLIENTACK to whoever sent it to say we got it.
270      */
271     if (!__Zephyr_server) {
272         if (notice.z_kind != HMACK && notice.z_kind != SERVACK &&
273             notice.z_kind != SERVNAK && notice.z_kind != CLIENTACK) {
274             ZNotice_t tmpnotice;
275             ZPacket_t pkt;
276             int len;
277
278             tmpnotice = notice;
279             tmpnotice.z_kind = CLIENTACK;
280             tmpnotice.z_message_len = 0;
281             olddest = __HM_addr;
282             __HM_addr = from;
283             if ((retval = ZFormatSmallRawNotice(&tmpnotice, pkt, &len))
284                 != ZERR_NONE)
285                 return(retval);
286             if ((retval = ZSendPacket(pkt, len, 0)) != ZERR_NONE)
287                 return (retval);
288             __HM_addr = olddest;
289         }
290         if (find_or_insert_uid(&notice.z_uid, notice.z_kind))
291             return(ZERR_NONE);
292
293         /* Check authentication on the notice. */
294         notice.z_checked_auth = ZCheckAuthentication(&notice, &from);
295     }
296
297
298     /*
299      * Parse apart the z_multinotice field - if the field is blank for
300      * some reason, assume this packet stands by itself.
301      */
302     slash = strchr(notice.z_multinotice, '/');
303     if (slash) {
304         part = atoi(notice.z_multinotice);
305         partof = atoi(slash+1);
306         if (part > partof || partof == 0) {
307             part = 0;
308             partof = notice.z_message_len;
309         }
310     }
311     else {
312         part = 0;
313         partof = notice.z_message_len;
314     }
315
316     /* Too big a packet...just ignore it! */
317     if (partof > Z_MAXNOTICESIZE)
318         return (ZERR_NONE);
319
320     /*
321      * If we aren't a server and we can find a notice in the queue
322      * with the same multiuid field, insert the current fragment as
323      * appropriate.
324      */
325     switch (notice.z_kind) {
326     case SERVACK:
327     case SERVNAK:
328         /* The SERVACK and SERVNAK replies shouldn't be reassembled
329            (they have no parts).  Instead, we should hold on to the reply
330            ONLY if it's the first part of a fragmented message, i.e.
331            multi_uid == uid.  This allows programs to wait for the uid
332            of the first packet, and get a response when that notice
333            arrives.  Acknowledgements of the other fragments are discarded
334            (XXX we assume here that they all carry the same information
335            regarding failure/success)
336          */
337         if (!__Zephyr_server &&
338             !ZCompareUID(&notice.z_multiuid, &notice.z_uid))
339             /* they're not the same... throw away this packet. */
340             return(ZERR_NONE);
341         /* fall thru & process it */
342     default:
343         /* for HMACK types, we assume no packet loss (local loopback
344            connections).  The other types can be fragmented and MUST
345            run through this code. */
346         if (!__Zephyr_server && (qptr = Z_SearchQueue(&notice.z_multiuid,
347                                                       notice.z_kind))) {
348             /*
349              * If this is the first fragment, and we haven't already
350              * gotten a first fragment, grab the header from it.
351              */
352             if (part == 0 && !qptr->header) {
353                 qptr->header_len = packet_len-notice.z_message_len;
354                 qptr->header = (char *) malloc((unsigned) qptr->header_len);
355                 if (!qptr->header)
356                     return (ENOMEM);
357                 (void) memcpy(qptr->header, packet, qptr->header_len);
358             }
359             return (Z_AddNoticeToEntry(qptr, &notice, part));
360         }
361     }
362
363     /*
364      * We'll have to create a new entry...make sure the queue isn't
365      * going to get too big.
366      */
367     if (__Q_Size+(__Zephyr_server ? notice.z_message_len : partof) > Z_MAXQUEUESIZE)
368         return (ZERR_NONE);
369
370     /*
371      * This is a notice we haven't heard of, so create a new queue
372      * entry for it and zero it out.
373      */
374     qptr = (struct _Z_InputQ *)malloc(sizeof(struct _Z_InputQ));
375     if (!qptr)
376         return (ENOMEM);
377     (void) memset((char *)qptr, 0, sizeof(struct _Z_InputQ));
378
379     /* Insert the entry at the end of the queue */
380     qptr->next = NULL;
381     qptr->prev = __Q_Tail;
382     if (__Q_Tail)
383         __Q_Tail->next = qptr;
384     __Q_Tail = qptr;
385
386     if (!__Q_Head)
387         __Q_Head = qptr;
388
389     
390     /* Copy the from field, multiuid, kind, and checked authentication. */
391     qptr->from = from;
392     qptr->uid = notice.z_multiuid;
393     qptr->kind = notice.z_kind;
394     qptr->auth = notice.z_checked_auth;
395     
396     /*
397      * If this is the first part of the notice, we take the header
398      * from it.  We only take it if this is the first fragment so that
399      * the Unique ID's will be predictable.
400      *
401      * If a Zephyr Server, we always take the header.
402      */
403     if (__Zephyr_server || part == 0) {
404         qptr->header_len = packet_len-notice.z_message_len;
405         qptr->header = (char *) malloc((unsigned) qptr->header_len);
406         if (!qptr->header)
407             return ENOMEM;
408         (void) memcpy(qptr->header, packet, qptr->header_len);
409     }
410
411     /*
412      * If this is not a fragmented notice, then don't bother with a
413      * hole list.
414      * If we are a Zephyr server, all notices are treated as complete.
415      */
416     if (__Zephyr_server || (part == 0 && notice.z_message_len == partof)) {
417         __Q_CompleteLength++;
418         qptr->holelist = (struct _Z_Hole *) 0;
419         qptr->complete = 1;
420         /* allocate a msg buf for this piece */
421         if (notice.z_message_len == 0)
422             qptr->msg = 0;
423         else if (!(qptr->msg = (char *) malloc((unsigned) notice.z_message_len)))
424             return(ENOMEM);
425         else
426             (void) memcpy(qptr->msg, notice.z_message, notice.z_message_len);
427         qptr->msg_len = notice.z_message_len;
428         __Q_Size += notice.z_message_len;
429         qptr->packet_len = qptr->header_len+qptr->msg_len;
430         if (!(qptr->packet = (char *) malloc((unsigned) qptr->packet_len)))
431             return (ENOMEM);
432         (void) memcpy(qptr->packet, qptr->header, qptr->header_len);
433         if(qptr->msg)
434             (void) memcpy(qptr->packet+qptr->header_len, qptr->msg,
435                            qptr->msg_len);
436         return (ZERR_NONE);
437     }
438
439     /*
440      * We know how long the message is going to be (this is better
441      * than IP fragmentation...), so go ahead and allocate it all.
442      */
443     if (!(qptr->msg = (char *) malloc((unsigned) partof)) && partof)
444         return (ENOMEM);
445     qptr->msg_len = partof;
446     __Q_Size += partof;
447
448     /*
449      * Well, it's a fragmented notice...allocate a hole list and
450      * initialize it to the full packet size.  Then insert the
451      * current fragment.
452      */
453     if (!(qptr->holelist = (struct _Z_Hole *)
454           malloc(sizeof(struct _Z_Hole))))
455         return (ENOMEM);
456     qptr->holelist->next = (struct _Z_Hole *) 0;
457     qptr->holelist->first = 0;
458     qptr->holelist->last = partof-1;
459     return (Z_AddNoticeToEntry(qptr, &notice, part));
460 }
461
462
463 /* Fragment management routines - compliments, more or less, of RFC815 */
464
465 Code_t Z_AddNoticeToEntry(qptr, notice, part)
466     struct _Z_InputQ *qptr;
467     ZNotice_t *notice;
468     int part;
469 {
470     int last, oldfirst, oldlast;
471     struct _Z_Hole *hole, *lasthole;
472     struct timeval tv;
473
474     /* Incorporate this notice's checked authentication. */
475     if (notice->z_checked_auth == ZAUTH_FAILED)
476         qptr->auth = ZAUTH_FAILED;
477     else if (notice->z_checked_auth == ZAUTH_NO && qptr->auth != ZAUTH_FAILED)
478         qptr->auth = ZAUTH_NO;
479
480     (void) gettimeofday(&tv, (struct timezone *)0);
481     qptr->timep = tv.tv_sec;
482     
483     last = part+notice->z_message_len-1;
484
485     hole = qptr->holelist;
486     lasthole = (struct _Z_Hole *) 0;
487
488     /* copy in the message body */
489     (void) memcpy(qptr->msg+part, notice->z_message, notice->z_message_len);
490
491     /* Search for a hole that overlaps with the current fragment */
492     while (hole) {
493         if (part <= hole->last && last >= hole->first)
494             break;
495         lasthole = hole;
496         hole = hole->next;
497     }
498
499     /* If we found one, delete it and reconstruct a new hole */
500     if (hole) {
501         oldfirst = hole->first;
502         oldlast = hole->last;
503         if (lasthole)
504             lasthole->next = hole->next;
505         else
506             qptr->holelist = hole->next;
507         free((char *)hole);
508         /*
509          * Now create a new hole that is the original hole without the
510          * current fragment.
511          */
512         if (part > oldfirst) {
513             /* Search for the end of the hole list */
514             hole = qptr->holelist;
515             lasthole = (struct _Z_Hole *) 0;
516             while (hole) {
517                 lasthole = hole;
518                 hole = hole->next;
519             }
520             if (lasthole) {
521                 if (!(lasthole->next = (struct _Z_Hole *)
522                       malloc(sizeof(struct _Z_InputQ))))
523                     return (ENOMEM);
524                 hole = lasthole->next;
525             }
526             else {
527                 if (!(qptr->holelist = (struct _Z_Hole *)
528                       malloc(sizeof(struct _Z_InputQ))))
529                     return (ENOMEM);
530                 hole = qptr->holelist;
531             }
532             hole->next = NULL;
533             hole->first = oldfirst;
534             hole->last = part-1;
535         }
536         if (last < oldlast) {
537             /* Search for the end of the hole list */
538             hole = qptr->holelist;
539             lasthole = (struct _Z_Hole *) 0;
540             while (hole) {
541                 lasthole = hole;
542                 hole = hole->next;
543             }
544             if (lasthole) {
545                 if (!(lasthole->next = (struct _Z_Hole *)
546                       malloc(sizeof(struct _Z_InputQ))))
547                     return (ENOMEM);
548                 hole = lasthole->next;
549             }
550             else {
551                 if (!(qptr->holelist = (struct _Z_Hole *)
552                       malloc(sizeof(struct _Z_InputQ))))
553                     return (ENOMEM);
554                 hole = qptr->holelist;
555             }
556             hole->next = (struct _Z_Hole *) 0;
557             hole->first = last+1;
558             hole->last = oldlast;
559         }
560     }
561
562     if (!qptr->holelist) {
563         if (!qptr->complete)
564             __Q_CompleteLength++;
565         qptr->complete = 1;
566         qptr->timep = 0;                /* don't time out anymore */
567         qptr->packet_len = qptr->header_len+qptr->msg_len;
568         if (!(qptr->packet = (char *) malloc((unsigned) qptr->packet_len)))
569             return (ENOMEM);
570         (void) memcpy(qptr->packet, qptr->header, qptr->header_len);
571         (void) memcpy(qptr->packet+qptr->header_len, qptr->msg,
572                        qptr->msg_len);
573     }
574     
575     return (ZERR_NONE);
576 }
577
578 void Z_gettimeofday(struct _ZTimeval *ztv, struct timezone *tz)
579 {
580         struct timeval tv;
581         (void) gettimeofday(&tv, tz); /* yeah, yeah, I know */
582         ztv->tv_sec=tv.tv_sec;
583         ztv->tv_usec=tv.tv_usec;
584 }
585
586 Code_t Z_FormatHeader(notice, buffer, buffer_len, len, cert_routine)
587     ZNotice_t *notice;
588     char *buffer;
589     int buffer_len;
590     int *len;
591     Z_AuthProc cert_routine;
592 {
593     Code_t retval;
594     static char version[BUFSIZ]; /* default init should be all \0 */
595     struct sockaddr_in name;
596     int namelen = sizeof(name);
597
598     if (!notice->z_sender)
599         notice->z_sender = ZGetSender();
600
601     if (notice->z_port == 0) {
602         if (ZGetFD() < 0) {
603             retval = ZOpenPort((u_short *)0);
604             if (retval != ZERR_NONE)
605                 return (retval);
606         }
607         retval = getsockname(ZGetFD(), (struct sockaddr *) &name, &namelen);
608         if (retval != 0)
609             return (retval);
610         notice->z_port = name.sin_port;
611     }
612
613     notice->z_multinotice = "";
614     
615     (void) Z_gettimeofday(&notice->z_uid.tv, (struct timezone *)0);
616     notice->z_uid.tv.tv_sec = htonl((u_long) notice->z_uid.tv.tv_sec);
617     notice->z_uid.tv.tv_usec = htonl((u_long) notice->z_uid.tv.tv_usec);
618     
619     (void) memcpy(&notice->z_uid.zuid_addr, &__My_addr, sizeof(__My_addr));
620
621     notice->z_multiuid = notice->z_uid;
622
623     if (!version[0])
624             (void) sprintf(version, "%s%d.%d", ZVERSIONHDR, ZVERSIONMAJOR,
625                            ZVERSIONMINOR);
626     notice->z_version = version;
627
628     return Z_FormatAuthHeader(notice, buffer, buffer_len, len, cert_routine);
629 }
630
631 Code_t Z_FormatAuthHeader(notice, buffer, buffer_len, len, cert_routine)
632     ZNotice_t *notice;
633     char *buffer;
634     int buffer_len;
635     int *len;
636     Z_AuthProc cert_routine;
637 {
638     if (!cert_routine) {
639         notice->z_auth = 0;
640         notice->z_authent_len = 0;
641         notice->z_ascii_authent = "";
642         notice->z_checksum = 0;
643         return (Z_FormatRawHeader(notice, buffer, buffer_len,
644                                   len, NULL, NULL));
645     }
646     
647     return ((*cert_routine)(notice, buffer, buffer_len, len));
648
649         
650 Code_t Z_FormatRawHeader(notice, buffer, buffer_len, len, cstart, cend)
651     ZNotice_t *notice;
652     char *buffer;
653     int buffer_len;
654     int *len;
655     char **cstart, **cend;
656 {
657     char newrecip[BUFSIZ];
658     char *ptr, *end;
659     int i;
660
661     if (!notice->z_class)
662             notice->z_class = "";
663
664     if (!notice->z_class_inst)
665             notice->z_class_inst = "";
666
667     if (!notice->z_opcode)
668             notice->z_opcode = "";
669
670     if (!notice->z_recipient)
671             notice->z_recipient = "";
672
673     if (!notice->z_default_format)
674             notice->z_default_format = "";
675
676     ptr = buffer;
677     end = buffer+buffer_len;
678
679     if (buffer_len < strlen(notice->z_version)+1)
680         return (ZERR_HEADERLEN);
681
682     (void) strcpy(ptr, notice->z_version);
683     ptr += strlen(ptr)+1;
684
685     if (ZMakeAscii32(ptr, end-ptr, Z_NUMFIELDS + notice->z_num_other_fields)
686         == ZERR_FIELDLEN)
687         return (ZERR_HEADERLEN);
688     ptr += strlen(ptr)+1;
689
690     if (ZMakeAscii32(ptr, end-ptr, notice->z_kind) == ZERR_FIELDLEN)
691         return (ZERR_HEADERLEN);
692     ptr += strlen(ptr)+1;
693
694     if (ZMakeAscii(ptr, end-ptr, (unsigned char *)&notice->z_uid, 
695                    sizeof(ZUnique_Id_t)) == ZERR_FIELDLEN)
696         return (ZERR_HEADERLEN);
697     ptr += strlen(ptr)+1;
698
699     if (ZMakeAscii16(ptr, end-ptr, ntohs(notice->z_port)) == ZERR_FIELDLEN)
700         return (ZERR_HEADERLEN);
701     ptr += strlen(ptr)+1;
702
703     if (ZMakeAscii32(ptr, end-ptr, notice->z_auth) == ZERR_FIELDLEN)
704         return (ZERR_HEADERLEN);
705     ptr += strlen(ptr)+1;
706
707     if (ZMakeAscii32(ptr, end-ptr, notice->z_authent_len) == ZERR_FIELDLEN)
708         return (ZERR_HEADERLEN);
709     ptr += strlen(ptr)+1;
710
711     if (Z_AddField(&ptr, notice->z_ascii_authent, end))
712         return (ZERR_HEADERLEN);
713     if (Z_AddField(&ptr, notice->z_class, end))
714         return (ZERR_HEADERLEN);
715     if (Z_AddField(&ptr, notice->z_class_inst, end))
716         return (ZERR_HEADERLEN);
717     if (Z_AddField(&ptr, notice->z_opcode, end))
718         return (ZERR_HEADERLEN);
719     if (Z_AddField(&ptr, notice->z_sender, end))
720         return (ZERR_HEADERLEN);
721     if (strchr(notice->z_recipient, '@') || !*notice->z_recipient) {
722         if (Z_AddField(&ptr, notice->z_recipient, end))
723             return (ZERR_HEADERLEN);
724     }
725     else {
726         if (strlen(notice->z_recipient) + strlen(__Zephyr_realm) + 2 >
727             sizeof(newrecip))
728             return (ZERR_HEADERLEN);
729         (void) sprintf(newrecip, "%s@%s", notice->z_recipient, __Zephyr_realm);
730         if (Z_AddField(&ptr, newrecip, end))
731             return (ZERR_HEADERLEN);
732     }           
733     if (Z_AddField(&ptr, notice->z_default_format, end))
734         return (ZERR_HEADERLEN);
735
736     /* copy back the end pointer location for crypto checksum */
737     if (cstart)
738         *cstart = ptr;
739     if (ZMakeAscii32(ptr, end-ptr, notice->z_checksum) == ZERR_FIELDLEN)
740         return (ZERR_HEADERLEN);
741     ptr += strlen(ptr)+1;
742     if (cend)
743         *cend = ptr;
744
745     if (Z_AddField(&ptr, notice->z_multinotice, end))
746         return (ZERR_HEADERLEN);
747
748     if (ZMakeAscii(ptr, end-ptr, (unsigned char *)&notice->z_multiuid, 
749                    sizeof(ZUnique_Id_t)) == ZERR_FIELDLEN)
750         return (ZERR_HEADERLEN);
751     ptr += strlen(ptr)+1;
752         
753     for (i=0;i<notice->z_num_other_fields;i++)
754         if (Z_AddField(&ptr, notice->z_other_fields[i], end))
755             return (ZERR_HEADERLEN);
756     
757     *len = ptr-buffer;
758         
759     return (ZERR_NONE);
760 }
761
762 static int
763 Z_AddField(ptr, field, end)
764     char **ptr, *field, *end;
765 {
766     register int len;
767
768     len = field ? strlen (field) + 1 : 1;
769
770     if (*ptr+len > end)
771         return 1;
772     if (field)
773         (void) strcpy(*ptr, field);
774     else
775         **ptr = '\0';
776     *ptr += len;
777
778     return 0;
779 }
780
781 struct _Z_InputQ *Z_GetFirstComplete()
782 {
783     struct _Z_InputQ *qptr;
784
785     qptr = __Q_Head;
786
787     while (qptr) {
788         if (qptr->complete)
789             return (qptr);
790         qptr = qptr->next;
791     }
792
793     return ((struct _Z_InputQ *)0);
794 }
795
796 struct _Z_InputQ *Z_GetNextComplete(qptr)
797     struct _Z_InputQ *qptr;
798 {
799     qptr = qptr->next;
800     while (qptr) {
801         if (qptr->complete)
802             return (qptr);
803         qptr = qptr->next;
804     }
805
806     return ((struct _Z_InputQ *)0);
807 }
808
809 void Z_RemQueue(qptr)
810     struct _Z_InputQ *qptr;
811 {
812     struct _Z_Hole *hole, *nexthole;
813     
814     if (qptr->complete)
815         __Q_CompleteLength--;
816
817     __Q_Size -= qptr->msg_len;
818     
819     if (qptr->header)
820         free(qptr->header);
821     if (qptr->msg)
822         free(qptr->msg);
823     if (qptr->packet)
824         free(qptr->packet);
825     
826     hole = qptr->holelist;
827     while (hole) {
828         nexthole = hole->next;
829         free((char *)hole);
830         hole = nexthole;
831     }
832     
833     if (qptr == __Q_Head && __Q_Head == __Q_Tail) {
834         free ((char *)qptr);
835         __Q_Head = (struct _Z_InputQ *)0;
836         __Q_Tail = (struct _Z_InputQ *)0;
837         return;
838     }
839     
840     if (qptr == __Q_Head) {
841         __Q_Head = qptr->next;
842         __Q_Head->prev = (struct _Z_InputQ *)0;
843         free ((char *)qptr);
844         return;
845     } 
846     if (qptr == __Q_Tail) {
847         __Q_Tail = qptr->prev;
848         __Q_Tail->next = (struct _Z_InputQ *)0;
849         free ((char *)qptr);
850         return;
851     }
852     qptr->prev->next = qptr->next;
853     qptr->next->prev = qptr->prev;
854     free ((char *)qptr);
855     return;
856 }
857
858 Code_t Z_SendFragmentedNotice(notice, len, cert_func, send_func)
859     ZNotice_t *notice;
860     int len;
861     Z_AuthProc cert_func;
862     Z_SendProc send_func;
863 {
864     ZNotice_t partnotice;
865     ZPacket_t buffer;
866     char multi[64];
867     int offset, hdrsize, fragsize, ret_len, message_len, waitforack;
868     Code_t retval;
869     
870     hdrsize = len-notice->z_message_len;
871     fragsize = Z_MAXPKTLEN-hdrsize-Z_FRAGFUDGE;
872     
873     offset = 0;
874
875     waitforack = ((notice->z_kind == UNACKED || notice->z_kind == ACKED)
876                   && !__Zephyr_server);
877     
878     partnotice = *notice;
879
880     while (offset < notice->z_message_len || !notice->z_message_len) {
881         (void) sprintf(multi, "%d/%d", offset, notice->z_message_len);
882         partnotice.z_multinotice = multi;
883         if (offset > 0) {
884             (void) Z_gettimeofday(&partnotice.z_uid.tv,
885                                   (struct timezone *)0);
886             partnotice.z_uid.tv.tv_sec =
887                 htonl((u_long) partnotice.z_uid.tv.tv_sec);
888             partnotice.z_uid.tv.tv_usec =
889                 htonl((u_long) partnotice.z_uid.tv.tv_usec);
890             (void) memcpy((char *)&partnotice.z_uid.zuid_addr, &__My_addr, 
891                           sizeof(__My_addr));
892         }
893         message_len = min(notice->z_message_len-offset, fragsize);
894         partnotice.z_message = notice->z_message+offset;
895         partnotice.z_message_len = message_len;
896         if ((retval = Z_FormatAuthHeader(&partnotice, buffer, Z_MAXHEADERLEN,
897                                          &ret_len, cert_func)) != ZERR_NONE) {
898             return (retval);
899         }
900         memcpy(buffer + ret_len, partnotice.z_message, message_len);
901         if ((retval = (*send_func)(&partnotice, buffer, ret_len+message_len,
902                                    waitforack)) != ZERR_NONE) {
903             return (retval);
904         }
905         offset += fragsize;
906         if (!notice->z_message_len)
907             break;
908     }
909
910     return (ZERR_NONE);
911 }
912
913 /*ARGSUSED*/
914 Code_t Z_XmitFragment(notice, buf, len, wait)
915 ZNotice_t *notice;
916 char *buf;
917 int len;
918 int wait;
919 {
920         return(ZSendPacket(buf, len, wait));
921 }
922
923 #ifdef Z_DEBUG
924 /* For debugging printing */
925 const char *const ZNoticeKinds[] = {
926     "UNSAFE", "UNACKED", "ACKED", "HMACK", "HMCTL", "SERVACK", "SERVNAK",
927     "CLIENTACK", "STAT"
928 };
929 #endif
930
931 #ifdef Z_DEBUG
932
933 #undef Z_debug
934 #ifdef HAVE_STDARG_H
935 void Z_debug (const char *format, ...)
936 {
937     va_list pvar;
938     if (!__Z_debug_print)
939       return;
940     va_start (pvar, format);
941     (*__Z_debug_print) (format, pvar, __Z_debug_print_closure);
942     va_end (pvar);
943 }
944 #else /* stdarg */
945 void Z_debug (va_alist) va_dcl
946 {
947     va_list pvar;
948     char *format;
949     if (!__Z_debug_print)
950       return;
951     va_start (pvar);
952     format = va_arg (pvar, char *);
953     (*__Z_debug_print) (format, pvar, __Z_debug_print_closure);
954     va_end (pvar);
955 }
956 #endif
957
958 void Z_debug_stderr (format, args, closure)
959      const char *format;
960      va_list args;
961      void *closure;
962 {
963 #ifdef HAVE_VPRINTF
964     vfprintf (stderr, format, args);
965 #else
966     _doprnt (format, args, stderr);
967 #endif
968     putc ('\n', stderr);
969 }
970
971 #undef ZGetFD
972 int ZGetFD () { return __Zephyr_fd; }
973
974 #undef ZQLength
975 int ZQLength () { return __Q_CompleteLength; }
976
977 #undef ZGetDestAddr
978 struct sockaddr_in ZGetDestAddr () { return __HM_addr; }
979
980 #undef ZGetRealm
981 Zconst char * ZGetRealm () { return __Zephyr_realm; }
982
983 #undef ZSetDebug
984 void ZSetDebug(proc, arg)
985     void (*proc) __P((const char *, va_list, void *));
986     char *arg;
987 {
988     __Z_debug_print = proc;
989     __Z_debug_print_closure = arg;
990 }
991 #endif /* Z_DEBUG */
992