1 /* This file is part of the Project Athena Zephyr Notification System.
2 * It contains source for the internal Zephyr routines.
4 * Created by: Robert French
6 * $Id: Zinternal.c,v 1.41 2000/01/27 03:48:53 ghudson Exp $
8 * Copyright (c) 1987,1988,1991 by the Massachusetts Institute of
10 * For copying and distribution information, see the file
15 #include <arpa/inet.h>
16 #include <sys/socket.h>
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.";
26 extern char *inet_ntoa ();
30 int __Zephyr_port = -1;
31 struct in_addr __My_addr;
32 int __Q_CompleteLength;
34 struct _Z_InputQ *__Q_Head, *__Q_Tail;
35 struct sockaddr_in __HM_addr;
36 struct sockaddr_in __HM_addr_real;
39 ZLocations_t *__locate_list;
42 ZSubscription_t *__subscriptions_list;
43 int __subscriptions_num;
44 int __subscriptions_next;
45 int Z_discarded_packets = 0;
48 C_Block __Zephyr_session;
50 char __Zephyr_realm[REALM_SZ];
53 void (*__Z_debug_print) __P((const char *fmt, va_list args, void *closure));
54 void *__Z_debug_print_closure;
57 #define min(a,b) ((a)<(b)?(a):(b))
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));
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)
71 static struct _filter {
85 /* Initialize the uid buffer if it hasn't been done already. */
87 size = Z_INITFILTERSIZE;
88 buffer = (struct _filter *) malloc(size * sizeof(*buffer));
93 /* Age the uid buffer, discarding any uids older than the clock skew. */
95 while (num && (now - buffer[start % size].t) > CLOCK_SKEW)
99 /* Make room for a new uid, since we'll probably have to insert one. */
101 new_size = size * 2 + 2;
102 new = (struct _filter *) malloc(new_size * sizeof(*new));
105 for (i = 0; i < num; i++)
106 new[i] = buffer[(start + i) % size];
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)
122 /* We didn't find it; insert the uid into the buffer after 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;
135 /* Return 1 if there is a packet waiting, 0 otherwise */
137 int Z_PacketWaiting()
142 tv.tv_sec = tv.tv_usec = 0;
144 FD_SET(ZGetFD(), &read);
145 return (select(ZGetFD() + 1, &read, NULL, NULL, &tv));
149 /* Wait for a complete notice to become available */
151 Code_t Z_WaitForComplete()
155 if (__Q_CompleteLength)
156 return (Z_ReadEnqueue());
158 while (!__Q_CompleteLength)
159 if ((retval = Z_ReadWait()) != ZERR_NONE)
166 /* Read any available packets and enqueue them */
168 Code_t Z_ReadEnqueue()
173 return (ZERR_NOPORT);
175 while (Z_PacketWaiting())
176 if ((retval = Z_ReadWait()) != ZERR_NONE)
184 * Search the queue for a notice with the proper multiuid - remove any
185 * notices that haven't been touched in a while
188 struct _Z_InputQ *Z_SearchQueue(uid, kind)
192 register struct _Z_InputQ *qptr;
193 struct _Z_InputQ *next;
196 (void) gettimeofday(&tv, (struct timezone *)0);
201 if (ZCompareUID(uid, &qptr->uid) && qptr->kind == kind)
204 if (qptr->timep && (qptr->timep+Z_NOTICETIMELIMIT < tv.tv_sec))
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...
216 * This routine does NOT guarantee a complete packet will be ready when it
222 register struct _Z_InputQ *qptr;
225 struct sockaddr_in olddest, from;
226 int from_len, packet_len, zvlen, part, partof;
233 return (ZERR_NOPORT);
236 FD_SET(ZGetFD(), &fds);
240 if (select(ZGetFD() + 1, &fds, NULL, NULL, &tv) < 0)
242 if (!FD_ISSET(ZGetFD(), &fds))
245 from_len = sizeof(struct sockaddr_in);
247 packet_len = recvfrom(ZGetFD(), packet, sizeof(packet), 0,
248 (struct sockaddr *)&from, &from_len);
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++;
263 /* Parse the notice */
264 if ((retval = ZParseNotice(packet, packet_len, ¬ice)) != ZERR_NONE)
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.
271 if (!__Zephyr_server) {
272 if (notice.z_kind != HMACK && notice.z_kind != SERVACK &&
273 notice.z_kind != SERVNAK && notice.z_kind != CLIENTACK) {
279 tmpnotice.z_kind = CLIENTACK;
280 tmpnotice.z_message_len = 0;
283 if ((retval = ZFormatSmallRawNotice(&tmpnotice, pkt, &len))
286 if ((retval = ZSendPacket(pkt, len, 0)) != ZERR_NONE)
290 if (find_or_insert_uid(¬ice.z_uid, notice.z_kind))
293 /* Check authentication on the notice. */
294 notice.z_checked_auth = ZCheckAuthentication(¬ice, &from);
299 * Parse apart the z_multinotice field - if the field is blank for
300 * some reason, assume this packet stands by itself.
302 slash = strchr(notice.z_multinotice, '/');
304 part = atoi(notice.z_multinotice);
305 partof = atoi(slash+1);
306 if (part > partof || partof == 0) {
308 partof = notice.z_message_len;
313 partof = notice.z_message_len;
316 /* Too big a packet...just ignore it! */
317 if (partof > Z_MAXNOTICESIZE)
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
325 switch (notice.z_kind) {
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)
337 if (!__Zephyr_server &&
338 !ZCompareUID(¬ice.z_multiuid, ¬ice.z_uid))
339 /* they're not the same... throw away this packet. */
341 /* fall thru & process it */
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(¬ice.z_multiuid,
349 * If this is the first fragment, and we haven't already
350 * gotten a first fragment, grab the header from it.
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);
357 (void) memcpy(qptr->header, packet, qptr->header_len);
359 return (Z_AddNoticeToEntry(qptr, ¬ice, part));
364 * We'll have to create a new entry...make sure the queue isn't
365 * going to get too big.
367 if (__Q_Size+(__Zephyr_server ? notice.z_message_len : partof) > Z_MAXQUEUESIZE)
371 * This is a notice we haven't heard of, so create a new queue
372 * entry for it and zero it out.
374 qptr = (struct _Z_InputQ *)malloc(sizeof(struct _Z_InputQ));
377 (void) memset((char *)qptr, 0, sizeof(struct _Z_InputQ));
379 /* Insert the entry at the end of the queue */
381 qptr->prev = __Q_Tail;
383 __Q_Tail->next = qptr;
390 /* Copy the from field, multiuid, kind, and checked authentication. */
392 qptr->uid = notice.z_multiuid;
393 qptr->kind = notice.z_kind;
394 qptr->auth = notice.z_checked_auth;
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.
401 * If a Zephyr Server, we always take the header.
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);
408 (void) memcpy(qptr->header, packet, qptr->header_len);
412 * If this is not a fragmented notice, then don't bother with a
414 * If we are a Zephyr server, all notices are treated as complete.
416 if (__Zephyr_server || (part == 0 && notice.z_message_len == partof)) {
417 __Q_CompleteLength++;
418 qptr->holelist = (struct _Z_Hole *) 0;
420 /* allocate a msg buf for this piece */
421 if (notice.z_message_len == 0)
423 else if (!(qptr->msg = (char *) malloc((unsigned) notice.z_message_len)))
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)))
432 (void) memcpy(qptr->packet, qptr->header, qptr->header_len);
434 (void) memcpy(qptr->packet+qptr->header_len, qptr->msg,
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.
443 if (!(qptr->msg = (char *) malloc((unsigned) partof)) && partof)
445 qptr->msg_len = partof;
449 * Well, it's a fragmented notice...allocate a hole list and
450 * initialize it to the full packet size. Then insert the
453 if (!(qptr->holelist = (struct _Z_Hole *)
454 malloc(sizeof(struct _Z_Hole))))
456 qptr->holelist->next = (struct _Z_Hole *) 0;
457 qptr->holelist->first = 0;
458 qptr->holelist->last = partof-1;
459 return (Z_AddNoticeToEntry(qptr, ¬ice, part));
463 /* Fragment management routines - compliments, more or less, of RFC815 */
465 Code_t Z_AddNoticeToEntry(qptr, notice, part)
466 struct _Z_InputQ *qptr;
470 int last, oldfirst, oldlast;
471 struct _Z_Hole *hole, *lasthole;
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;
480 (void) gettimeofday(&tv, (struct timezone *)0);
481 qptr->timep = tv.tv_sec;
483 last = part+notice->z_message_len-1;
485 hole = qptr->holelist;
486 lasthole = (struct _Z_Hole *) 0;
488 /* copy in the message body */
489 (void) memcpy(qptr->msg+part, notice->z_message, notice->z_message_len);
491 /* Search for a hole that overlaps with the current fragment */
493 if (part <= hole->last && last >= hole->first)
499 /* If we found one, delete it and reconstruct a new hole */
501 oldfirst = hole->first;
502 oldlast = hole->last;
504 lasthole->next = hole->next;
506 qptr->holelist = hole->next;
509 * Now create a new hole that is the original hole without the
512 if (part > oldfirst) {
513 /* Search for the end of the hole list */
514 hole = qptr->holelist;
515 lasthole = (struct _Z_Hole *) 0;
521 if (!(lasthole->next = (struct _Z_Hole *)
522 malloc(sizeof(struct _Z_InputQ))))
524 hole = lasthole->next;
527 if (!(qptr->holelist = (struct _Z_Hole *)
528 malloc(sizeof(struct _Z_InputQ))))
530 hole = qptr->holelist;
533 hole->first = oldfirst;
536 if (last < oldlast) {
537 /* Search for the end of the hole list */
538 hole = qptr->holelist;
539 lasthole = (struct _Z_Hole *) 0;
545 if (!(lasthole->next = (struct _Z_Hole *)
546 malloc(sizeof(struct _Z_InputQ))))
548 hole = lasthole->next;
551 if (!(qptr->holelist = (struct _Z_Hole *)
552 malloc(sizeof(struct _Z_InputQ))))
554 hole = qptr->holelist;
556 hole->next = (struct _Z_Hole *) 0;
557 hole->first = last+1;
558 hole->last = oldlast;
562 if (!qptr->holelist) {
564 __Q_CompleteLength++;
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)))
570 (void) memcpy(qptr->packet, qptr->header, qptr->header_len);
571 (void) memcpy(qptr->packet+qptr->header_len, qptr->msg,
578 void Z_gettimeofday(struct _ZTimeval *ztv, struct timezone *tz)
581 (void) gettimeofday(&tv, tz); /* yeah, yeah, I know */
582 ztv->tv_sec=tv.tv_sec;
583 ztv->tv_usec=tv.tv_usec;
586 Code_t Z_FormatHeader(notice, buffer, buffer_len, len, cert_routine)
591 Z_AuthProc cert_routine;
594 static char version[BUFSIZ]; /* default init should be all \0 */
595 struct sockaddr_in name;
596 int namelen = sizeof(name);
598 if (!notice->z_sender)
599 notice->z_sender = ZGetSender();
601 if (notice->z_port == 0) {
603 retval = ZOpenPort((u_short *)0);
604 if (retval != ZERR_NONE)
607 retval = getsockname(ZGetFD(), (struct sockaddr *) &name, &namelen);
610 notice->z_port = name.sin_port;
613 notice->z_multinotice = "";
615 (void) Z_gettimeofday(¬ice->z_uid.tv, (struct timezone *)0);
616 notice->z_uid.tv.tv_sec = htonl((u_long) notice->z_uid.tv.tv_sec);
617 notice->z_uid.tv.tv_usec = htonl((u_long) notice->z_uid.tv.tv_usec);
619 (void) memcpy(¬ice->z_uid.zuid_addr, &__My_addr, sizeof(__My_addr));
621 notice->z_multiuid = notice->z_uid;
624 (void) sprintf(version, "%s%d.%d", ZVERSIONHDR, ZVERSIONMAJOR,
626 notice->z_version = version;
628 return Z_FormatAuthHeader(notice, buffer, buffer_len, len, cert_routine);
631 Code_t Z_FormatAuthHeader(notice, buffer, buffer_len, len, cert_routine)
636 Z_AuthProc cert_routine;
640 notice->z_authent_len = 0;
641 notice->z_ascii_authent = "";
642 notice->z_checksum = 0;
643 return (Z_FormatRawHeader(notice, buffer, buffer_len,
647 return ((*cert_routine)(notice, buffer, buffer_len, len));
650 Code_t Z_FormatRawHeader(notice, buffer, buffer_len, len, cstart, cend)
655 char **cstart, **cend;
657 char newrecip[BUFSIZ];
661 if (!notice->z_class)
662 notice->z_class = "";
664 if (!notice->z_class_inst)
665 notice->z_class_inst = "";
667 if (!notice->z_opcode)
668 notice->z_opcode = "";
670 if (!notice->z_recipient)
671 notice->z_recipient = "";
673 if (!notice->z_default_format)
674 notice->z_default_format = "";
677 end = buffer+buffer_len;
679 if (buffer_len < strlen(notice->z_version)+1)
680 return (ZERR_HEADERLEN);
682 (void) strcpy(ptr, notice->z_version);
683 ptr += strlen(ptr)+1;
685 if (ZMakeAscii32(ptr, end-ptr, Z_NUMFIELDS + notice->z_num_other_fields)
687 return (ZERR_HEADERLEN);
688 ptr += strlen(ptr)+1;
690 if (ZMakeAscii32(ptr, end-ptr, notice->z_kind) == ZERR_FIELDLEN)
691 return (ZERR_HEADERLEN);
692 ptr += strlen(ptr)+1;
694 if (ZMakeAscii(ptr, end-ptr, (unsigned char *)¬ice->z_uid,
695 sizeof(ZUnique_Id_t)) == ZERR_FIELDLEN)
696 return (ZERR_HEADERLEN);
697 ptr += strlen(ptr)+1;
699 if (ZMakeAscii16(ptr, end-ptr, ntohs(notice->z_port)) == ZERR_FIELDLEN)
700 return (ZERR_HEADERLEN);
701 ptr += strlen(ptr)+1;
703 if (ZMakeAscii32(ptr, end-ptr, notice->z_auth) == ZERR_FIELDLEN)
704 return (ZERR_HEADERLEN);
705 ptr += strlen(ptr)+1;
707 if (ZMakeAscii32(ptr, end-ptr, notice->z_authent_len) == ZERR_FIELDLEN)
708 return (ZERR_HEADERLEN);
709 ptr += strlen(ptr)+1;
711 if (Z_AddField(&ptr, notice->z_ascii_authent, end))
712 return (ZERR_HEADERLEN);
713 if (Z_AddField(&ptr, notice->z_class, end))
714 return (ZERR_HEADERLEN);
715 if (Z_AddField(&ptr, notice->z_class_inst, end))
716 return (ZERR_HEADERLEN);
717 if (Z_AddField(&ptr, notice->z_opcode, end))
718 return (ZERR_HEADERLEN);
719 if (Z_AddField(&ptr, notice->z_sender, end))
720 return (ZERR_HEADERLEN);
721 if (strchr(notice->z_recipient, '@') || !*notice->z_recipient) {
722 if (Z_AddField(&ptr, notice->z_recipient, end))
723 return (ZERR_HEADERLEN);
726 if (strlen(notice->z_recipient) + strlen(__Zephyr_realm) + 2 >
728 return (ZERR_HEADERLEN);
729 (void) sprintf(newrecip, "%s@%s", notice->z_recipient, __Zephyr_realm);
730 if (Z_AddField(&ptr, newrecip, end))
731 return (ZERR_HEADERLEN);
733 if (Z_AddField(&ptr, notice->z_default_format, end))
734 return (ZERR_HEADERLEN);
736 /* copy back the end pointer location for crypto checksum */
739 if (ZMakeAscii32(ptr, end-ptr, notice->z_checksum) == ZERR_FIELDLEN)
740 return (ZERR_HEADERLEN);
741 ptr += strlen(ptr)+1;
745 if (Z_AddField(&ptr, notice->z_multinotice, end))
746 return (ZERR_HEADERLEN);
748 if (ZMakeAscii(ptr, end-ptr, (unsigned char *)¬ice->z_multiuid,
749 sizeof(ZUnique_Id_t)) == ZERR_FIELDLEN)
750 return (ZERR_HEADERLEN);
751 ptr += strlen(ptr)+1;
753 for (i=0;i<notice->z_num_other_fields;i++)
754 if (Z_AddField(&ptr, notice->z_other_fields[i], end))
755 return (ZERR_HEADERLEN);
763 Z_AddField(ptr, field, end)
764 char **ptr, *field, *end;
768 len = field ? strlen (field) + 1 : 1;
773 (void) strcpy(*ptr, field);
781 struct _Z_InputQ *Z_GetFirstComplete()
783 struct _Z_InputQ *qptr;
793 return ((struct _Z_InputQ *)0);
796 struct _Z_InputQ *Z_GetNextComplete(qptr)
797 struct _Z_InputQ *qptr;
806 return ((struct _Z_InputQ *)0);
809 void Z_RemQueue(qptr)
810 struct _Z_InputQ *qptr;
812 struct _Z_Hole *hole, *nexthole;
815 __Q_CompleteLength--;
817 __Q_Size -= qptr->msg_len;
826 hole = qptr->holelist;
828 nexthole = hole->next;
833 if (qptr == __Q_Head && __Q_Head == __Q_Tail) {
835 __Q_Head = (struct _Z_InputQ *)0;
836 __Q_Tail = (struct _Z_InputQ *)0;
840 if (qptr == __Q_Head) {
841 __Q_Head = qptr->next;
842 __Q_Head->prev = (struct _Z_InputQ *)0;
846 if (qptr == __Q_Tail) {
847 __Q_Tail = qptr->prev;
848 __Q_Tail->next = (struct _Z_InputQ *)0;
852 qptr->prev->next = qptr->next;
853 qptr->next->prev = qptr->prev;
858 Code_t Z_SendFragmentedNotice(notice, len, cert_func, send_func)
861 Z_AuthProc cert_func;
862 Z_SendProc send_func;
864 ZNotice_t partnotice;
867 int offset, hdrsize, fragsize, ret_len, message_len, waitforack;
870 hdrsize = len-notice->z_message_len;
871 fragsize = Z_MAXPKTLEN-hdrsize-Z_FRAGFUDGE;
875 waitforack = ((notice->z_kind == UNACKED || notice->z_kind == ACKED)
876 && !__Zephyr_server);
878 partnotice = *notice;
880 while (offset < notice->z_message_len || !notice->z_message_len) {
881 (void) sprintf(multi, "%d/%d", offset, notice->z_message_len);
882 partnotice.z_multinotice = multi;
884 (void) Z_gettimeofday(&partnotice.z_uid.tv,
885 (struct timezone *)0);
886 partnotice.z_uid.tv.tv_sec =
887 htonl((u_long) partnotice.z_uid.tv.tv_sec);
888 partnotice.z_uid.tv.tv_usec =
889 htonl((u_long) partnotice.z_uid.tv.tv_usec);
890 (void) memcpy((char *)&partnotice.z_uid.zuid_addr, &__My_addr,
893 message_len = min(notice->z_message_len-offset, fragsize);
894 partnotice.z_message = notice->z_message+offset;
895 partnotice.z_message_len = message_len;
896 if ((retval = Z_FormatAuthHeader(&partnotice, buffer, Z_MAXHEADERLEN,
897 &ret_len, cert_func)) != ZERR_NONE) {
900 memcpy(buffer + ret_len, partnotice.z_message, message_len);
901 if ((retval = (*send_func)(&partnotice, buffer, ret_len+message_len,
902 waitforack)) != ZERR_NONE) {
906 if (!notice->z_message_len)
914 Code_t Z_XmitFragment(notice, buf, len, wait)
920 return(ZSendPacket(buf, len, wait));
924 /* For debugging printing */
925 const char *const ZNoticeKinds[] = {
926 "UNSAFE", "UNACKED", "ACKED", "HMACK", "HMCTL", "SERVACK", "SERVNAK",
935 void Z_debug (const char *format, ...)
938 if (!__Z_debug_print)
940 va_start (pvar, format);
941 (*__Z_debug_print) (format, pvar, __Z_debug_print_closure);
945 void Z_debug (va_alist) va_dcl
949 if (!__Z_debug_print)
952 format = va_arg (pvar, char *);
953 (*__Z_debug_print) (format, pvar, __Z_debug_print_closure);
958 void Z_debug_stderr (format, args, closure)
964 vfprintf (stderr, format, args);
966 _doprnt (format, args, stderr);
972 int ZGetFD () { return __Zephyr_fd; }
975 int ZQLength () { return __Q_CompleteLength; }
978 struct sockaddr_in ZGetDestAddr () { return __HM_addr; }
981 Zconst char * ZGetRealm () { return __Zephyr_realm; }
984 void ZSetDebug(proc, arg)
985 void (*proc) __P((const char *, va_list, void *));
988 __Z_debug_print = proc;
989 __Z_debug_print_closure = arg;