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