]> asedeno.scripts.mit.edu Git - 1ts-debian.git/blob - zephyr/lib/Zinternal.c
b3d89b7a49d6ad15b3a67074b09e7f4f7a6edc81
[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 Code_t Z_FormatHeader(notice, buffer, buffer_len, len, cert_routine)
579     ZNotice_t *notice;
580     char *buffer;
581     int buffer_len;
582     int *len;
583     Z_AuthProc cert_routine;
584 {
585     Code_t retval;
586     static char version[BUFSIZ]; /* default init should be all \0 */
587     struct sockaddr_in name;
588     int namelen = sizeof(name);
589
590     if (!notice->z_sender)
591         notice->z_sender = ZGetSender();
592
593     if (notice->z_port == 0) {
594         if (ZGetFD() < 0) {
595             retval = ZOpenPort((u_short *)0);
596             if (retval != ZERR_NONE)
597                 return (retval);
598         }
599         retval = getsockname(ZGetFD(), (struct sockaddr *) &name, &namelen);
600         if (retval != 0)
601             return (retval);
602         notice->z_port = name.sin_port;
603     }
604
605     notice->z_multinotice = "";
606     
607     (void) gettimeofday(&notice->z_uid.tv, (struct timezone *)0);
608     notice->z_uid.tv.tv_sec = htonl((u_long) notice->z_uid.tv.tv_sec);
609     notice->z_uid.tv.tv_usec = htonl((u_long) notice->z_uid.tv.tv_usec);
610     
611     (void) memcpy(&notice->z_uid.zuid_addr, &__My_addr, sizeof(__My_addr));
612
613     notice->z_multiuid = notice->z_uid;
614
615     if (!version[0])
616             (void) sprintf(version, "%s%d.%d", ZVERSIONHDR, ZVERSIONMAJOR,
617                            ZVERSIONMINOR);
618     notice->z_version = version;
619
620     return Z_FormatAuthHeader(notice, buffer, buffer_len, len, cert_routine);
621 }
622
623 Code_t Z_FormatAuthHeader(notice, buffer, buffer_len, len, cert_routine)
624     ZNotice_t *notice;
625     char *buffer;
626     int buffer_len;
627     int *len;
628     Z_AuthProc cert_routine;
629 {
630     if (!cert_routine) {
631         notice->z_auth = 0;
632         notice->z_authent_len = 0;
633         notice->z_ascii_authent = "";
634         notice->z_checksum = 0;
635         return (Z_FormatRawHeader(notice, buffer, buffer_len,
636                                   len, NULL, NULL));
637     }
638     
639     return ((*cert_routine)(notice, buffer, buffer_len, len));
640
641         
642 Code_t Z_FormatRawHeader(notice, buffer, buffer_len, len, cstart, cend)
643     ZNotice_t *notice;
644     char *buffer;
645     int buffer_len;
646     int *len;
647     char **cstart, **cend;
648 {
649     char newrecip[BUFSIZ];
650     char *ptr, *end;
651     int i;
652
653     if (!notice->z_class)
654             notice->z_class = "";
655
656     if (!notice->z_class_inst)
657             notice->z_class_inst = "";
658
659     if (!notice->z_opcode)
660             notice->z_opcode = "";
661
662     if (!notice->z_recipient)
663             notice->z_recipient = "";
664
665     if (!notice->z_default_format)
666             notice->z_default_format = "";
667
668     ptr = buffer;
669     end = buffer+buffer_len;
670
671     if (buffer_len < strlen(notice->z_version)+1)
672         return (ZERR_HEADERLEN);
673
674     (void) strcpy(ptr, notice->z_version);
675     ptr += strlen(ptr)+1;
676
677     if (ZMakeAscii32(ptr, end-ptr, Z_NUMFIELDS + notice->z_num_other_fields)
678         == ZERR_FIELDLEN)
679         return (ZERR_HEADERLEN);
680     ptr += strlen(ptr)+1;
681
682     if (ZMakeAscii32(ptr, end-ptr, notice->z_kind) == ZERR_FIELDLEN)
683         return (ZERR_HEADERLEN);
684     ptr += strlen(ptr)+1;
685
686     if (ZMakeAscii(ptr, end-ptr, (unsigned char *)&notice->z_uid, 
687                    sizeof(ZUnique_Id_t)) == ZERR_FIELDLEN)
688         return (ZERR_HEADERLEN);
689     ptr += strlen(ptr)+1;
690
691     if (ZMakeAscii16(ptr, end-ptr, ntohs(notice->z_port)) == ZERR_FIELDLEN)
692         return (ZERR_HEADERLEN);
693     ptr += strlen(ptr)+1;
694
695     if (ZMakeAscii32(ptr, end-ptr, notice->z_auth) == ZERR_FIELDLEN)
696         return (ZERR_HEADERLEN);
697     ptr += strlen(ptr)+1;
698
699     if (ZMakeAscii32(ptr, end-ptr, notice->z_authent_len) == ZERR_FIELDLEN)
700         return (ZERR_HEADERLEN);
701     ptr += strlen(ptr)+1;
702
703     if (Z_AddField(&ptr, notice->z_ascii_authent, end))
704         return (ZERR_HEADERLEN);
705     if (Z_AddField(&ptr, notice->z_class, end))
706         return (ZERR_HEADERLEN);
707     if (Z_AddField(&ptr, notice->z_class_inst, end))
708         return (ZERR_HEADERLEN);
709     if (Z_AddField(&ptr, notice->z_opcode, end))
710         return (ZERR_HEADERLEN);
711     if (Z_AddField(&ptr, notice->z_sender, end))
712         return (ZERR_HEADERLEN);
713     if (strchr(notice->z_recipient, '@') || !*notice->z_recipient) {
714         if (Z_AddField(&ptr, notice->z_recipient, end))
715             return (ZERR_HEADERLEN);
716     }
717     else {
718         if (strlen(notice->z_recipient) + strlen(__Zephyr_realm) + 2 >
719             sizeof(newrecip))
720             return (ZERR_HEADERLEN);
721         (void) sprintf(newrecip, "%s@%s", notice->z_recipient, __Zephyr_realm);
722         if (Z_AddField(&ptr, newrecip, end))
723             return (ZERR_HEADERLEN);
724     }           
725     if (Z_AddField(&ptr, notice->z_default_format, end))
726         return (ZERR_HEADERLEN);
727
728     /* copy back the end pointer location for crypto checksum */
729     if (cstart)
730         *cstart = ptr;
731     if (ZMakeAscii32(ptr, end-ptr, notice->z_checksum) == ZERR_FIELDLEN)
732         return (ZERR_HEADERLEN);
733     ptr += strlen(ptr)+1;
734     if (cend)
735         *cend = ptr;
736
737     if (Z_AddField(&ptr, notice->z_multinotice, end))
738         return (ZERR_HEADERLEN);
739
740     if (ZMakeAscii(ptr, end-ptr, (unsigned char *)&notice->z_multiuid, 
741                    sizeof(ZUnique_Id_t)) == ZERR_FIELDLEN)
742         return (ZERR_HEADERLEN);
743     ptr += strlen(ptr)+1;
744         
745     for (i=0;i<notice->z_num_other_fields;i++)
746         if (Z_AddField(&ptr, notice->z_other_fields[i], end))
747             return (ZERR_HEADERLEN);
748     
749     *len = ptr-buffer;
750         
751     return (ZERR_NONE);
752 }
753
754 static int
755 Z_AddField(ptr, field, end)
756     char **ptr, *field, *end;
757 {
758     register int len;
759
760     len = field ? strlen (field) + 1 : 1;
761
762     if (*ptr+len > end)
763         return 1;
764     if (field)
765         (void) strcpy(*ptr, field);
766     else
767         **ptr = '\0';
768     *ptr += len;
769
770     return 0;
771 }
772
773 struct _Z_InputQ *Z_GetFirstComplete()
774 {
775     struct _Z_InputQ *qptr;
776
777     qptr = __Q_Head;
778
779     while (qptr) {
780         if (qptr->complete)
781             return (qptr);
782         qptr = qptr->next;
783     }
784
785     return ((struct _Z_InputQ *)0);
786 }
787
788 struct _Z_InputQ *Z_GetNextComplete(qptr)
789     struct _Z_InputQ *qptr;
790 {
791     qptr = qptr->next;
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 void Z_RemQueue(qptr)
802     struct _Z_InputQ *qptr;
803 {
804     struct _Z_Hole *hole, *nexthole;
805     
806     if (qptr->complete)
807         __Q_CompleteLength--;
808
809     __Q_Size -= qptr->msg_len;
810     
811     if (qptr->header)
812         free(qptr->header);
813     if (qptr->msg)
814         free(qptr->msg);
815     if (qptr->packet)
816         free(qptr->packet);
817     
818     hole = qptr->holelist;
819     while (hole) {
820         nexthole = hole->next;
821         free((char *)hole);
822         hole = nexthole;
823     }
824     
825     if (qptr == __Q_Head && __Q_Head == __Q_Tail) {
826         free ((char *)qptr);
827         __Q_Head = (struct _Z_InputQ *)0;
828         __Q_Tail = (struct _Z_InputQ *)0;
829         return;
830     }
831     
832     if (qptr == __Q_Head) {
833         __Q_Head = qptr->next;
834         __Q_Head->prev = (struct _Z_InputQ *)0;
835         free ((char *)qptr);
836         return;
837     } 
838     if (qptr == __Q_Tail) {
839         __Q_Tail = qptr->prev;
840         __Q_Tail->next = (struct _Z_InputQ *)0;
841         free ((char *)qptr);
842         return;
843     }
844     qptr->prev->next = qptr->next;
845     qptr->next->prev = qptr->prev;
846     free ((char *)qptr);
847     return;
848 }
849
850 Code_t Z_SendFragmentedNotice(notice, len, cert_func, send_func)
851     ZNotice_t *notice;
852     int len;
853     Z_AuthProc cert_func;
854     Z_SendProc send_func;
855 {
856     ZNotice_t partnotice;
857     ZPacket_t buffer;
858     char multi[64];
859     int offset, hdrsize, fragsize, ret_len, message_len, waitforack;
860     Code_t retval;
861     
862     hdrsize = len-notice->z_message_len;
863     fragsize = Z_MAXPKTLEN-hdrsize-Z_FRAGFUDGE;
864     
865     offset = 0;
866
867     waitforack = ((notice->z_kind == UNACKED || notice->z_kind == ACKED)
868                   && !__Zephyr_server);
869     
870     partnotice = *notice;
871
872     while (offset < notice->z_message_len || !notice->z_message_len) {
873         (void) sprintf(multi, "%d/%d", offset, notice->z_message_len);
874         partnotice.z_multinotice = multi;
875         if (offset > 0) {
876             (void) gettimeofday(&partnotice.z_uid.tv,
877                                 (struct timezone *)0);
878             partnotice.z_uid.tv.tv_sec =
879                 htonl((u_long) partnotice.z_uid.tv.tv_sec);
880             partnotice.z_uid.tv.tv_usec =
881                 htonl((u_long) partnotice.z_uid.tv.tv_usec);
882             (void) memcpy((char *)&partnotice.z_uid.zuid_addr, &__My_addr, 
883                           sizeof(__My_addr));
884         }
885         message_len = min(notice->z_message_len-offset, fragsize);
886         partnotice.z_message = notice->z_message+offset;
887         partnotice.z_message_len = message_len;
888         if ((retval = Z_FormatAuthHeader(&partnotice, buffer, Z_MAXHEADERLEN,
889                                          &ret_len, cert_func)) != ZERR_NONE) {
890             return (retval);
891         }
892         memcpy(buffer + ret_len, partnotice.z_message, message_len);
893         if ((retval = (*send_func)(&partnotice, buffer, ret_len+message_len,
894                                    waitforack)) != ZERR_NONE) {
895             return (retval);
896         }
897         offset += fragsize;
898         if (!notice->z_message_len)
899             break;
900     }
901
902     return (ZERR_NONE);
903 }
904
905 /*ARGSUSED*/
906 Code_t Z_XmitFragment(notice, buf, len, wait)
907 ZNotice_t *notice;
908 char *buf;
909 int len;
910 int wait;
911 {
912         return(ZSendPacket(buf, len, wait));
913 }
914
915 #ifdef Z_DEBUG
916 /* For debugging printing */
917 const char *const ZNoticeKinds[] = {
918     "UNSAFE", "UNACKED", "ACKED", "HMACK", "HMCTL", "SERVACK", "SERVNAK",
919     "CLIENTACK", "STAT"
920 };
921 #endif
922
923 #ifdef Z_DEBUG
924
925 #undef Z_debug
926 #ifdef HAVE_STDARG_H
927 void Z_debug (const char *format, ...)
928 {
929     va_list pvar;
930     if (!__Z_debug_print)
931       return;
932     va_start (pvar, format);
933     (*__Z_debug_print) (format, pvar, __Z_debug_print_closure);
934     va_end (pvar);
935 }
936 #else /* stdarg */
937 void Z_debug (va_alist) va_dcl
938 {
939     va_list pvar;
940     char *format;
941     if (!__Z_debug_print)
942       return;
943     va_start (pvar);
944     format = va_arg (pvar, char *);
945     (*__Z_debug_print) (format, pvar, __Z_debug_print_closure);
946     va_end (pvar);
947 }
948 #endif
949
950 void Z_debug_stderr (format, args, closure)
951      const char *format;
952      va_list args;
953      void *closure;
954 {
955 #ifdef HAVE_VPRINTF
956     vfprintf (stderr, format, args);
957 #else
958     _doprnt (format, args, stderr);
959 #endif
960     putc ('\n', stderr);
961 }
962
963 #undef ZGetFD
964 int ZGetFD () { return __Zephyr_fd; }
965
966 #undef ZQLength
967 int ZQLength () { return __Q_CompleteLength; }
968
969 #undef ZGetDestAddr
970 struct sockaddr_in ZGetDestAddr () { return __HM_addr; }
971
972 #undef ZGetRealm
973 Zconst char * ZGetRealm () { return __Zephyr_realm; }
974
975 #undef ZSetDebug
976 void ZSetDebug(proc, arg)
977     void (*proc) __P((const char *, va_list, void *));
978     char *arg;
979 {
980     __Z_debug_print = proc;
981     __Z_debug_print_closure = arg;
982 }
983 #endif /* Z_DEBUG */
984