]> asedeno.scripts.mit.edu Git - 1ts-debian.git/blob - zephyr/lib/Zinternal.c
finalize -3
[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$
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$";
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     /* Bounds check. */
475     if (part < 0 || notice->z_message_len < 0 || part > qptr->msg_len
476         || notice->z_message_len > qptr->msg_len - part)
477       return (ZERR_NONE);
478
479     /* Incorporate this notice's checked authentication. */
480     if (notice->z_checked_auth == ZAUTH_FAILED)
481         qptr->auth = ZAUTH_FAILED;
482     else if (notice->z_checked_auth == ZAUTH_NO && qptr->auth != ZAUTH_FAILED)
483         qptr->auth = ZAUTH_NO;
484
485     (void) gettimeofday(&tv, (struct timezone *)0);
486     qptr->timep = tv.tv_sec;
487     
488     last = part+notice->z_message_len-1;
489
490     hole = qptr->holelist;
491     lasthole = (struct _Z_Hole *) 0;
492
493     /* copy in the message body */
494     (void) memcpy(qptr->msg+part, notice->z_message, notice->z_message_len);
495
496     /* Search for a hole that overlaps with the current fragment */
497     while (hole) {
498         if (part <= hole->last && last >= hole->first)
499             break;
500         lasthole = hole;
501         hole = hole->next;
502     }
503
504     /* If we found one, delete it and reconstruct a new hole */
505     if (hole) {
506         oldfirst = hole->first;
507         oldlast = hole->last;
508         if (lasthole)
509             lasthole->next = hole->next;
510         else
511             qptr->holelist = hole->next;
512         free((char *)hole);
513         /*
514          * Now create a new hole that is the original hole without the
515          * current fragment.
516          */
517         if (part > oldfirst) {
518             /* Search for the end of the hole list */
519             hole = qptr->holelist;
520             lasthole = (struct _Z_Hole *) 0;
521             while (hole) {
522                 lasthole = hole;
523                 hole = hole->next;
524             }
525             if (lasthole) {
526                 if (!(lasthole->next = (struct _Z_Hole *)
527                       malloc(sizeof(struct _Z_InputQ))))
528                     return (ENOMEM);
529                 hole = lasthole->next;
530             }
531             else {
532                 if (!(qptr->holelist = (struct _Z_Hole *)
533                       malloc(sizeof(struct _Z_InputQ))))
534                     return (ENOMEM);
535                 hole = qptr->holelist;
536             }
537             hole->next = NULL;
538             hole->first = oldfirst;
539             hole->last = part-1;
540         }
541         if (last < oldlast) {
542             /* Search for the end of the hole list */
543             hole = qptr->holelist;
544             lasthole = (struct _Z_Hole *) 0;
545             while (hole) {
546                 lasthole = hole;
547                 hole = hole->next;
548             }
549             if (lasthole) {
550                 if (!(lasthole->next = (struct _Z_Hole *)
551                       malloc(sizeof(struct _Z_InputQ))))
552                     return (ENOMEM);
553                 hole = lasthole->next;
554             }
555             else {
556                 if (!(qptr->holelist = (struct _Z_Hole *)
557                       malloc(sizeof(struct _Z_InputQ))))
558                     return (ENOMEM);
559                 hole = qptr->holelist;
560             }
561             hole->next = (struct _Z_Hole *) 0;
562             hole->first = last+1;
563             hole->last = oldlast;
564         }
565     }
566
567     if (!qptr->holelist) {
568         if (!qptr->complete)
569             __Q_CompleteLength++;
570         qptr->complete = 1;
571         qptr->timep = 0;                /* don't time out anymore */
572         qptr->packet_len = qptr->header_len+qptr->msg_len;
573         if (!(qptr->packet = (char *) malloc((unsigned) qptr->packet_len)))
574             return (ENOMEM);
575         (void) memcpy(qptr->packet, qptr->header, qptr->header_len);
576         (void) memcpy(qptr->packet+qptr->header_len, qptr->msg,
577                        qptr->msg_len);
578     }
579     
580     return (ZERR_NONE);
581 }
582
583 void Z_gettimeofday(struct _ZTimeval *ztv, struct timezone *tz)
584 {
585         struct timeval tv;
586         (void) gettimeofday(&tv, tz); /* yeah, yeah, I know */
587         ztv->tv_sec=tv.tv_sec;
588         ztv->tv_usec=tv.tv_usec;
589 }
590
591 Code_t Z_FormatHeader(notice, buffer, buffer_len, len, cert_routine)
592     ZNotice_t *notice;
593     char *buffer;
594     int buffer_len;
595     int *len;
596     Z_AuthProc cert_routine;
597 {
598     Code_t retval;
599     static char version[BUFSIZ]; /* default init should be all \0 */
600     struct sockaddr_in name;
601     int namelen = sizeof(name);
602
603     if (!notice->z_sender)
604         notice->z_sender = ZGetSender();
605
606     if (notice->z_port == 0) {
607         if (ZGetFD() < 0) {
608             retval = ZOpenPort((u_short *)0);
609             if (retval != ZERR_NONE)
610                 return (retval);
611         }
612         retval = getsockname(ZGetFD(), (struct sockaddr *) &name, &namelen);
613         if (retval != 0)
614             return (retval);
615         notice->z_port = name.sin_port;
616     }
617
618     notice->z_multinotice = "";
619     
620     (void) Z_gettimeofday(&notice->z_uid.tv, (struct timezone *)0);
621     notice->z_uid.tv.tv_sec = htonl((u_long) notice->z_uid.tv.tv_sec);
622     notice->z_uid.tv.tv_usec = htonl((u_long) notice->z_uid.tv.tv_usec);
623     
624     (void) memcpy(&notice->z_uid.zuid_addr, &__My_addr, sizeof(__My_addr));
625
626     notice->z_multiuid = notice->z_uid;
627
628     if (!version[0])
629             (void) sprintf(version, "%s%d.%d", ZVERSIONHDR, ZVERSIONMAJOR,
630                            ZVERSIONMINOR);
631     notice->z_version = version;
632
633     return Z_FormatAuthHeader(notice, buffer, buffer_len, len, cert_routine);
634 }
635
636 Code_t Z_FormatAuthHeader(notice, buffer, buffer_len, len, cert_routine)
637     ZNotice_t *notice;
638     char *buffer;
639     int buffer_len;
640     int *len;
641     Z_AuthProc cert_routine;
642 {
643     if (!cert_routine) {
644         notice->z_auth = 0;
645         notice->z_authent_len = 0;
646         notice->z_ascii_authent = "";
647         notice->z_checksum = 0;
648         return (Z_FormatRawHeader(notice, buffer, buffer_len,
649                                   len, NULL, NULL));
650     }
651     
652     return ((*cert_routine)(notice, buffer, buffer_len, len));
653
654         
655 Code_t Z_FormatRawHeader(notice, buffer, buffer_len, len, cstart, cend)
656     ZNotice_t *notice;
657     char *buffer;
658     int buffer_len;
659     int *len;
660     char **cstart, **cend;
661 {
662     char newrecip[BUFSIZ];
663     char *ptr, *end;
664     int i;
665
666     if (!notice->z_class)
667             notice->z_class = "";
668
669     if (!notice->z_class_inst)
670             notice->z_class_inst = "";
671
672     if (!notice->z_opcode)
673             notice->z_opcode = "";
674
675     if (!notice->z_recipient)
676             notice->z_recipient = "";
677
678     if (!notice->z_default_format)
679             notice->z_default_format = "";
680
681     ptr = buffer;
682     end = buffer+buffer_len;
683
684     if (buffer_len < strlen(notice->z_version)+1)
685         return (ZERR_HEADERLEN);
686
687     (void) strcpy(ptr, notice->z_version);
688     ptr += strlen(ptr)+1;
689
690     if (ZMakeAscii32(ptr, end-ptr, Z_NUMFIELDS + notice->z_num_other_fields)
691         == ZERR_FIELDLEN)
692         return (ZERR_HEADERLEN);
693     ptr += strlen(ptr)+1;
694
695     if (ZMakeAscii32(ptr, end-ptr, notice->z_kind) == ZERR_FIELDLEN)
696         return (ZERR_HEADERLEN);
697     ptr += strlen(ptr)+1;
698
699     if (ZMakeAscii(ptr, end-ptr, (unsigned char *)&notice->z_uid, 
700                    sizeof(ZUnique_Id_t)) == ZERR_FIELDLEN)
701         return (ZERR_HEADERLEN);
702     ptr += strlen(ptr)+1;
703
704     if (ZMakeAscii16(ptr, end-ptr, ntohs(notice->z_port)) == ZERR_FIELDLEN)
705         return (ZERR_HEADERLEN);
706     ptr += strlen(ptr)+1;
707
708     if (ZMakeAscii32(ptr, end-ptr, notice->z_auth) == ZERR_FIELDLEN)
709         return (ZERR_HEADERLEN);
710     ptr += strlen(ptr)+1;
711
712     if (ZMakeAscii32(ptr, end-ptr, notice->z_authent_len) == ZERR_FIELDLEN)
713         return (ZERR_HEADERLEN);
714     ptr += strlen(ptr)+1;
715
716     if (Z_AddField(&ptr, notice->z_ascii_authent, end))
717         return (ZERR_HEADERLEN);
718     if (Z_AddField(&ptr, notice->z_class, end))
719         return (ZERR_HEADERLEN);
720     if (Z_AddField(&ptr, notice->z_class_inst, end))
721         return (ZERR_HEADERLEN);
722     if (Z_AddField(&ptr, notice->z_opcode, end))
723         return (ZERR_HEADERLEN);
724     if (Z_AddField(&ptr, notice->z_sender, end))
725         return (ZERR_HEADERLEN);
726     if (strchr(notice->z_recipient, '@') || !*notice->z_recipient) {
727         if (Z_AddField(&ptr, notice->z_recipient, end))
728             return (ZERR_HEADERLEN);
729     }
730     else {
731         if (strlen(notice->z_recipient) + strlen(__Zephyr_realm) + 2 >
732             sizeof(newrecip))
733             return (ZERR_HEADERLEN);
734         (void) sprintf(newrecip, "%s@%s", notice->z_recipient, __Zephyr_realm);
735         if (Z_AddField(&ptr, newrecip, end))
736             return (ZERR_HEADERLEN);
737     }           
738     if (Z_AddField(&ptr, notice->z_default_format, end))
739         return (ZERR_HEADERLEN);
740
741     /* copy back the end pointer location for crypto checksum */
742     if (cstart)
743         *cstart = ptr;
744     if (ZMakeAscii32(ptr, end-ptr, notice->z_checksum) == ZERR_FIELDLEN)
745         return (ZERR_HEADERLEN);
746     ptr += strlen(ptr)+1;
747     if (cend)
748         *cend = ptr;
749
750     if (Z_AddField(&ptr, notice->z_multinotice, end))
751         return (ZERR_HEADERLEN);
752
753     if (ZMakeAscii(ptr, end-ptr, (unsigned char *)&notice->z_multiuid, 
754                    sizeof(ZUnique_Id_t)) == ZERR_FIELDLEN)
755         return (ZERR_HEADERLEN);
756     ptr += strlen(ptr)+1;
757         
758     for (i=0;i<notice->z_num_other_fields;i++)
759         if (Z_AddField(&ptr, notice->z_other_fields[i], end))
760             return (ZERR_HEADERLEN);
761     
762     *len = ptr-buffer;
763         
764     return (ZERR_NONE);
765 }
766
767 static int
768 Z_AddField(ptr, field, end)
769     char **ptr, *field, *end;
770 {
771     register int len;
772
773     len = field ? strlen (field) + 1 : 1;
774
775     if (*ptr+len > end)
776         return 1;
777     if (field)
778         (void) strcpy(*ptr, field);
779     else
780         **ptr = '\0';
781     *ptr += len;
782
783     return 0;
784 }
785
786 struct _Z_InputQ *Z_GetFirstComplete()
787 {
788     struct _Z_InputQ *qptr;
789
790     qptr = __Q_Head;
791
792     while (qptr) {
793         if (qptr->complete)
794             return (qptr);
795         qptr = qptr->next;
796     }
797
798     return ((struct _Z_InputQ *)0);
799 }
800
801 struct _Z_InputQ *Z_GetNextComplete(qptr)
802     struct _Z_InputQ *qptr;
803 {
804     qptr = qptr->next;
805     while (qptr) {
806         if (qptr->complete)
807             return (qptr);
808         qptr = qptr->next;
809     }
810
811     return ((struct _Z_InputQ *)0);
812 }
813
814 void Z_RemQueue(qptr)
815     struct _Z_InputQ *qptr;
816 {
817     struct _Z_Hole *hole, *nexthole;
818     
819     if (qptr->complete)
820         __Q_CompleteLength--;
821
822     __Q_Size -= qptr->msg_len;
823     
824     if (qptr->header)
825         free(qptr->header);
826     if (qptr->msg)
827         free(qptr->msg);
828     if (qptr->packet)
829         free(qptr->packet);
830     
831     hole = qptr->holelist;
832     while (hole) {
833         nexthole = hole->next;
834         free((char *)hole);
835         hole = nexthole;
836     }
837     
838     if (qptr == __Q_Head && __Q_Head == __Q_Tail) {
839         free ((char *)qptr);
840         __Q_Head = (struct _Z_InputQ *)0;
841         __Q_Tail = (struct _Z_InputQ *)0;
842         return;
843     }
844     
845     if (qptr == __Q_Head) {
846         __Q_Head = qptr->next;
847         __Q_Head->prev = (struct _Z_InputQ *)0;
848         free ((char *)qptr);
849         return;
850     } 
851     if (qptr == __Q_Tail) {
852         __Q_Tail = qptr->prev;
853         __Q_Tail->next = (struct _Z_InputQ *)0;
854         free ((char *)qptr);
855         return;
856     }
857     qptr->prev->next = qptr->next;
858     qptr->next->prev = qptr->prev;
859     free ((char *)qptr);
860     return;
861 }
862
863 Code_t Z_SendFragmentedNotice(notice, len, cert_func, send_func)
864     ZNotice_t *notice;
865     int len;
866     Z_AuthProc cert_func;
867     Z_SendProc send_func;
868 {
869     ZNotice_t partnotice;
870     ZPacket_t buffer;
871     char multi[64];
872     int offset, hdrsize, fragsize, ret_len, message_len, waitforack;
873     Code_t retval;
874     
875     hdrsize = len-notice->z_message_len;
876     fragsize = Z_MAXPKTLEN-hdrsize-Z_FRAGFUDGE;
877     
878     offset = 0;
879
880     waitforack = ((notice->z_kind == UNACKED || notice->z_kind == ACKED)
881                   && !__Zephyr_server);
882     
883     partnotice = *notice;
884
885     while (offset < notice->z_message_len || !notice->z_message_len) {
886         (void) sprintf(multi, "%d/%d", offset, notice->z_message_len);
887         partnotice.z_multinotice = multi;
888         if (offset > 0) {
889             (void) Z_gettimeofday(&partnotice.z_uid.tv,
890                                   (struct timezone *)0);
891             partnotice.z_uid.tv.tv_sec =
892                 htonl((u_long) partnotice.z_uid.tv.tv_sec);
893             partnotice.z_uid.tv.tv_usec =
894                 htonl((u_long) partnotice.z_uid.tv.tv_usec);
895             (void) memcpy((char *)&partnotice.z_uid.zuid_addr, &__My_addr, 
896                           sizeof(__My_addr));
897         }
898         message_len = min(notice->z_message_len-offset, fragsize);
899         partnotice.z_message = notice->z_message+offset;
900         partnotice.z_message_len = message_len;
901         if ((retval = Z_FormatAuthHeader(&partnotice, buffer, Z_MAXHEADERLEN,
902                                          &ret_len, cert_func)) != ZERR_NONE) {
903             return (retval);
904         }
905         memcpy(buffer + ret_len, partnotice.z_message, message_len);
906         if ((retval = (*send_func)(&partnotice, buffer, ret_len+message_len,
907                                    waitforack)) != ZERR_NONE) {
908             return (retval);
909         }
910         offset += fragsize;
911         if (!notice->z_message_len)
912             break;
913     }
914
915     return (ZERR_NONE);
916 }
917
918 /*ARGSUSED*/
919 Code_t Z_XmitFragment(notice, buf, len, wait)
920 ZNotice_t *notice;
921 char *buf;
922 int len;
923 int wait;
924 {
925         return(ZSendPacket(buf, len, wait));
926 }
927
928 #ifdef Z_DEBUG
929 /* For debugging printing */
930 const char *const ZNoticeKinds[] = {
931     "UNSAFE", "UNACKED", "ACKED", "HMACK", "HMCTL", "SERVACK", "SERVNAK",
932     "CLIENTACK", "STAT"
933 };
934 #endif
935
936 #ifdef Z_DEBUG
937
938 #undef Z_debug
939 #ifdef HAVE_STDARG_H
940 void Z_debug (const char *format, ...)
941 {
942     va_list pvar;
943     if (!__Z_debug_print)
944       return;
945     va_start (pvar, format);
946     (*__Z_debug_print) (format, pvar, __Z_debug_print_closure);
947     va_end (pvar);
948 }
949 #else /* stdarg */
950 void Z_debug (va_alist) va_dcl
951 {
952     va_list pvar;
953     char *format;
954     if (!__Z_debug_print)
955       return;
956     va_start (pvar);
957     format = va_arg (pvar, char *);
958     (*__Z_debug_print) (format, pvar, __Z_debug_print_closure);
959     va_end (pvar);
960 }
961 #endif
962
963 void Z_debug_stderr (format, args, closure)
964      const char *format;
965      va_list args;
966      void *closure;
967 {
968 #ifdef HAVE_VPRINTF
969     vfprintf (stderr, format, args);
970 #else
971     _doprnt (format, args, stderr);
972 #endif
973     putc ('\n', stderr);
974 }
975
976 #undef ZGetFD
977 int ZGetFD () { return __Zephyr_fd; }
978
979 #undef ZQLength
980 int ZQLength () { return __Q_CompleteLength; }
981
982 #undef ZGetDestAddr
983 struct sockaddr_in ZGetDestAddr () { return __HM_addr; }
984
985 #undef ZGetRealm
986 Zconst char * ZGetRealm () { return __Zephyr_realm; }
987
988 #undef ZSetDebug
989 void ZSetDebug(proc, arg)
990     void (*proc) __P((const char *, va_list, void *));
991     char *arg;
992 {
993     __Z_debug_print = proc;
994     __Z_debug_print_closure = arg;
995 }
996 #endif /* Z_DEBUG */
997