1/*
2 * OSPF Sending and Receiving OSPF Packets.
3 * Copyright (C) 1999, 2000 Toshiaki Takada
4 *
5 * This file is part of GNU Zebra.
6 *
7 * GNU Zebra is free software; you can redistribute it and/or modify it
8 * under the terms of the GNU General Public License as published by the
9 * Free Software Foundation; either version 2, or (at your option) any
10 * later version.
11 *
12 * GNU Zebra is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 * General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with GNU Zebra; see the file COPYING.  If not, write to the Free
19 * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
20 * 02111-1307, USA.
21 */
22
23#include <zebra.h>
24
25#include "thread.h"
26#include "memory.h"
27#include "linklist.h"
28#include "prefix.h"
29#include "if.h"
30#include "table.h"
31#include "sockunion.h"
32#include "stream.h"
33#include "log.h"
34#include "sockopt.h"
35#include "checksum.h"
36#include "md5.h"
37
38#include "ospfd/ospfd.h"
39#include "ospfd/ospf_network.h"
40#include "ospfd/ospf_interface.h"
41#include "ospfd/ospf_ism.h"
42#include "ospfd/ospf_asbr.h"
43#include "ospfd/ospf_lsa.h"
44#include "ospfd/ospf_lsdb.h"
45#include "ospfd/ospf_neighbor.h"
46#include "ospfd/ospf_nsm.h"
47#include "ospfd/ospf_packet.h"
48#include "ospfd/ospf_spf.h"
49#include "ospfd/ospf_flood.h"
50#include "ospfd/ospf_dump.h"
51
52/* Packet Type String. */
53const struct message ospf_packet_type_str[] =
54{
55  { OSPF_MSG_HELLO,   "Hello"                     },
56  { OSPF_MSG_DB_DESC, "Database Description"      },
57  { OSPF_MSG_LS_REQ,  "Link State Request"        },
58  { OSPF_MSG_LS_UPD,  "Link State Update"         },
59  { OSPF_MSG_LS_ACK,  "Link State Acknowledgment" },
60};
61const size_t ospf_packet_type_str_max = sizeof (ospf_packet_type_str) /
62  sizeof (ospf_packet_type_str[0]);
63
64/* Minimum (besides OSPF_HEADER_SIZE) lengths for OSPF packets of
65   particular types, offset is the "type" field of a packet. */
66static const u_int16_t ospf_packet_minlen[] =
67{
68  0,
69  OSPF_HELLO_MIN_SIZE,
70  OSPF_DB_DESC_MIN_SIZE,
71  OSPF_LS_REQ_MIN_SIZE,
72  OSPF_LS_UPD_MIN_SIZE,
73  OSPF_LS_ACK_MIN_SIZE,
74};
75
76/* Minimum (besides OSPF_LSA_HEADER_SIZE) lengths for LSAs of particular
77   types, offset is the "LSA type" field. */
78static const u_int16_t ospf_lsa_minlen[] =
79{
80  0,
81  OSPF_ROUTER_LSA_MIN_SIZE,
82  OSPF_NETWORK_LSA_MIN_SIZE,
83  OSPF_SUMMARY_LSA_MIN_SIZE,
84  OSPF_SUMMARY_LSA_MIN_SIZE,
85  OSPF_AS_EXTERNAL_LSA_MIN_SIZE,
86  0,
87  OSPF_AS_EXTERNAL_LSA_MIN_SIZE,
88  0,
89  0,
90  0,
91  0,
92};
93
94/* for ospf_check_auth() */
95static int ospf_check_sum (struct ospf_header *);
96
97/* OSPF authentication checking function */
98static int
99ospf_auth_type (struct ospf_interface *oi)
100{
101  int auth_type;
102
103  if (OSPF_IF_PARAM (oi, auth_type) == OSPF_AUTH_NOTSET)
104    auth_type = oi->area->auth_type;
105  else
106    auth_type = OSPF_IF_PARAM (oi, auth_type);
107
108  /* Handle case where MD5 key list is not configured aka Cisco */
109  if (auth_type == OSPF_AUTH_CRYPTOGRAPHIC &&
110      list_isempty (OSPF_IF_PARAM (oi, auth_crypt)))
111    return OSPF_AUTH_NULL;
112
113  return auth_type;
114
115}
116
117struct ospf_packet *
118ospf_packet_new (size_t size)
119{
120  struct ospf_packet *new;
121
122  new = XCALLOC (MTYPE_OSPF_PACKET, sizeof (struct ospf_packet));
123  new->s = stream_new (size);
124
125  return new;
126}
127
128void
129ospf_packet_free (struct ospf_packet *op)
130{
131  if (op->s)
132    stream_free (op->s);
133
134  XFREE (MTYPE_OSPF_PACKET, op);
135
136  op = NULL;
137}
138
139struct ospf_fifo *
140ospf_fifo_new ()
141{
142  struct ospf_fifo *new;
143
144  new = XCALLOC (MTYPE_OSPF_FIFO, sizeof (struct ospf_fifo));
145  return new;
146}
147
148/* Add new packet to fifo. */
149void
150ospf_fifo_push (struct ospf_fifo *fifo, struct ospf_packet *op)
151{
152  if (fifo->tail)
153    fifo->tail->next = op;
154  else
155    fifo->head = op;
156
157  fifo->tail = op;
158
159  fifo->count++;
160}
161
162/* Add new packet to head of fifo. */
163static void
164ospf_fifo_push_head (struct ospf_fifo *fifo, struct ospf_packet *op)
165{
166  op->next = fifo->head;
167
168  if (fifo->tail == NULL)
169    fifo->tail = op;
170
171  fifo->head = op;
172
173  fifo->count++;
174}
175
176/* Delete first packet from fifo. */
177struct ospf_packet *
178ospf_fifo_pop (struct ospf_fifo *fifo)
179{
180  struct ospf_packet *op;
181
182  op = fifo->head;
183
184  if (op)
185    {
186      fifo->head = op->next;
187
188      if (fifo->head == NULL)
189	fifo->tail = NULL;
190
191      fifo->count--;
192    }
193
194  return op;
195}
196
197/* Return first fifo entry. */
198struct ospf_packet *
199ospf_fifo_head (struct ospf_fifo *fifo)
200{
201  return fifo->head;
202}
203
204/* Flush ospf packet fifo. */
205void
206ospf_fifo_flush (struct ospf_fifo *fifo)
207{
208  struct ospf_packet *op;
209  struct ospf_packet *next;
210
211  for (op = fifo->head; op; op = next)
212    {
213      next = op->next;
214      ospf_packet_free (op);
215    }
216  fifo->head = fifo->tail = NULL;
217  fifo->count = 0;
218}
219
220/* Free ospf packet fifo. */
221void
222ospf_fifo_free (struct ospf_fifo *fifo)
223{
224  ospf_fifo_flush (fifo);
225
226  XFREE (MTYPE_OSPF_FIFO, fifo);
227}
228
229void
230ospf_packet_add (struct ospf_interface *oi, struct ospf_packet *op)
231{
232  if (!oi->obuf)
233    {
234      zlog_err("ospf_packet_add(interface %s in state %d [%s], packet type %s, "
235	       "destination %s) called with NULL obuf, ignoring "
236	       "(please report this bug)!\n",
237	       IF_NAME(oi), oi->state, LOOKUP (ospf_ism_state_msg, oi->state),
238	       LOOKUP (ospf_packet_type_str, stream_getc_from(op->s, 1)),
239	       inet_ntoa (op->dst));
240      return;
241    }
242
243  /* Add packet to end of queue. */
244  ospf_fifo_push (oi->obuf, op);
245
246  /* Debug of packet fifo*/
247  /* ospf_fifo_debug (oi->obuf); */
248}
249
250static void
251ospf_packet_add_top (struct ospf_interface *oi, struct ospf_packet *op)
252{
253  if (!oi->obuf)
254    {
255      zlog_err("ospf_packet_add(interface %s in state %d [%s], packet type %s, "
256	       "destination %s) called with NULL obuf, ignoring "
257	       "(please report this bug)!\n",
258	       IF_NAME(oi), oi->state, LOOKUP (ospf_ism_state_msg, oi->state),
259	       LOOKUP (ospf_packet_type_str, stream_getc_from(op->s, 1)),
260	       inet_ntoa (op->dst));
261      return;
262    }
263
264  /* Add packet to head of queue. */
265  ospf_fifo_push_head (oi->obuf, op);
266
267  /* Debug of packet fifo*/
268  /* ospf_fifo_debug (oi->obuf); */
269}
270
271void
272ospf_packet_delete (struct ospf_interface *oi)
273{
274  struct ospf_packet *op;
275
276  op = ospf_fifo_pop (oi->obuf);
277
278  if (op)
279    ospf_packet_free (op);
280}
281
282struct ospf_packet *
283ospf_packet_dup (struct ospf_packet *op)
284{
285  struct ospf_packet *new;
286
287  if (stream_get_endp(op->s) != op->length)
288    /* XXX size_t */
289    zlog_warn ("ospf_packet_dup stream %lu ospf_packet %u size mismatch",
290	       (u_long)STREAM_SIZE(op->s), op->length);
291
292  /* Reserve space for MD5 authentication that may be added later. */
293  new = ospf_packet_new (stream_get_endp(op->s) + OSPF_AUTH_MD5_SIZE);
294  stream_copy (new->s, op->s);
295
296  new->dst = op->dst;
297  new->length = op->length;
298
299  return new;
300}
301
302/* XXX inline */
303static unsigned int
304ospf_packet_authspace (struct ospf_interface *oi)
305{
306  int auth = 0;
307
308  if ( ospf_auth_type (oi) == OSPF_AUTH_CRYPTOGRAPHIC)
309    auth = OSPF_AUTH_MD5_SIZE;
310
311  return auth;
312}
313
314static unsigned int
315ospf_packet_max (struct ospf_interface *oi)
316{
317  int max;
318
319  max = oi->ifp->mtu - ospf_packet_authspace(oi);
320
321  max -= (OSPF_HEADER_SIZE + sizeof (struct ip));
322
323  return max;
324}
325
326
327static int
328ospf_check_md5_digest (struct ospf_interface *oi, struct ospf_header *ospfh)
329{
330  MD5_CTX ctx;
331  unsigned char digest[OSPF_AUTH_MD5_SIZE];
332  struct crypt_key *ck;
333  struct ospf_neighbor *nbr;
334  u_int16_t length = ntohs (ospfh->length);
335
336  /* Get secret key. */
337  ck = ospf_crypt_key_lookup (OSPF_IF_PARAM (oi, auth_crypt),
338			      ospfh->u.crypt.key_id);
339  if (ck == NULL)
340    {
341      zlog_warn ("interface %s: ospf_check_md5 no key %d",
342		 IF_NAME (oi), ospfh->u.crypt.key_id);
343      return 0;
344    }
345
346  /* check crypto seqnum. */
347  nbr = ospf_nbr_lookup_by_routerid (oi->nbrs, &ospfh->router_id);
348
349  if (nbr && ntohl(nbr->crypt_seqnum) > ntohl(ospfh->u.crypt.crypt_seqnum))
350    {
351      zlog_warn ("interface %s: ospf_check_md5 bad sequence %d (expect %d)",
352		 IF_NAME (oi),
353		 ntohl(ospfh->u.crypt.crypt_seqnum),
354		 ntohl(nbr->crypt_seqnum));
355      return 0;
356    }
357
358  /* Generate a digest for the ospf packet - their digest + our digest. */
359  memset(&ctx, 0, sizeof(ctx));
360  MD5Init(&ctx);
361  MD5Update(&ctx, ospfh, length);
362  MD5Update(&ctx, ck->auth_key, OSPF_AUTH_MD5_SIZE);
363  MD5Final(digest, &ctx);
364
365  /* compare the two */
366  if (memcmp ((caddr_t)ospfh + length, digest, OSPF_AUTH_MD5_SIZE))
367    {
368      zlog_warn ("interface %s: ospf_check_md5 checksum mismatch",
369		 IF_NAME (oi));
370      return 0;
371    }
372
373  /* save neighbor's crypt_seqnum */
374  if (nbr)
375    nbr->crypt_seqnum = ospfh->u.crypt.crypt_seqnum;
376  return 1;
377}
378
379/* This function is called from ospf_write(), it will detect the
380   authentication scheme and if it is MD5, it will change the sequence
381   and update the MD5 digest. */
382static int
383ospf_make_md5_digest (struct ospf_interface *oi, struct ospf_packet *op)
384{
385  struct ospf_header *ospfh;
386  unsigned char digest[OSPF_AUTH_MD5_SIZE] = {0};
387  MD5_CTX ctx;
388  void *ibuf;
389  u_int32_t t;
390  struct crypt_key *ck;
391  const u_int8_t *auth_key;
392
393  ibuf = STREAM_DATA (op->s);
394  ospfh = (struct ospf_header *) ibuf;
395
396  if (ntohs (ospfh->auth_type) != OSPF_AUTH_CRYPTOGRAPHIC)
397    return 0;
398
399  /* We do this here so when we dup a packet, we don't have to
400     waste CPU rewriting other headers.
401
402     Note that quagga_time /deliberately/ is not used here */
403  t = (time(NULL) & 0xFFFFFFFF);
404  if (t > oi->crypt_seqnum)
405    oi->crypt_seqnum = t;
406  else
407    oi->crypt_seqnum++;
408
409  ospfh->u.crypt.crypt_seqnum = htonl (oi->crypt_seqnum);
410
411  /* Get MD5 Authentication key from auth_key list. */
412  if (list_isempty (OSPF_IF_PARAM (oi, auth_crypt)))
413    auth_key = (const u_int8_t *) digest;
414  else
415    {
416      ck = listgetdata (listtail(OSPF_IF_PARAM (oi, auth_crypt)));
417      auth_key = ck->auth_key;
418    }
419
420  /* Generate a digest for the entire packet + our secret key. */
421  memset(&ctx, 0, sizeof(ctx));
422  MD5Init(&ctx);
423  MD5Update(&ctx, ibuf, ntohs (ospfh->length));
424  MD5Update(&ctx, auth_key, OSPF_AUTH_MD5_SIZE);
425  MD5Final(digest, &ctx);
426
427  /* Append md5 digest to the end of the stream. */
428  stream_put (op->s, digest, OSPF_AUTH_MD5_SIZE);
429
430  /* We do *NOT* increment the OSPF header length. */
431  op->length = ntohs (ospfh->length) + OSPF_AUTH_MD5_SIZE;
432
433  if (stream_get_endp(op->s) != op->length)
434    /* XXX size_t */
435    zlog_warn("ospf_make_md5_digest: length mismatch stream %lu ospf_packet %u",
436	      (u_long)stream_get_endp(op->s), op->length);
437
438  return OSPF_AUTH_MD5_SIZE;
439}
440
441
442static int
443ospf_ls_req_timer (struct thread *thread)
444{
445  struct ospf_neighbor *nbr;
446
447  nbr = THREAD_ARG (thread);
448  nbr->t_ls_req = NULL;
449
450  /* Send Link State Request. */
451  if (ospf_ls_request_count (nbr))
452    ospf_ls_req_send (nbr);
453
454  /* Set Link State Request retransmission timer. */
455  OSPF_NSM_TIMER_ON (nbr->t_ls_req, ospf_ls_req_timer, nbr->v_ls_req);
456
457  return 0;
458}
459
460void
461ospf_ls_req_event (struct ospf_neighbor *nbr)
462{
463  if (nbr->t_ls_req)
464    {
465      thread_cancel (nbr->t_ls_req);
466      nbr->t_ls_req = NULL;
467    }
468  nbr->t_ls_req = thread_add_event (master, ospf_ls_req_timer, nbr, 0);
469}
470
471/* Cyclic timer function.  Fist registered in ospf_nbr_new () in
472   ospf_neighbor.c  */
473int
474ospf_ls_upd_timer (struct thread *thread)
475{
476  struct ospf_neighbor *nbr;
477
478  nbr = THREAD_ARG (thread);
479  nbr->t_ls_upd = NULL;
480
481  /* Send Link State Update. */
482  if (ospf_ls_retransmit_count (nbr) > 0)
483    {
484      struct list *update;
485      struct ospf_lsdb *lsdb;
486      int i;
487      int retransmit_interval;
488
489      retransmit_interval = OSPF_IF_PARAM (nbr->oi, retransmit_interval);
490
491      lsdb = &nbr->ls_rxmt;
492      update = list_new ();
493
494      for (i = OSPF_MIN_LSA; i < OSPF_MAX_LSA; i++)
495	{
496	  struct route_table *table = lsdb->type[i].db;
497	  struct route_node *rn;
498
499	  for (rn = route_top (table); rn; rn = route_next (rn))
500	    {
501	      struct ospf_lsa *lsa;
502
503	      if ((lsa = rn->info) != NULL)
504		/* Don't retransmit an LSA if we received it within
505		  the last RxmtInterval seconds - this is to allow the
506		  neighbour a chance to acknowledge the LSA as it may
507		  have ben just received before the retransmit timer
508		  fired.  This is a small tweak to what is in the RFC,
509		  but it will cut out out a lot of retransmit traffic
510		  - MAG */
511		if (tv_cmp (tv_sub (recent_relative_time (), lsa->tv_recv),
512			    int2tv (retransmit_interval)) >= 0)
513		  listnode_add (update, rn->info);
514	    }
515	}
516
517      if (listcount (update) > 0)
518	ospf_ls_upd_send (nbr, update, OSPF_SEND_PACKET_DIRECT);
519      list_delete (update);
520    }
521
522  /* Set LS Update retransmission timer. */
523  OSPF_NSM_TIMER_ON (nbr->t_ls_upd, ospf_ls_upd_timer, nbr->v_ls_upd);
524
525  return 0;
526}
527
528int
529ospf_ls_ack_timer (struct thread *thread)
530{
531  struct ospf_interface *oi;
532
533  oi = THREAD_ARG (thread);
534  oi->t_ls_ack = NULL;
535
536  /* Send Link State Acknowledgment. */
537  if (listcount (oi->ls_ack) > 0)
538    ospf_ls_ack_send_delayed (oi);
539
540  /* Set LS Ack timer. */
541  OSPF_ISM_TIMER_ON (oi->t_ls_ack, ospf_ls_ack_timer, oi->v_ls_ack);
542
543  return 0;
544}
545
546#ifdef WANT_OSPF_WRITE_FRAGMENT
547static void
548ospf_write_frags (int fd, struct ospf_packet *op, struct ip *iph,
549                  struct msghdr *msg, unsigned int maxdatasize,
550                  unsigned int mtu, int flags, u_char type)
551{
552#define OSPF_WRITE_FRAG_SHIFT 3
553  u_int16_t offset;
554  struct iovec *iovp;
555  int ret;
556
557  assert ( op->length == stream_get_endp(op->s) );
558  assert (msg->msg_iovlen == 2);
559
560  /* we can but try.
561   *
562   * SunOS, BSD and BSD derived kernels likely will clear ip_id, as
563   * well as the IP_MF flag, making this all quite pointless.
564   *
565   * However, for a system on which IP_MF is left alone, and ip_id left
566   * alone or else which sets same ip_id for each fragment this might
567   * work, eg linux.
568   *
569   * XXX-TODO: It would be much nicer to have the kernel's use their
570   * existing fragmentation support to do this for us. Bugs/RFEs need to
571   * be raised against the various kernels.
572   */
573
574  /* set More Frag */
575  iph->ip_off |= IP_MF;
576
577  /* ip frag offset is expressed in units of 8byte words */
578  offset = maxdatasize >> OSPF_WRITE_FRAG_SHIFT;
579
580  iovp = &msg->msg_iov[1];
581
582  while ( (stream_get_endp(op->s) - stream_get_getp (op->s))
583         > maxdatasize )
584    {
585      /* data length of this frag is to next offset value */
586      iovp->iov_len = offset << OSPF_WRITE_FRAG_SHIFT;
587      iph->ip_len = iovp->iov_len + sizeof (struct ip);
588      assert (iph->ip_len <= mtu);
589
590      sockopt_iphdrincl_swab_htosys (iph);
591
592      ret = sendmsg (fd, msg, flags);
593
594      sockopt_iphdrincl_swab_systoh (iph);
595
596      if (ret < 0)
597        zlog_warn ("*** ospf_write_frags: sendmsg failed to %s,"
598		   " id %d, off %d, len %d, mtu %u failed with %s",
599		   inet_ntoa (iph->ip_dst),
600		   iph->ip_id,
601		   iph->ip_off,
602		   iph->ip_len,
603		   mtu,
604		   safe_strerror (errno));
605
606      if (IS_DEBUG_OSPF_PACKET (type - 1, SEND))
607        {
608          zlog_debug ("ospf_write_frags: sent id %d, off %d, len %d to %s\n",
609                     iph->ip_id, iph->ip_off, iph->ip_len,
610                     inet_ntoa (iph->ip_dst));
611          if (IS_DEBUG_OSPF_PACKET (type - 1, DETAIL))
612            {
613              zlog_debug ("-----------------IP Header Dump----------------------");
614              ospf_ip_header_dump (iph);
615              zlog_debug ("-----------------------------------------------------");
616            }
617        }
618
619      iph->ip_off += offset;
620      stream_forward_getp (op->s, iovp->iov_len);
621      iovp->iov_base = STREAM_PNT (op->s);
622    }
623
624  /* setup for final fragment */
625  iovp->iov_len = stream_get_endp(op->s) - stream_get_getp (op->s);
626  iph->ip_len = iovp->iov_len + sizeof (struct ip);
627  iph->ip_off &= (~IP_MF);
628}
629#endif /* WANT_OSPF_WRITE_FRAGMENT */
630
631static int
632ospf_write (struct thread *thread)
633{
634  struct ospf *ospf = THREAD_ARG (thread);
635  struct ospf_interface *oi;
636  struct ospf_packet *op;
637  struct sockaddr_in sa_dst;
638  struct ip iph;
639  struct msghdr msg;
640  struct iovec iov[2];
641  u_char type;
642  int ret;
643  int flags = 0;
644  struct listnode *node;
645#ifdef WANT_OSPF_WRITE_FRAGMENT
646  static u_int16_t ipid = 0;
647#endif /* WANT_OSPF_WRITE_FRAGMENT */
648  u_int16_t maxdatasize;
649#define OSPF_WRITE_IPHL_SHIFT 2
650
651  ospf->t_write = NULL;
652
653  node = listhead (ospf->oi_write_q);
654  assert (node);
655  oi = listgetdata (node);
656  assert (oi);
657
658#ifdef WANT_OSPF_WRITE_FRAGMENT
659  /* seed ipid static with low order bits of time */
660  if (ipid == 0)
661    ipid = (time(NULL) & 0xffff);
662#endif /* WANT_OSPF_WRITE_FRAGMENT */
663
664  /* convenience - max OSPF data per packet,
665   * and reliability - not more data, than our
666   * socket can accept
667   */
668  maxdatasize = MIN (oi->ifp->mtu, ospf->maxsndbuflen) -
669    sizeof (struct ip);
670
671  /* Get one packet from queue. */
672  op = ospf_fifo_head (oi->obuf);
673  assert (op);
674  assert (op->length >= OSPF_HEADER_SIZE);
675
676  if (op->dst.s_addr == htonl (OSPF_ALLSPFROUTERS)
677      || op->dst.s_addr == htonl (OSPF_ALLDROUTERS))
678      ospf_if_ipmulticast (ospf, oi->address, oi->ifp->ifindex);
679
680  /* Rewrite the md5 signature & update the seq */
681  ospf_make_md5_digest (oi, op);
682
683  /* Retrieve OSPF packet type. */
684  stream_set_getp (op->s, 1);
685  type = stream_getc (op->s);
686
687  /* reset get pointer */
688  stream_set_getp (op->s, 0);
689
690  memset (&iph, 0, sizeof (struct ip));
691  memset (&sa_dst, 0, sizeof (sa_dst));
692
693  sa_dst.sin_family = AF_INET;
694#ifdef HAVE_STRUCT_SOCKADDR_IN_SIN_LEN
695  sa_dst.sin_len = sizeof(sa_dst);
696#endif /* HAVE_STRUCT_SOCKADDR_IN_SIN_LEN */
697  sa_dst.sin_addr = op->dst;
698  sa_dst.sin_port = htons (0);
699
700  /* Set DONTROUTE flag if dst is unicast. */
701  if (oi->type != OSPF_IFTYPE_VIRTUALLINK)
702    if (!IN_MULTICAST (htonl (op->dst.s_addr)))
703      flags = MSG_DONTROUTE;
704
705  iph.ip_hl = sizeof (struct ip) >> OSPF_WRITE_IPHL_SHIFT;
706  /* it'd be very strange for header to not be 4byte-word aligned but.. */
707  if ( sizeof (struct ip)
708        > (unsigned int)(iph.ip_hl << OSPF_WRITE_IPHL_SHIFT) )
709    iph.ip_hl++; /* we presume sizeof struct ip cant overflow ip_hl.. */
710
711  iph.ip_v = IPVERSION;
712  iph.ip_tos = IPTOS_PREC_INTERNETCONTROL;
713  iph.ip_len = (iph.ip_hl << OSPF_WRITE_IPHL_SHIFT) + op->length;
714
715#if defined(__DragonFly__)
716  /*
717   * DragonFly's raw socket expects ip_len/ip_off in network byte order.
718   */
719  iph.ip_len = htons(iph.ip_len);
720#endif
721
722#ifdef WANT_OSPF_WRITE_FRAGMENT
723  /* XXX-MT: not thread-safe at all..
724   * XXX: this presumes this is only programme sending OSPF packets
725   * otherwise, no guarantee ipid will be unique
726   */
727  iph.ip_id = ++ipid;
728#endif /* WANT_OSPF_WRITE_FRAGMENT */
729
730  iph.ip_off = 0;
731  if (oi->type == OSPF_IFTYPE_VIRTUALLINK)
732    iph.ip_ttl = OSPF_VL_IP_TTL;
733  else
734    iph.ip_ttl = OSPF_IP_TTL;
735  iph.ip_p = IPPROTO_OSPFIGP;
736  iph.ip_sum = 0;
737  iph.ip_src.s_addr = oi->address->u.prefix4.s_addr;
738  iph.ip_dst.s_addr = op->dst.s_addr;
739
740  memset (&msg, 0, sizeof (msg));
741  msg.msg_name = (caddr_t) &sa_dst;
742  msg.msg_namelen = sizeof (sa_dst);
743  msg.msg_iov = iov;
744  msg.msg_iovlen = 2;
745  iov[0].iov_base = (char*)&iph;
746  iov[0].iov_len = iph.ip_hl << OSPF_WRITE_IPHL_SHIFT;
747  iov[1].iov_base = STREAM_PNT (op->s);
748  iov[1].iov_len = op->length;
749
750  /* Sadly we can not rely on kernels to fragment packets because of either
751   * IP_HDRINCL and/or multicast destination being set.
752   */
753#ifdef WANT_OSPF_WRITE_FRAGMENT
754  if ( op->length > maxdatasize )
755    ospf_write_frags (ospf->fd, op, &iph, &msg, maxdatasize,
756                      oi->ifp->mtu, flags, type);
757#endif /* WANT_OSPF_WRITE_FRAGMENT */
758
759  /* send final fragment (could be first) */
760  sockopt_iphdrincl_swab_htosys (&iph);
761  ret = sendmsg (ospf->fd, &msg, flags);
762  sockopt_iphdrincl_swab_systoh (&iph);
763
764  if (ret < 0)
765    zlog_warn ("*** sendmsg in ospf_write failed to %s, "
766	       "id %d, off %d, len %d, interface %s, mtu %u: %s",
767	       inet_ntoa (iph.ip_dst), iph.ip_id, iph.ip_off, iph.ip_len,
768	       oi->ifp->name, oi->ifp->mtu, safe_strerror (errno));
769
770  /* Show debug sending packet. */
771  if (IS_DEBUG_OSPF_PACKET (type - 1, SEND))
772    {
773      if (IS_DEBUG_OSPF_PACKET (type - 1, DETAIL))
774	{
775	  zlog_debug ("-----------------------------------------------------");
776	  ospf_ip_header_dump (&iph);
777	  stream_set_getp (op->s, 0);
778	  ospf_packet_dump (op->s);
779	}
780
781      zlog_debug ("%s sent to [%s] via [%s].",
782		 LOOKUP (ospf_packet_type_str, type), inet_ntoa (op->dst),
783		 IF_NAME (oi));
784
785      if (IS_DEBUG_OSPF_PACKET (type - 1, DETAIL))
786	zlog_debug ("-----------------------------------------------------");
787    }
788
789  /* Now delete packet from queue. */
790  ospf_packet_delete (oi);
791
792  /* Move this interface to the tail of write_q to
793	 serve everyone in a round robin fashion */
794  listnode_move_to_tail (ospf->oi_write_q, node);
795  if (ospf_fifo_head (oi->obuf) == NULL)
796    {
797      oi->on_write_q = 0;
798      list_delete_node (ospf->oi_write_q, node);
799    }
800
801  /* If packets still remain in queue, call write thread. */
802  if (!list_isempty (ospf->oi_write_q))
803    ospf->t_write =
804      thread_add_write (master, ospf_write, ospf, ospf->fd);
805
806  return 0;
807}
808
809/* OSPF Hello message read -- RFC2328 Section 10.5. */
810static void
811ospf_hello (struct ip *iph, struct ospf_header *ospfh,
812	    struct stream * s, struct ospf_interface *oi, int size)
813{
814  struct ospf_hello *hello;
815  struct ospf_neighbor *nbr;
816  int old_state;
817  struct prefix p;
818
819  /* increment statistics. */
820  oi->hello_in++;
821
822  hello = (struct ospf_hello *) STREAM_PNT (s);
823
824  /* If Hello is myself, silently discard. */
825  if (IPV4_ADDR_SAME (&ospfh->router_id, &oi->ospf->router_id))
826    {
827      if (IS_DEBUG_OSPF_PACKET (ospfh->type - 1, RECV))
828        {
829          zlog_debug ("ospf_header[%s/%s]: selforiginated, "
830                     "dropping.",
831                     LOOKUP (ospf_packet_type_str, ospfh->type),
832                     inet_ntoa (iph->ip_src));
833        }
834      return;
835    }
836
837  /* get neighbor prefix. */
838  p.family = AF_INET;
839  p.prefixlen = ip_masklen (hello->network_mask);
840  p.u.prefix4 = iph->ip_src;
841
842  /* Compare network mask. */
843  /* Checking is ignored for Point-to-Point and Virtual link. */
844  if (oi->type != OSPF_IFTYPE_POINTOPOINT
845      && oi->type != OSPF_IFTYPE_VIRTUALLINK)
846    if (oi->address->prefixlen != p.prefixlen)
847      {
848	zlog_warn ("Packet %s [Hello:RECV]: NetworkMask mismatch on %s (configured prefix length is %d, but hello packet indicates %d).",
849		   inet_ntoa(ospfh->router_id), IF_NAME(oi),
850		   (int)oi->address->prefixlen, (int)p.prefixlen);
851	return;
852      }
853
854  /* Compare Router Dead Interval. */
855  if (OSPF_IF_PARAM (oi, v_wait) != ntohl (hello->dead_interval))
856    {
857      zlog_warn ("Packet %s [Hello:RECV]: RouterDeadInterval mismatch "
858      		 "(expected %u, but received %u).",
859		 inet_ntoa(ospfh->router_id),
860		 OSPF_IF_PARAM(oi, v_wait), ntohl(hello->dead_interval));
861      return;
862    }
863
864  /* Compare Hello Interval - ignored if fast-hellos are set. */
865  if (OSPF_IF_PARAM (oi, fast_hello) == 0)
866    {
867      if (OSPF_IF_PARAM (oi, v_hello) != ntohs (hello->hello_interval))
868        {
869          zlog_warn ("Packet %s [Hello:RECV]: HelloInterval mismatch "
870		     "(expected %u, but received %u).",
871		     inet_ntoa(ospfh->router_id),
872		     OSPF_IF_PARAM(oi, v_hello), ntohs(hello->hello_interval));
873          return;
874        }
875    }
876
877  if (IS_DEBUG_OSPF_EVENT)
878    zlog_debug ("Packet %s [Hello:RECV]: Options %s",
879	       inet_ntoa (ospfh->router_id),
880	       ospf_options_dump (hello->options));
881
882  /* Compare options. */
883#define REJECT_IF_TBIT_ON	1 /* XXX */
884#ifdef REJECT_IF_TBIT_ON
885  if (CHECK_FLAG (hello->options, OSPF_OPTION_T))
886    {
887      /*
888       * This router does not support non-zero TOS.
889       * Drop this Hello packet not to establish neighbor relationship.
890       */
891      zlog_warn ("Packet %s [Hello:RECV]: T-bit on, drop it.",
892		 inet_ntoa (ospfh->router_id));
893      return;
894    }
895#endif /* REJECT_IF_TBIT_ON */
896
897#ifdef HAVE_OPAQUE_LSA
898  if (CHECK_FLAG (oi->ospf->config, OSPF_OPAQUE_CAPABLE)
899      && CHECK_FLAG (hello->options, OSPF_OPTION_O))
900    {
901      /*
902       * This router does know the correct usage of O-bit
903       * the bit should be set in DD packet only.
904       */
905      zlog_warn ("Packet %s [Hello:RECV]: O-bit abuse?",
906		 inet_ntoa (ospfh->router_id));
907#ifdef STRICT_OBIT_USAGE_CHECK
908      return;                                     /* Reject this packet. */
909#else /* STRICT_OBIT_USAGE_CHECK */
910      UNSET_FLAG (hello->options, OSPF_OPTION_O); /* Ignore O-bit. */
911#endif /* STRICT_OBIT_USAGE_CHECK */
912    }
913#endif /* HAVE_OPAQUE_LSA */
914
915  /* new for NSSA is to ensure that NP is on and E is off */
916
917  if (oi->area->external_routing == OSPF_AREA_NSSA)
918    {
919      if (! (CHECK_FLAG (OPTIONS (oi), OSPF_OPTION_NP)
920	     && CHECK_FLAG (hello->options, OSPF_OPTION_NP)
921	     && ! CHECK_FLAG (OPTIONS (oi), OSPF_OPTION_E)
922	     && ! CHECK_FLAG (hello->options, OSPF_OPTION_E)))
923	{
924	  zlog_warn ("NSSA-Packet-%s[Hello:RECV]: my options: %x, his options %x", inet_ntoa (ospfh->router_id), OPTIONS (oi), hello->options);
925	  return;
926	}
927      if (IS_DEBUG_OSPF_NSSA)
928        zlog_debug ("NSSA-Hello:RECV:Packet from %s:", inet_ntoa(ospfh->router_id));
929    }
930  else
931    /* The setting of the E-bit found in the Hello Packet's Options
932       field must match this area's ExternalRoutingCapability A
933       mismatch causes processing to stop and the packet to be
934       dropped. The setting of the rest of the bits in the Hello
935       Packet's Options field should be ignored. */
936    if (CHECK_FLAG (OPTIONS (oi), OSPF_OPTION_E) !=
937	CHECK_FLAG (hello->options, OSPF_OPTION_E))
938      {
939	zlog_warn ("Packet %s [Hello:RECV]: my options: %x, his options %x",
940		   inet_ntoa(ospfh->router_id), OPTIONS (oi), hello->options);
941	return;
942      }
943
944  /* get neighbour struct */
945  nbr = ospf_nbr_get (oi, ospfh, iph, &p);
946
947  /* neighbour must be valid, ospf_nbr_get creates if none existed */
948  assert (nbr);
949
950  old_state = nbr->state;
951
952  /* Add event to thread. */
953  OSPF_NSM_EVENT_SCHEDULE (nbr, NSM_PacketReceived);
954
955  /*  RFC2328  Section 9.5.1
956      If the router is not eligible to become Designated Router,
957      (snip)   It	must also send an Hello	Packet in reply	to an
958      Hello Packet received from any eligible neighbor (other than
959      the	current	Designated Router and Backup Designated	Router).  */
960  if (oi->type == OSPF_IFTYPE_NBMA)
961    if (PRIORITY(oi) == 0 && hello->priority > 0
962	&& IPV4_ADDR_CMP(&DR(oi),  &iph->ip_src)
963	&& IPV4_ADDR_CMP(&BDR(oi), &iph->ip_src))
964      OSPF_NSM_TIMER_ON (nbr->t_hello_reply, ospf_hello_reply_timer,
965			 OSPF_HELLO_REPLY_DELAY);
966
967  /* on NBMA network type, it happens to receive bidirectional Hello packet
968     without advance 1-Way Received event.
969     To avoid incorrect DR-seletion, raise 1-Way Received event.*/
970  if (oi->type == OSPF_IFTYPE_NBMA &&
971      (old_state == NSM_Down || old_state == NSM_Attempt))
972    {
973      OSPF_NSM_EVENT_SCHEDULE (nbr, NSM_OneWayReceived);
974      nbr->priority = hello->priority;
975      nbr->d_router = hello->d_router;
976      nbr->bd_router = hello->bd_router;
977      return;
978    }
979
980  if (ospf_nbr_bidirectional (&oi->ospf->router_id, hello->neighbors,
981			      size - OSPF_HELLO_MIN_SIZE))
982    {
983      OSPF_NSM_EVENT_SCHEDULE (nbr, NSM_TwoWayReceived);
984      nbr->options |= hello->options;
985    }
986  else
987    {
988      OSPF_NSM_EVENT_SCHEDULE (nbr, NSM_OneWayReceived);
989      /* Set neighbor information. */
990      nbr->priority = hello->priority;
991      nbr->d_router = hello->d_router;
992      nbr->bd_router = hello->bd_router;
993      return;
994    }
995
996  /* If neighbor itself declares DR and no BDR exists,
997     cause event BackupSeen */
998  if (IPV4_ADDR_SAME (&nbr->address.u.prefix4, &hello->d_router))
999    if (hello->bd_router.s_addr == 0 && oi->state == ISM_Waiting)
1000      OSPF_ISM_EVENT_SCHEDULE (oi, ISM_BackupSeen);
1001
1002  /* neighbor itself declares BDR. */
1003  if (oi->state == ISM_Waiting &&
1004      IPV4_ADDR_SAME (&nbr->address.u.prefix4, &hello->bd_router))
1005    OSPF_ISM_EVENT_SCHEDULE (oi, ISM_BackupSeen);
1006
1007  /* had not previously. */
1008  if ((IPV4_ADDR_SAME (&nbr->address.u.prefix4, &hello->d_router) &&
1009       IPV4_ADDR_CMP (&nbr->address.u.prefix4, &nbr->d_router)) ||
1010      (IPV4_ADDR_CMP (&nbr->address.u.prefix4, &hello->d_router) &&
1011       IPV4_ADDR_SAME (&nbr->address.u.prefix4, &nbr->d_router)))
1012    OSPF_ISM_EVENT_SCHEDULE (oi, ISM_NeighborChange);
1013
1014  /* had not previously. */
1015  if ((IPV4_ADDR_SAME (&nbr->address.u.prefix4, &hello->bd_router) &&
1016       IPV4_ADDR_CMP (&nbr->address.u.prefix4, &nbr->bd_router)) ||
1017      (IPV4_ADDR_CMP (&nbr->address.u.prefix4, &hello->bd_router) &&
1018       IPV4_ADDR_SAME (&nbr->address.u.prefix4, &nbr->bd_router)))
1019    OSPF_ISM_EVENT_SCHEDULE (oi, ISM_NeighborChange);
1020
1021  /* Neighbor priority check. */
1022  if (nbr->priority >= 0 && nbr->priority != hello->priority)
1023    OSPF_ISM_EVENT_SCHEDULE (oi, ISM_NeighborChange);
1024
1025  /* Set neighbor information. */
1026  nbr->priority = hello->priority;
1027  nbr->d_router = hello->d_router;
1028  nbr->bd_router = hello->bd_router;
1029}
1030
1031/* Save DD flags/options/Seqnum received. */
1032static void
1033ospf_db_desc_save_current (struct ospf_neighbor *nbr,
1034			   struct ospf_db_desc *dd)
1035{
1036  nbr->last_recv.flags = dd->flags;
1037  nbr->last_recv.options = dd->options;
1038  nbr->last_recv.dd_seqnum = ntohl (dd->dd_seqnum);
1039}
1040
1041/* Process rest of DD packet. */
1042static void
1043ospf_db_desc_proc (struct stream *s, struct ospf_interface *oi,
1044		   struct ospf_neighbor *nbr, struct ospf_db_desc *dd,
1045		   u_int16_t size)
1046{
1047  struct ospf_lsa *new, *find;
1048  struct lsa_header *lsah;
1049
1050  stream_forward_getp (s, OSPF_DB_DESC_MIN_SIZE);
1051  for (size -= OSPF_DB_DESC_MIN_SIZE;
1052       size >= OSPF_LSA_HEADER_SIZE; size -= OSPF_LSA_HEADER_SIZE)
1053    {
1054      lsah = (struct lsa_header *) STREAM_PNT (s);
1055      stream_forward_getp (s, OSPF_LSA_HEADER_SIZE);
1056
1057      /* Unknown LS type. */
1058      if (lsah->type < OSPF_MIN_LSA || lsah->type >= OSPF_MAX_LSA)
1059	{
1060	  zlog_warn ("Packet [DD:RECV]: Unknown LS type %d.", lsah->type);
1061	  OSPF_NSM_EVENT_SCHEDULE (nbr, NSM_SeqNumberMismatch);
1062	  return;
1063	}
1064
1065#ifdef HAVE_OPAQUE_LSA
1066      if (IS_OPAQUE_LSA (lsah->type)
1067      &&  ! CHECK_FLAG (nbr->options, OSPF_OPTION_O))
1068        {
1069          zlog_warn ("LSA[Type%d:%s]: Opaque capability mismatch?", lsah->type, inet_ntoa (lsah->id));
1070          OSPF_NSM_EVENT_SCHEDULE (nbr, NSM_SeqNumberMismatch);
1071          return;
1072        }
1073#endif /* HAVE_OPAQUE_LSA */
1074
1075      switch (lsah->type)
1076        {
1077        case OSPF_AS_EXTERNAL_LSA:
1078#ifdef HAVE_OPAQUE_LSA
1079	case OSPF_OPAQUE_AS_LSA:
1080#endif /* HAVE_OPAQUE_LSA */
1081          /* Check for stub area.  Reject if AS-External from stub but
1082             allow if from NSSA. */
1083          if (oi->area->external_routing == OSPF_AREA_STUB)
1084            {
1085              zlog_warn ("Packet [DD:RECV]: LSA[Type%d:%s] from %s area.",
1086                         lsah->type, inet_ntoa (lsah->id),
1087                         (oi->area->external_routing == OSPF_AREA_STUB) ?\
1088                         "STUB" : "NSSA");
1089              OSPF_NSM_EVENT_SCHEDULE (nbr, NSM_SeqNumberMismatch);
1090              return;
1091            }
1092          break;
1093	default:
1094	  break;
1095        }
1096
1097      /* Create LS-request object. */
1098      new = ospf_ls_request_new (lsah);
1099
1100      /* Lookup received LSA, then add LS request list. */
1101      find = ospf_lsa_lookup_by_header (oi->area, lsah);
1102
1103      /* ospf_lsa_more_recent is fine with NULL pointers */
1104      switch (ospf_lsa_more_recent (find, new))
1105        {
1106          case -1:
1107            /* Neighbour has a more recent LSA, we must request it */
1108            ospf_ls_request_add (nbr, new);
1109          case 0:
1110            /* If we have a copy of this LSA, it's either less recent
1111             * and we're requesting it from neighbour (the case above), or
1112             * it's as recent and we both have same copy (this case).
1113             *
1114             * In neither of these two cases is there any point in
1115             * describing our copy of the LSA to the neighbour in a
1116             * DB-Summary packet, if we're still intending to do so.
1117             *
1118             * See: draft-ogier-ospf-dbex-opt-00.txt, describing the
1119             * backward compatible optimisation to OSPF DB Exchange /
1120             * DB Description process implemented here.
1121             */
1122            if (find)
1123              ospf_lsdb_delete (&nbr->db_sum, find);
1124            ospf_lsa_discard (new);
1125            break;
1126          default:
1127            /* We have the more recent copy, nothing specific to do:
1128             * - no need to request neighbours stale copy
1129             * - must leave DB summary list copy alone
1130             */
1131            if (IS_DEBUG_OSPF_EVENT)
1132              zlog_debug ("Packet [DD:RECV]: LSA received Type %d, "
1133                         "ID %s is not recent.", lsah->type, inet_ntoa (lsah->id));
1134            ospf_lsa_discard (new);
1135        }
1136    }
1137
1138  /* Master */
1139  if (IS_SET_DD_MS (nbr->dd_flags))
1140    {
1141      nbr->dd_seqnum++;
1142
1143      /* Both sides have no More, then we're done with Exchange */
1144      if (!IS_SET_DD_M (dd->flags) && !IS_SET_DD_M (nbr->dd_flags))
1145	OSPF_NSM_EVENT_SCHEDULE (nbr, NSM_ExchangeDone);
1146      else
1147	ospf_db_desc_send (nbr);
1148    }
1149  /* Slave */
1150  else
1151    {
1152      nbr->dd_seqnum = ntohl (dd->dd_seqnum);
1153
1154      /* Send DD packet in reply.
1155       *
1156       * Must be done to acknowledge the Master's DD, regardless of
1157       * whether we have more LSAs ourselves to describe.
1158       *
1159       * This function will clear the 'More' bit, if after this DD
1160       * we have no more LSAs to describe to the master..
1161       */
1162      ospf_db_desc_send (nbr);
1163
1164      /* Slave can raise ExchangeDone now, if master is also done */
1165      if (!IS_SET_DD_M (dd->flags) && !IS_SET_DD_M (nbr->dd_flags))
1166	OSPF_NSM_EVENT_SCHEDULE (nbr, NSM_ExchangeDone);
1167    }
1168
1169  /* Save received neighbor values from DD. */
1170  ospf_db_desc_save_current (nbr, dd);
1171}
1172
1173static int
1174ospf_db_desc_is_dup (struct ospf_db_desc *dd, struct ospf_neighbor *nbr)
1175{
1176  /* Is DD duplicated? */
1177  if (dd->options == nbr->last_recv.options &&
1178      dd->flags == nbr->last_recv.flags &&
1179      dd->dd_seqnum == htonl (nbr->last_recv.dd_seqnum))
1180    return 1;
1181
1182  return 0;
1183}
1184
1185/* OSPF Database Description message read -- RFC2328 Section 10.6. */
1186static void
1187ospf_db_desc (struct ip *iph, struct ospf_header *ospfh,
1188	      struct stream *s, struct ospf_interface *oi, u_int16_t size)
1189{
1190  struct ospf_db_desc *dd;
1191  struct ospf_neighbor *nbr;
1192
1193  /* Increment statistics. */
1194  oi->db_desc_in++;
1195
1196  dd = (struct ospf_db_desc *) STREAM_PNT (s);
1197
1198  nbr = ospf_nbr_lookup (oi, iph, ospfh);
1199  if (nbr == NULL)
1200    {
1201      zlog_warn ("Packet[DD]: Unknown Neighbor %s",
1202		 inet_ntoa (ospfh->router_id));
1203      return;
1204    }
1205
1206  /* Check MTU. */
1207  if ((OSPF_IF_PARAM (oi, mtu_ignore) == 0) &&
1208      (ntohs (dd->mtu) > oi->ifp->mtu))
1209    {
1210      zlog_warn ("Packet[DD]: Neighbor %s MTU %u is larger than [%s]'s MTU %u",
1211		 inet_ntoa (nbr->router_id), ntohs (dd->mtu),
1212		 IF_NAME (oi), oi->ifp->mtu);
1213      return;
1214    }
1215
1216  /*
1217   * XXX HACK by Hasso Tepper. Setting N/P bit in NSSA area DD packets is not
1218   * required. In fact at least JunOS sends DD packets with P bit clear.
1219   * Until proper solution is developped, this hack should help.
1220   *
1221   * Update: According to the RFCs, N bit is specified /only/ for Hello
1222   * options, unfortunately its use in DD options is not specified. Hence some
1223   * implementations follow E-bit semantics and set it in DD options, and some
1224   * treat it as unspecified and hence follow the directive "default for
1225   * options is clear", ie unset.
1226   *
1227   * Reset the flag, as ospfd follows E-bit semantics.
1228   */
1229  if ( (oi->area->external_routing == OSPF_AREA_NSSA)
1230       && (CHECK_FLAG (nbr->options, OSPF_OPTION_NP))
1231       && (!CHECK_FLAG (dd->options, OSPF_OPTION_NP)) )
1232    {
1233      if (IS_DEBUG_OSPF_EVENT)
1234        zlog_debug ("Packet[DD]: Neighbour %s: Has NSSA capability, sends with N bit clear in DD options",
1235                    inet_ntoa (nbr->router_id) );
1236      SET_FLAG (dd->options, OSPF_OPTION_NP);
1237    }
1238
1239#ifdef REJECT_IF_TBIT_ON
1240  if (CHECK_FLAG (dd->options, OSPF_OPTION_T))
1241    {
1242      /*
1243       * In Hello protocol, optional capability must have checked
1244       * to prevent this T-bit enabled router be my neighbor.
1245       */
1246      zlog_warn ("Packet[DD]: Neighbor %s: T-bit on?", inet_ntoa (nbr->router_id));
1247      return;
1248    }
1249#endif /* REJECT_IF_TBIT_ON */
1250
1251#ifdef HAVE_OPAQUE_LSA
1252  if (CHECK_FLAG (dd->options, OSPF_OPTION_O)
1253      && !CHECK_FLAG (oi->ospf->config, OSPF_OPAQUE_CAPABLE))
1254    {
1255      /*
1256       * This node is not configured to handle O-bit, for now.
1257       * Clear it to ignore unsupported capability proposed by neighbor.
1258       */
1259      UNSET_FLAG (dd->options, OSPF_OPTION_O);
1260    }
1261#endif /* HAVE_OPAQUE_LSA */
1262
1263  /* Add event to thread. */
1264  OSPF_NSM_EVENT_SCHEDULE (nbr, NSM_PacketReceived);
1265
1266  /* Process DD packet by neighbor status. */
1267  switch (nbr->state)
1268    {
1269    case NSM_Down:
1270    case NSM_Attempt:
1271    case NSM_TwoWay:
1272      zlog_warn ("Packet[DD]: Neighbor %s state is %s, packet discarded.",
1273		 inet_ntoa(nbr->router_id),
1274		 LOOKUP (ospf_nsm_state_msg, nbr->state));
1275      break;
1276    case NSM_Init:
1277      OSPF_NSM_EVENT_EXECUTE (nbr, NSM_TwoWayReceived);
1278      /* If the new state is ExStart, the processing of the current
1279	 packet should then continue in this new state by falling
1280	 through to case ExStart below.  */
1281      if (nbr->state != NSM_ExStart)
1282	break;
1283    case NSM_ExStart:
1284      /* Initial DBD */
1285      if ((IS_SET_DD_ALL (dd->flags) == OSPF_DD_FLAG_ALL) &&
1286	  (size == OSPF_DB_DESC_MIN_SIZE))
1287	{
1288	  if (IPV4_ADDR_CMP (&nbr->router_id, &oi->ospf->router_id) > 0)
1289	    {
1290	      /* We're Slave---obey */
1291	      zlog_info ("Packet[DD]: Neighbor %s Negotiation done (Slave).",
1292	      		 inet_ntoa(nbr->router_id));
1293	      nbr->dd_seqnum = ntohl (dd->dd_seqnum);
1294
1295	      /* Reset I/MS */
1296	      UNSET_FLAG (nbr->dd_flags, (OSPF_DD_FLAG_MS|OSPF_DD_FLAG_I));
1297	    }
1298	  else
1299	    {
1300	      /* We're Master, ignore the initial DBD from Slave */
1301	      zlog_info ("Packet[DD]: Neighbor %s: Initial DBD from Slave, "
1302	      		 "ignoring.", inet_ntoa(nbr->router_id));
1303	      break;
1304	    }
1305	}
1306      /* Ack from the Slave */
1307      else if (!IS_SET_DD_MS (dd->flags) && !IS_SET_DD_I (dd->flags) &&
1308	       ntohl (dd->dd_seqnum) == nbr->dd_seqnum &&
1309	       IPV4_ADDR_CMP (&nbr->router_id, &oi->ospf->router_id) < 0)
1310	{
1311	  zlog_info ("Packet[DD]: Neighbor %s Negotiation done (Master).",
1312		     inet_ntoa(nbr->router_id));
1313          /* Reset I, leaving MS */
1314          UNSET_FLAG (nbr->dd_flags, OSPF_DD_FLAG_I);
1315	}
1316      else
1317	{
1318	  zlog_warn ("Packet[DD]: Neighbor %s Negotiation fails.",
1319		     inet_ntoa(nbr->router_id));
1320	  break;
1321	}
1322
1323      /* This is where the real Options are saved */
1324      nbr->options = dd->options;
1325
1326#ifdef HAVE_OPAQUE_LSA
1327      if (CHECK_FLAG (oi->ospf->config, OSPF_OPAQUE_CAPABLE))
1328        {
1329          if (IS_DEBUG_OSPF_EVENT)
1330            zlog_debug ("Neighbor[%s] is %sOpaque-capable.",
1331		       inet_ntoa (nbr->router_id),
1332		       CHECK_FLAG (nbr->options, OSPF_OPTION_O) ? "" : "NOT ");
1333
1334          if (! CHECK_FLAG (nbr->options, OSPF_OPTION_O)
1335          &&  IPV4_ADDR_SAME (&DR (oi), &nbr->address.u.prefix4))
1336            {
1337              zlog_warn ("DR-neighbor[%s] is NOT opaque-capable; "
1338                         "Opaque-LSAs cannot be reliably advertised "
1339                         "in this network.",
1340                         inet_ntoa (nbr->router_id));
1341              /* This situation is undesirable, but not a real error. */
1342            }
1343        }
1344#endif /* HAVE_OPAQUE_LSA */
1345
1346      OSPF_NSM_EVENT_EXECUTE (nbr, NSM_NegotiationDone);
1347
1348      /* continue processing rest of packet. */
1349      ospf_db_desc_proc (s, oi, nbr, dd, size);
1350      break;
1351    case NSM_Exchange:
1352      if (ospf_db_desc_is_dup (dd, nbr))
1353	{
1354	  if (IS_SET_DD_MS (nbr->dd_flags))
1355	    /* Master: discard duplicated DD packet. */
1356	    zlog_info ("Packet[DD] (Master): Neighbor %s packet duplicated.",
1357		       inet_ntoa (nbr->router_id));
1358	  else
1359	    /* Slave: cause to retransmit the last Database Description. */
1360	    {
1361	      zlog_info ("Packet[DD] [Slave]: Neighbor %s packet duplicated.",
1362			 inet_ntoa (nbr->router_id));
1363	      ospf_db_desc_resend (nbr);
1364	    }
1365	  break;
1366	}
1367
1368      /* Otherwise DD packet should be checked. */
1369      /* Check Master/Slave bit mismatch */
1370      if (IS_SET_DD_MS (dd->flags) != IS_SET_DD_MS (nbr->last_recv.flags))
1371	{
1372	  zlog_warn ("Packet[DD]: Neighbor %s MS-bit mismatch.",
1373		     inet_ntoa(nbr->router_id));
1374	  OSPF_NSM_EVENT_SCHEDULE (nbr, NSM_SeqNumberMismatch);
1375	  if (IS_DEBUG_OSPF_EVENT)
1376	    zlog_debug ("Packet[DD]: dd->flags=%d, nbr->dd_flags=%d",
1377		        dd->flags, nbr->dd_flags);
1378	  break;
1379	}
1380
1381      /* Check initialize bit is set. */
1382      if (IS_SET_DD_I (dd->flags))
1383	{
1384	  zlog_info ("Packet[DD]: Neighbor %s I-bit set.",
1385		     inet_ntoa(nbr->router_id));
1386	  OSPF_NSM_EVENT_SCHEDULE (nbr, NSM_SeqNumberMismatch);
1387	  break;
1388	}
1389
1390      /* Check DD Options. */
1391      if (dd->options != nbr->options)
1392	{
1393#ifdef ORIGINAL_CODING
1394	  /* Save the new options for debugging */
1395	  nbr->options = dd->options;
1396#endif /* ORIGINAL_CODING */
1397	  zlog_warn ("Packet[DD]: Neighbor %s options mismatch.",
1398		     inet_ntoa(nbr->router_id));
1399	  OSPF_NSM_EVENT_SCHEDULE (nbr, NSM_SeqNumberMismatch);
1400	  break;
1401	}
1402
1403      /* Check DD sequence number. */
1404      if ((IS_SET_DD_MS (nbr->dd_flags) &&
1405	   ntohl (dd->dd_seqnum) != nbr->dd_seqnum) ||
1406	  (!IS_SET_DD_MS (nbr->dd_flags) &&
1407	   ntohl (dd->dd_seqnum) != nbr->dd_seqnum + 1))
1408	{
1409	  zlog_warn ("Packet[DD]: Neighbor %s sequence number mismatch.",
1410		     inet_ntoa(nbr->router_id));
1411	  OSPF_NSM_EVENT_SCHEDULE (nbr, NSM_SeqNumberMismatch);
1412	  break;
1413	}
1414
1415      /* Continue processing rest of packet. */
1416      ospf_db_desc_proc (s, oi, nbr, dd, size);
1417      break;
1418    case NSM_Loading:
1419    case NSM_Full:
1420      if (ospf_db_desc_is_dup (dd, nbr))
1421	{
1422	  if (IS_SET_DD_MS (nbr->dd_flags))
1423	    {
1424	      /* Master should discard duplicate DD packet. */
1425	      zlog_info ("Packet[DD]: Neighbor %s duplicated, "
1426	                 "packet discarded.",
1427			inet_ntoa(nbr->router_id));
1428	      break;
1429	    }
1430	  else
1431	    {
1432	      struct timeval t, now;
1433	      quagga_gettime (QUAGGA_CLK_MONOTONIC, &now);
1434	      t = tv_sub (now, nbr->last_send_ts);
1435	      if (tv_cmp (t, int2tv (nbr->v_inactivity)) < 0)
1436		{
1437		  /* In states Loading and Full the slave must resend
1438		     its last Database Description packet in response to
1439		     duplicate Database Description packets received
1440		     from the master.  For this reason the slave must
1441		     wait RouterDeadInterval seconds before freeing the
1442		     last Database Description packet.  Reception of a
1443		     Database Description packet from the master after
1444		     this interval will generate a SeqNumberMismatch
1445		     neighbor event. RFC2328 Section 10.8 */
1446		  ospf_db_desc_resend (nbr);
1447		  break;
1448		}
1449	    }
1450	}
1451
1452      OSPF_NSM_EVENT_SCHEDULE (nbr, NSM_SeqNumberMismatch);
1453      break;
1454    default:
1455      zlog_warn ("Packet[DD]: Neighbor %s NSM illegal status %u.",
1456		 inet_ntoa(nbr->router_id), nbr->state);
1457      break;
1458    }
1459}
1460
1461#define OSPF_LSA_KEY_SIZE       12 /* type(4) + id(4) + ar(4) */
1462
1463/* OSPF Link State Request Read -- RFC2328 Section 10.7. */
1464static void
1465ospf_ls_req (struct ip *iph, struct ospf_header *ospfh,
1466	     struct stream *s, struct ospf_interface *oi, u_int16_t size)
1467{
1468  struct ospf_neighbor *nbr;
1469  u_int32_t ls_type;
1470  struct in_addr ls_id;
1471  struct in_addr adv_router;
1472  struct ospf_lsa *find;
1473  struct list *ls_upd;
1474  unsigned int length;
1475
1476  /* Increment statistics. */
1477  oi->ls_req_in++;
1478
1479  nbr = ospf_nbr_lookup (oi, iph, ospfh);
1480  if (nbr == NULL)
1481    {
1482      zlog_warn ("Link State Request: Unknown Neighbor %s.",
1483		 inet_ntoa (ospfh->router_id));
1484      return;
1485    }
1486
1487  /* Add event to thread. */
1488  OSPF_NSM_EVENT_SCHEDULE (nbr, NSM_PacketReceived);
1489
1490  /* Neighbor State should be Exchange or later. */
1491  if (nbr->state != NSM_Exchange &&
1492      nbr->state != NSM_Loading &&
1493      nbr->state != NSM_Full)
1494    {
1495      zlog_warn ("Link State Request received from %s: "
1496      		 "Neighbor state is %s, packet discarded.",
1497		 inet_ntoa (ospfh->router_id),
1498		 LOOKUP (ospf_nsm_state_msg, nbr->state));
1499      return;
1500    }
1501
1502  /* Send Link State Update for ALL requested LSAs. */
1503  ls_upd = list_new ();
1504  length = OSPF_HEADER_SIZE + OSPF_LS_UPD_MIN_SIZE;
1505
1506  while (size >= OSPF_LSA_KEY_SIZE)
1507    {
1508      /* Get one slice of Link State Request. */
1509      ls_type = stream_getl (s);
1510      ls_id.s_addr = stream_get_ipv4 (s);
1511      adv_router.s_addr = stream_get_ipv4 (s);
1512
1513      /* Verify LSA type. */
1514      if (ls_type < OSPF_MIN_LSA || ls_type >= OSPF_MAX_LSA)
1515	{
1516	  OSPF_NSM_EVENT_SCHEDULE (nbr, NSM_BadLSReq);
1517	  list_delete (ls_upd);
1518	  return;
1519	}
1520
1521      /* Search proper LSA in LSDB. */
1522      find = ospf_lsa_lookup (oi->area, ls_type, ls_id, adv_router);
1523      if (find == NULL)
1524	{
1525	  OSPF_NSM_EVENT_SCHEDULE (nbr, NSM_BadLSReq);
1526	  list_delete (ls_upd);
1527	  return;
1528	}
1529
1530      /* Packet overflows MTU size, send immediately. */
1531      if (length + ntohs (find->data->length) > ospf_packet_max (oi))
1532	{
1533	  if (oi->type == OSPF_IFTYPE_NBMA)
1534	    ospf_ls_upd_send (nbr, ls_upd, OSPF_SEND_PACKET_DIRECT);
1535	  else
1536	    ospf_ls_upd_send (nbr, ls_upd, OSPF_SEND_PACKET_INDIRECT);
1537
1538	  /* Only remove list contents.  Keep ls_upd. */
1539	  list_delete_all_node (ls_upd);
1540
1541	  length = OSPF_HEADER_SIZE + OSPF_LS_UPD_MIN_SIZE;
1542	}
1543
1544      /* Append LSA to update list. */
1545      listnode_add (ls_upd, find);
1546      length += ntohs (find->data->length);
1547
1548      size -= OSPF_LSA_KEY_SIZE;
1549    }
1550
1551  /* Send rest of Link State Update. */
1552  if (listcount (ls_upd) > 0)
1553    {
1554      if (oi->type == OSPF_IFTYPE_NBMA)
1555	ospf_ls_upd_send (nbr, ls_upd, OSPF_SEND_PACKET_DIRECT);
1556      else
1557	ospf_ls_upd_send (nbr, ls_upd, OSPF_SEND_PACKET_INDIRECT);
1558
1559      list_delete (ls_upd);
1560    }
1561  else
1562    list_free (ls_upd);
1563}
1564
1565/* Get the list of LSAs from Link State Update packet.
1566   And process some validation -- RFC2328 Section 13. (1)-(2). */
1567static struct list *
1568ospf_ls_upd_list_lsa (struct ospf_neighbor *nbr, struct stream *s,
1569                      struct ospf_interface *oi, size_t size)
1570{
1571  u_int16_t count, sum;
1572  u_int32_t length;
1573  struct lsa_header *lsah;
1574  struct ospf_lsa *lsa;
1575  struct list *lsas;
1576
1577  lsas = list_new ();
1578
1579  count = stream_getl (s);
1580  size -= OSPF_LS_UPD_MIN_SIZE; /* # LSAs */
1581
1582  for (; size >= OSPF_LSA_HEADER_SIZE && count > 0;
1583       size -= length, stream_forward_getp (s, length), count--)
1584    {
1585      lsah = (struct lsa_header *) STREAM_PNT (s);
1586      length = ntohs (lsah->length);
1587
1588      if (length > size)
1589	{
1590	  zlog_warn ("Link State Update: LSA length exceeds packet size.");
1591	  break;
1592	}
1593
1594      /* Validate the LSA's LS checksum. */
1595      sum = lsah->checksum;
1596      if (! ospf_lsa_checksum_valid (lsah))
1597	{
1598	  /* (bug #685) more details in a one-line message make it possible
1599	   * to identify problem source on the one hand and to have a better
1600	   * chance to compress repeated messages in syslog on the other */
1601	  zlog_warn ("Link State Update: LSA checksum error %x/%x, ID=%s from: nbr %s, router ID %s, adv router %s",
1602		     sum, lsah->checksum, inet_ntoa (lsah->id),
1603		     inet_ntoa (nbr->src), inet_ntoa (nbr->router_id),
1604		     inet_ntoa (lsah->adv_router));
1605	  continue;
1606	}
1607
1608      /* Examine the LSA's LS type. */
1609      if (lsah->type < OSPF_MIN_LSA || lsah->type >= OSPF_MAX_LSA)
1610	{
1611	  zlog_warn ("Link State Update: Unknown LS type %d", lsah->type);
1612	  continue;
1613	}
1614
1615      /*
1616       * What if the received LSA's age is greater than MaxAge?
1617       * Treat it as a MaxAge case -- endo.
1618       */
1619      if (ntohs (lsah->ls_age) > OSPF_LSA_MAXAGE)
1620        lsah->ls_age = htons (OSPF_LSA_MAXAGE);
1621
1622#ifdef HAVE_OPAQUE_LSA
1623      if (CHECK_FLAG (nbr->options, OSPF_OPTION_O))
1624        {
1625#ifdef STRICT_OBIT_USAGE_CHECK
1626	  if ((IS_OPAQUE_LSA(lsah->type) &&
1627               ! CHECK_FLAG (lsah->options, OSPF_OPTION_O))
1628	  ||  (! IS_OPAQUE_LSA(lsah->type) &&
1629               CHECK_FLAG (lsah->options, OSPF_OPTION_O)))
1630            {
1631              /*
1632               * This neighbor must know the exact usage of O-bit;
1633               * the bit will be set in Type-9,10,11 LSAs only.
1634               */
1635              zlog_warn ("LSA[Type%d:%s]: O-bit abuse?", lsah->type, inet_ntoa (lsah->id));
1636              continue;
1637            }
1638#endif /* STRICT_OBIT_USAGE_CHECK */
1639
1640          /* Do not take in AS External Opaque-LSAs if we are a stub. */
1641          if (lsah->type == OSPF_OPAQUE_AS_LSA
1642	      && nbr->oi->area->external_routing != OSPF_AREA_DEFAULT)
1643            {
1644              if (IS_DEBUG_OSPF_EVENT)
1645                zlog_debug ("LSA[Type%d:%s]: We are a stub, don't take this LSA.", lsah->type, inet_ntoa (lsah->id));
1646              continue;
1647            }
1648        }
1649      else if (IS_OPAQUE_LSA(lsah->type))
1650        {
1651          zlog_warn ("LSA[Type%d:%s]: Opaque capability mismatch?", lsah->type, inet_ntoa (lsah->id));
1652          continue;
1653        }
1654#endif /* HAVE_OPAQUE_LSA */
1655
1656      /* Create OSPF LSA instance. */
1657      lsa = ospf_lsa_new ();
1658
1659      /* We may wish to put some error checking if type NSSA comes in
1660         and area not in NSSA mode */
1661      switch (lsah->type)
1662        {
1663        case OSPF_AS_EXTERNAL_LSA:
1664#ifdef HAVE_OPAQUE_LSA
1665        case OSPF_OPAQUE_AS_LSA:
1666#endif /* HAVE_OPAQUE_LSA */
1667          lsa->area = NULL;
1668          break;
1669#ifdef HAVE_OPAQUE_LSA
1670        case OSPF_OPAQUE_LINK_LSA:
1671          lsa->oi = oi; /* Remember incoming interface for flooding control. */
1672          /* Fallthrough */
1673#endif /* HAVE_OPAQUE_LSA */
1674        default:
1675          lsa->area = oi->area;
1676          break;
1677        }
1678
1679      lsa->data = ospf_lsa_data_new (length);
1680      memcpy (lsa->data, lsah, length);
1681
1682      if (IS_DEBUG_OSPF_EVENT)
1683	zlog_debug("LSA[Type%d:%s]: %p new LSA created with Link State Update",
1684		  lsa->data->type, inet_ntoa (lsa->data->id), lsa);
1685      listnode_add (lsas, lsa);
1686    }
1687
1688  return lsas;
1689}
1690
1691/* Cleanup Update list. */
1692static void
1693ospf_upd_list_clean (struct list *lsas)
1694{
1695  struct listnode *node, *nnode;
1696  struct ospf_lsa *lsa;
1697
1698  for (ALL_LIST_ELEMENTS (lsas, node, nnode, lsa))
1699    ospf_lsa_discard (lsa);
1700
1701  list_delete (lsas);
1702}
1703
1704/* OSPF Link State Update message read -- RFC2328 Section 13. */
1705static void
1706ospf_ls_upd (struct ip *iph, struct ospf_header *ospfh,
1707	     struct stream *s, struct ospf_interface *oi, u_int16_t size)
1708{
1709  struct ospf_neighbor *nbr;
1710  struct list *lsas;
1711  struct listnode *node, *nnode;
1712  struct ospf_lsa *lsa = NULL;
1713  /* unsigned long ls_req_found = 0; */
1714
1715  /* Dis-assemble the stream, update each entry, re-encapsulate for flooding */
1716
1717  /* Increment statistics. */
1718  oi->ls_upd_in++;
1719
1720  /* Check neighbor. */
1721  nbr = ospf_nbr_lookup (oi, iph, ospfh);
1722  if (nbr == NULL)
1723    {
1724      zlog_warn ("Link State Update: Unknown Neighbor %s on int: %s",
1725		 inet_ntoa (ospfh->router_id), IF_NAME (oi));
1726      return;
1727    }
1728
1729  /* Add event to thread. */
1730  OSPF_NSM_EVENT_SCHEDULE (nbr, NSM_PacketReceived);
1731
1732  /* Check neighbor state. */
1733  if (nbr->state < NSM_Exchange)
1734    {
1735      zlog_warn ("Link State Update: "
1736      		 "Neighbor[%s] state %s is less than Exchange",
1737		 inet_ntoa (ospfh->router_id),
1738		 LOOKUP(ospf_nsm_state_msg, nbr->state));
1739      return;
1740    }
1741
1742  /* Get list of LSAs from Link State Update packet. - Also perorms Stages
1743   * 1 (validate LSA checksum) and 2 (check for LSA consistent type)
1744   * of section 13.
1745   */
1746  lsas = ospf_ls_upd_list_lsa (nbr, s, oi, size);
1747
1748#ifdef HAVE_OPAQUE_LSA
1749  /*
1750   * If self-originated Opaque-LSAs that have flooded before restart
1751   * are contained in the received LSUpd message, corresponding LSReq
1752   * messages to be sent may have to be modified.
1753   * To eliminate possible race conditions such that flushing and normal
1754   * updating for the same LSA would take place alternately, this trick
1755   * must be done before entering to the loop below.
1756   */
1757   /* XXX: Why is this Opaque specific? Either our core code is deficient
1758    * and this should be fixed generally, or Opaque is inventing strawman
1759    * problems */
1760   ospf_opaque_adjust_lsreq (nbr, lsas);
1761#endif /* HAVE_OPAQUE_LSA */
1762
1763#define DISCARD_LSA(L,N) {\
1764        if (IS_DEBUG_OSPF_EVENT) \
1765          zlog_debug ("ospf_lsa_discard() in ospf_ls_upd() point %d: lsa %p Type-%d", N, lsa, (int) lsa->data->type); \
1766        ospf_lsa_discard (L); \
1767	continue; }
1768
1769  /* Process each LSA received in the one packet.
1770   *
1771   * Numbers in parentheses, e.g. (1), (2), etc., and the corresponding
1772   * text below are from the steps in RFC 2328, Section 13.
1773   */
1774  for (ALL_LIST_ELEMENTS (lsas, node, nnode, lsa))
1775    {
1776      struct ospf_lsa *ls_ret, *current;
1777      int ret = 1;
1778
1779      if (IS_DEBUG_OSPF_NSSA)
1780	{
1781	  char buf1[INET_ADDRSTRLEN];
1782	  char buf2[INET_ADDRSTRLEN];
1783	  char buf3[INET_ADDRSTRLEN];
1784
1785	  zlog_debug("LSA Type-%d from %s, ID: %s, ADV: %s",
1786		  lsa->data->type,
1787		  inet_ntop (AF_INET, &ospfh->router_id,
1788			     buf1, INET_ADDRSTRLEN),
1789		  inet_ntop (AF_INET, &lsa->data->id,
1790			     buf2, INET_ADDRSTRLEN),
1791		  inet_ntop (AF_INET, &lsa->data->adv_router,
1792			     buf3, INET_ADDRSTRLEN));
1793	}
1794
1795      listnode_delete (lsas, lsa); /* We don't need it in list anymore */
1796
1797      /* (1) Validate Checksum - Done above by ospf_ls_upd_list_lsa() */
1798
1799      /* (2) LSA Type  - Done above by ospf_ls_upd_list_lsa() */
1800
1801      /* (3) Do not take in AS External LSAs if we are a stub or NSSA. */
1802
1803      /* Do not take in AS NSSA if this neighbor and we are not NSSA */
1804
1805      /* Do take in Type-7's if we are an NSSA  */
1806
1807      /* If we are also an ABR, later translate them to a Type-5 packet */
1808
1809      /* Later, an NSSA Re-fresh can Re-fresh Type-7's and an ABR will
1810	 translate them to a separate Type-5 packet.  */
1811
1812      if (lsa->data->type == OSPF_AS_EXTERNAL_LSA)
1813        /* Reject from STUB or NSSA */
1814        if (nbr->oi->area->external_routing != OSPF_AREA_DEFAULT)
1815	  {
1816	    if (IS_DEBUG_OSPF_NSSA)
1817	      zlog_debug("Incoming External LSA Discarded: We are NSSA/STUB Area");
1818	    DISCARD_LSA (lsa, 1);
1819	  }
1820
1821      if (lsa->data->type == OSPF_AS_NSSA_LSA)
1822	if (nbr->oi->area->external_routing != OSPF_AREA_NSSA)
1823	  {
1824	    if (IS_DEBUG_OSPF_NSSA)
1825	      zlog_debug("Incoming NSSA LSA Discarded:  Not NSSA Area");
1826	    DISCARD_LSA (lsa,2);
1827	  }
1828
1829      /* VU229804: Router-LSA Adv-ID must be equal to LS-ID */
1830      if (lsa->data->type == OSPF_ROUTER_LSA)
1831	if (!IPV4_ADDR_SAME(&lsa->data->id, &lsa->data->adv_router))
1832	  {
1833	    char buf1[INET_ADDRSTRLEN];
1834	    char buf2[INET_ADDRSTRLEN];
1835	    char buf3[INET_ADDRSTRLEN];
1836
1837	    zlog_err("Incoming Router-LSA from %s with "
1838		      "Adv-ID[%s] != LS-ID[%s]",
1839		      inet_ntop (AF_INET, &ospfh->router_id,
1840				 buf1, INET_ADDRSTRLEN),
1841		      inet_ntop (AF_INET, &lsa->data->id,
1842				 buf2, INET_ADDRSTRLEN),
1843		      inet_ntop (AF_INET, &lsa->data->adv_router,
1844				 buf3, INET_ADDRSTRLEN));
1845	    zlog_err("OSPF domain compromised by attack or corruption. "
1846		     "Verify correct operation of -ALL- OSPF routers.");
1847	    DISCARD_LSA (lsa, 0);
1848	  }
1849
1850      /* Find the LSA in the current database. */
1851
1852      current = ospf_lsa_lookup_by_header (oi->area, lsa->data);
1853
1854      /* (4) If the LSA's LS age is equal to MaxAge, and there is currently
1855	 no instance of the LSA in the router's link state database,
1856	 and none of router's neighbors are in states Exchange or Loading,
1857	 then take the following actions: */
1858
1859      if (IS_LSA_MAXAGE (lsa) && !current &&
1860	  ospf_check_nbr_status(oi->ospf))
1861	{
1862	  /* (4a) Response Link State Acknowledgment. */
1863	  ospf_ls_ack_send (nbr, lsa);
1864
1865	  /* (4b) Discard LSA. */
1866          if (IS_DEBUG_OSPF (lsa, LSA))
1867            {
1868	       zlog_debug ("Link State Update[%s]: LS age is equal to MaxAge.",
1869                           dump_lsa_key(lsa));
1870            }
1871          DISCARD_LSA (lsa, 3);
1872	}
1873
1874#ifdef HAVE_OPAQUE_LSA
1875      if (IS_OPAQUE_LSA (lsa->data->type)
1876      &&  IPV4_ADDR_SAME (&lsa->data->adv_router, &oi->ospf->router_id))
1877        {
1878          /*
1879           * Even if initial flushing seems to be completed, there might
1880           * be a case that self-originated LSA with MaxAge still remain
1881           * in the routing domain.
1882           * Just send an LSAck message to cease retransmission.
1883           */
1884          if (IS_LSA_MAXAGE (lsa))
1885            {
1886              zlog_warn ("LSA[%s]: Boomerang effect?", dump_lsa_key (lsa));
1887              ospf_ls_ack_send (nbr, lsa);
1888              ospf_lsa_discard (lsa);
1889
1890              if (current != NULL && ! IS_LSA_MAXAGE (current))
1891                ospf_opaque_lsa_refresh_schedule (current);
1892              continue;
1893            }
1894
1895          /*
1896           * If an instance of self-originated Opaque-LSA is not found
1897           * in the LSDB, there are some possible cases here.
1898           *
1899           * 1) This node lost opaque-capability after restart.
1900           * 2) Else, a part of opaque-type is no more supported.
1901           * 3) Else, a part of opaque-id is no more supported.
1902           *
1903           * Anyway, it is still this node's responsibility to flush it.
1904           * Otherwise, the LSA instance remains in the routing domain
1905           * until its age reaches to MaxAge.
1906           */
1907          /* XXX: We should deal with this for *ALL* LSAs, not just opaque */
1908          if (current == NULL)
1909            {
1910              if (IS_DEBUG_OSPF_EVENT)
1911                zlog_debug ("LSA[%s]: Previously originated Opaque-LSA,"
1912                            "not found in the LSDB.", dump_lsa_key (lsa));
1913
1914              SET_FLAG (lsa->flags, OSPF_LSA_SELF);
1915
1916              ospf_opaque_self_originated_lsa_received (nbr, lsa);
1917              ospf_ls_ack_send (nbr, lsa);
1918
1919              continue;
1920            }
1921        }
1922#endif /* HAVE_OPAQUE_LSA */
1923
1924      /* It might be happen that received LSA is self-originated network LSA, but
1925       * router ID is changed. So, we should check if LSA is a network-LSA whose
1926       * Link State ID is one of the router's own IP interface addresses but whose
1927       * Advertising Router is not equal to the router's own Router ID
1928       * According to RFC 2328 12.4.2 and 13.4 this LSA should be flushed.
1929       */
1930
1931      if(lsa->data->type == OSPF_NETWORK_LSA)
1932      {
1933        struct listnode *oinode, *oinnode;
1934        struct ospf_interface *out_if;
1935        int Flag = 0;
1936
1937        for (ALL_LIST_ELEMENTS (oi->ospf->oiflist, oinode, oinnode, out_if))
1938        {
1939          if(out_if == NULL)
1940            break;
1941
1942          if((IPV4_ADDR_SAME(&out_if->address->u.prefix4, &lsa->data->id)) &&
1943              (!(IPV4_ADDR_SAME(&oi->ospf->router_id, &lsa->data->adv_router))))
1944          {
1945            if(out_if->network_lsa_self)
1946            {
1947              ospf_lsa_flush_area(lsa,out_if->area);
1948              if(IS_DEBUG_OSPF_EVENT)
1949                zlog_debug ("ospf_lsa_discard() in ospf_ls_upd() point 9: lsa %p Type-%d",
1950                            lsa, (int) lsa->data->type);
1951              ospf_lsa_discard (lsa);
1952              Flag = 1;
1953            }
1954            break;
1955          }
1956        }
1957        if(Flag)
1958          continue;
1959      }
1960
1961      /* (5) Find the instance of this LSA that is currently contained
1962	 in the router's link state database.  If there is no
1963	 database copy, or the received LSA is more recent than
1964	 the database copy the following steps must be performed.
1965         (The sub steps from RFC 2328 section 13 step (5) will be performed in
1966         ospf_flood() ) */
1967
1968      if (current == NULL ||
1969	  (ret = ospf_lsa_more_recent (current, lsa)) < 0)
1970	{
1971	  /* Actual flooding procedure. */
1972	  if (ospf_flood (oi->ospf, nbr, current, lsa) < 0)  /* Trap NSSA later. */
1973	    DISCARD_LSA (lsa, 4);
1974	  continue;
1975	}
1976
1977      /* (6) Else, If there is an instance of the LSA on the sending
1978	 neighbor's Link state request list, an error has occurred in
1979	 the Database Exchange process.  In this case, restart the
1980	 Database Exchange process by generating the neighbor event
1981	 BadLSReq for the sending neighbor and stop processing the
1982	 Link State Update packet. */
1983
1984      if (ospf_ls_request_lookup (nbr, lsa))
1985	{
1986	  OSPF_NSM_EVENT_SCHEDULE (nbr, NSM_BadLSReq);
1987	  zlog_warn("LSA[%s] instance exists on Link state request list",
1988	  	    dump_lsa_key(lsa));
1989
1990	  /* Clean list of LSAs. */
1991          ospf_upd_list_clean (lsas);
1992	  /* this lsa is not on lsas list already. */
1993	  ospf_lsa_discard (lsa);
1994	  return;
1995	}
1996
1997      /* If the received LSA is the same instance as the database copy
1998	 (i.e., neither one is more recent) the following two steps
1999	 should be performed: */
2000
2001      if (ret == 0)
2002	{
2003	  /* If the LSA is listed in the Link state retransmission list
2004	     for the receiving adjacency, the router itself is expecting
2005	     an acknowledgment for this LSA.  The router should treat the
2006	     received LSA as an acknowledgment by removing the LSA from
2007	     the Link state retransmission list.  This is termed an
2008	     "implied acknowledgment". */
2009
2010	  ls_ret = ospf_ls_retransmit_lookup (nbr, lsa);
2011
2012	  if (ls_ret != NULL)
2013	    {
2014	      ospf_ls_retransmit_delete (nbr, ls_ret);
2015
2016	      /* Delayed acknowledgment sent if advertisement received
2017		 from Designated Router, otherwise do nothing. */
2018	      if (oi->state == ISM_Backup)
2019		if (NBR_IS_DR (nbr))
2020		  listnode_add (oi->ls_ack, ospf_lsa_lock (lsa));
2021
2022              DISCARD_LSA (lsa, 5);
2023	    }
2024	  else
2025	    /* Acknowledge the receipt of the LSA by sending a
2026	       Link State Acknowledgment packet back out the receiving
2027	       interface. */
2028	    {
2029	      ospf_ls_ack_send (nbr, lsa);
2030	      DISCARD_LSA (lsa, 6);
2031	    }
2032	}
2033
2034      /* The database copy is more recent.  If the database copy
2035	 has LS age equal to MaxAge and LS sequence number equal to
2036	 MaxSequenceNumber, simply discard the received LSA without
2037	 acknowledging it. (In this case, the LSA's LS sequence number is
2038	 wrapping, and the MaxSequenceNumber LSA must be completely
2039	 flushed before any new LSA instance can be introduced). */
2040
2041      else if (ret > 0)  /* Database copy is more recent */
2042	{
2043	  if (IS_LSA_MAXAGE (current) &&
2044	      current->data->ls_seqnum == htonl (OSPF_MAX_SEQUENCE_NUMBER))
2045	    {
2046	      DISCARD_LSA (lsa, 7);
2047	    }
2048	  /* Otherwise, as long as the database copy has not been sent in a
2049	     Link State Update within the last MinLSArrival seconds, send the
2050	     database copy back to the sending neighbor, encapsulated within
2051	     a Link State Update Packet. The Link State Update Packet should
2052	     be sent directly to the neighbor. In so doing, do not put the
2053	     database copy of the LSA on the neighbor's link state
2054	     retransmission list, and do not acknowledge the received (less
2055	     recent) LSA instance. */
2056	  else
2057	    {
2058	      struct timeval now;
2059
2060	      quagga_gettime (QUAGGA_CLK_MONOTONIC, &now);
2061
2062	      if (tv_cmp (tv_sub (now, current->tv_orig),
2063			  int2tv (OSPF_MIN_LS_ARRIVAL)) >= 0)
2064		/* Trap NSSA type later.*/
2065		ospf_ls_upd_send_lsa (nbr, current, OSPF_SEND_PACKET_DIRECT);
2066	      DISCARD_LSA (lsa, 8);
2067	    }
2068	}
2069    }
2070#undef DISCARD_LSA
2071
2072  assert (listcount (lsas) == 0);
2073  list_delete (lsas);
2074}
2075
2076/* OSPF Link State Acknowledgment message read -- RFC2328 Section 13.7. */
2077static void
2078ospf_ls_ack (struct ip *iph, struct ospf_header *ospfh,
2079	     struct stream *s, struct ospf_interface *oi, u_int16_t size)
2080{
2081  struct ospf_neighbor *nbr;
2082
2083  /* increment statistics. */
2084  oi->ls_ack_in++;
2085
2086  nbr = ospf_nbr_lookup (oi, iph, ospfh);
2087  if (nbr == NULL)
2088    {
2089      zlog_warn ("Link State Acknowledgment: Unknown Neighbor %s.",
2090		 inet_ntoa (ospfh->router_id));
2091      return;
2092    }
2093
2094  /* Add event to thread. */
2095  OSPF_NSM_EVENT_SCHEDULE (nbr, NSM_PacketReceived);
2096
2097  if (nbr->state < NSM_Exchange)
2098    {
2099      zlog_warn ("Link State Acknowledgment: "
2100      		 "Neighbor[%s] state %s is less than Exchange",
2101		 inet_ntoa (ospfh->router_id),
2102		 LOOKUP(ospf_nsm_state_msg, nbr->state));
2103      return;
2104    }
2105
2106  while (size >= OSPF_LSA_HEADER_SIZE)
2107    {
2108      struct ospf_lsa *lsa, *lsr;
2109
2110      lsa = ospf_lsa_new ();
2111      lsa->data = (struct lsa_header *) STREAM_PNT (s);
2112
2113      /* lsah = (struct lsa_header *) STREAM_PNT (s); */
2114      size -= OSPF_LSA_HEADER_SIZE;
2115      stream_forward_getp (s, OSPF_LSA_HEADER_SIZE);
2116
2117      if (lsa->data->type < OSPF_MIN_LSA || lsa->data->type >= OSPF_MAX_LSA)
2118	{
2119	  lsa->data = NULL;
2120	  ospf_lsa_discard (lsa);
2121	  continue;
2122	}
2123
2124      lsr = ospf_ls_retransmit_lookup (nbr, lsa);
2125
2126      if (lsr != NULL && ospf_lsa_more_recent (lsr, lsa) == 0)
2127        {
2128#ifdef HAVE_OPAQUE_LSA
2129          if (IS_OPAQUE_LSA (lsr->data->type))
2130            ospf_opaque_ls_ack_received (nbr, lsr);
2131#endif /* HAVE_OPAQUE_LSA */
2132
2133          ospf_ls_retransmit_delete (nbr, lsr);
2134        }
2135
2136      lsa->data = NULL;
2137      ospf_lsa_discard (lsa);
2138    }
2139
2140  return;
2141}
2142
2143static struct stream *
2144ospf_recv_packet (int fd, struct interface **ifp, struct stream *ibuf)
2145{
2146  int ret;
2147  struct ip *iph;
2148  u_int16_t ip_len;
2149  unsigned int ifindex = 0;
2150  struct iovec iov;
2151  /* Header and data both require alignment. */
2152  char buff [CMSG_SPACE(SOPT_SIZE_CMSG_IFINDEX_IPV4())];
2153  struct msghdr msgh;
2154
2155  memset (&msgh, 0, sizeof (struct msghdr));
2156  msgh.msg_iov = &iov;
2157  msgh.msg_iovlen = 1;
2158  msgh.msg_control = (caddr_t) buff;
2159  msgh.msg_controllen = sizeof (buff);
2160
2161  ret = stream_recvmsg (ibuf, fd, &msgh, 0, OSPF_MAX_PACKET_SIZE+1);
2162  if (ret < 0)
2163    {
2164      zlog_warn("stream_recvmsg failed: %s", safe_strerror(errno));
2165      return NULL;
2166    }
2167  if ((unsigned int)ret < sizeof(iph)) /* ret must be > 0 now */
2168    {
2169      zlog_warn("ospf_recv_packet: discarding runt packet of length %d "
2170		"(ip header size is %u)",
2171		ret, (u_int)sizeof(iph));
2172      return NULL;
2173    }
2174
2175  /* Note that there should not be alignment problems with this assignment
2176     because this is at the beginning of the stream data buffer. */
2177  iph = (struct ip *) STREAM_DATA(ibuf);
2178  sockopt_iphdrincl_swab_systoh (iph);
2179
2180  ip_len = iph->ip_len;
2181
2182#if !defined(GNU_LINUX) && (OpenBSD < 200311) && (__FreeBSD_version < 1000000)
2183  /*
2184   * Kernel network code touches incoming IP header parameters,
2185   * before protocol specific processing.
2186   *
2187   *   1) Convert byteorder to host representation.
2188   *      --> ip_len, ip_id, ip_off
2189   *
2190   *   2) Adjust ip_len to strip IP header size!
2191   *      --> If user process receives entire IP packet via RAW
2192   *          socket, it must consider adding IP header size to
2193   *          the "ip_len" field of "ip" structure.
2194   *
2195   * For more details, see <netinet/ip_input.c>.
2196   */
2197  ip_len = ip_len + (iph->ip_hl << 2);
2198#endif
2199
2200#if defined(__DragonFly__)
2201  /*
2202   * in DragonFly's raw socket, ip_len/ip_off are read
2203   * in network byte order.
2204   * As OpenBSD < 200311 adjust ip_len to strip IP header size!
2205   */
2206  ip_len = ntohs(iph->ip_len) + (iph->ip_hl << 2);
2207#endif
2208
2209  ifindex = getsockopt_ifindex (AF_INET, &msgh);
2210
2211  *ifp = if_lookup_by_index (ifindex);
2212
2213  if (ret != ip_len)
2214    {
2215      zlog_warn ("ospf_recv_packet read length mismatch: ip_len is %d, "
2216       		 "but recvmsg returned %d", ip_len, ret);
2217      return NULL;
2218    }
2219
2220  return ibuf;
2221}
2222
2223static struct ospf_interface *
2224ospf_associate_packet_vl (struct ospf *ospf, struct interface *ifp,
2225			  struct ip *iph, struct ospf_header *ospfh)
2226{
2227  struct ospf_interface *rcv_oi;
2228  struct ospf_vl_data *vl_data;
2229  struct ospf_area *vl_area;
2230  struct listnode *node;
2231
2232  if (IN_MULTICAST (ntohl (iph->ip_dst.s_addr)) ||
2233      !OSPF_IS_AREA_BACKBONE (ospfh))
2234    return NULL;
2235
2236  /* look for local OSPF interface matching the destination
2237   * to determine Area ID. We presume therefore the destination address
2238   * is unique, or at least (for "unnumbered" links), not used in other
2239   * areas
2240   */
2241  if ((rcv_oi = ospf_if_lookup_by_local_addr (ospf, NULL,
2242                                              iph->ip_dst)) == NULL)
2243    return NULL;
2244
2245  for (ALL_LIST_ELEMENTS_RO (ospf->vlinks, node, vl_data))
2246    {
2247      vl_area = ospf_area_lookup_by_area_id (ospf, vl_data->vl_area_id);
2248      if (!vl_area)
2249	continue;
2250
2251      if (OSPF_AREA_SAME (&vl_area, &rcv_oi->area) &&
2252	  IPV4_ADDR_SAME (&vl_data->vl_peer, &ospfh->router_id))
2253	{
2254	  if (IS_DEBUG_OSPF_EVENT)
2255	    zlog_debug ("associating packet with %s",
2256		       IF_NAME (vl_data->vl_oi));
2257	  if (! CHECK_FLAG (vl_data->vl_oi->ifp->flags, IFF_UP))
2258	    {
2259	      if (IS_DEBUG_OSPF_EVENT)
2260		zlog_debug ("This VL is not up yet, sorry");
2261	      return NULL;
2262	    }
2263
2264	  return vl_data->vl_oi;
2265	}
2266    }
2267
2268  if (IS_DEBUG_OSPF_EVENT)
2269    zlog_debug ("couldn't find any VL to associate the packet with");
2270
2271  return NULL;
2272}
2273
2274static int
2275ospf_check_area_id (struct ospf_interface *oi, struct ospf_header *ospfh)
2276{
2277  /* Check match the Area ID of the receiving interface. */
2278  if (OSPF_AREA_SAME (&oi->area, &ospfh))
2279    return 1;
2280
2281  return 0;
2282}
2283
2284/* Unbound socket will accept any Raw IP packets if proto is matched.
2285   To prevent it, compare src IP address and i/f address with masking
2286   i/f network mask. */
2287static int
2288ospf_check_network_mask (struct ospf_interface *oi, struct in_addr ip_src)
2289{
2290  struct in_addr mask, me, him;
2291
2292  if (oi->type == OSPF_IFTYPE_POINTOPOINT ||
2293      oi->type == OSPF_IFTYPE_VIRTUALLINK)
2294    return 1;
2295
2296  masklen2ip (oi->address->prefixlen, &mask);
2297
2298  me.s_addr = oi->address->u.prefix4.s_addr & mask.s_addr;
2299  him.s_addr = ip_src.s_addr & mask.s_addr;
2300
2301 if (IPV4_ADDR_SAME (&me, &him))
2302   return 1;
2303
2304 return 0;
2305}
2306
2307/* Return 1, if the packet is properly authenticated and checksummed,
2308   0 otherwise. In particular, check that AuType header field is valid and
2309   matches the locally configured AuType, and that D.5 requirements are met. */
2310static int
2311ospf_check_auth (struct ospf_interface *oi, struct ospf_header *ospfh)
2312{
2313  struct crypt_key *ck;
2314  u_int16_t iface_auth_type;
2315  u_int16_t pkt_auth_type = ntohs (ospfh->auth_type);
2316
2317  switch (pkt_auth_type)
2318  {
2319  case OSPF_AUTH_NULL: /* RFC2328 D.5.1 */
2320    if (OSPF_AUTH_NULL != (iface_auth_type = ospf_auth_type (oi)))
2321    {
2322      if (IS_DEBUG_OSPF_PACKET (ospfh->type - 1, RECV))
2323        zlog_warn ("interface %s: auth-type mismatch, local %s, rcvd Null",
2324                   IF_NAME (oi), LOOKUP (ospf_auth_type_str, iface_auth_type));
2325      return 0;
2326    }
2327    if (! ospf_check_sum (ospfh))
2328    {
2329      if (IS_DEBUG_OSPF_PACKET (ospfh->type - 1, RECV))
2330        zlog_warn ("interface %s: Null auth OK, but checksum error, Router-ID %s",
2331                   IF_NAME (oi), inet_ntoa (ospfh->router_id));
2332      return 0;
2333    }
2334    return 1;
2335  case OSPF_AUTH_SIMPLE: /* RFC2328 D.5.2 */
2336    if (OSPF_AUTH_SIMPLE != (iface_auth_type = ospf_auth_type (oi)))
2337    {
2338      if (IS_DEBUG_OSPF_PACKET (ospfh->type - 1, RECV))
2339        zlog_warn ("interface %s: auth-type mismatch, local %s, rcvd Simple",
2340                   IF_NAME (oi), LOOKUP (ospf_auth_type_str, iface_auth_type));
2341      return 0;
2342    }
2343    if (memcmp (OSPF_IF_PARAM (oi, auth_simple), ospfh->u.auth_data, OSPF_AUTH_SIMPLE_SIZE))
2344    {
2345      if (IS_DEBUG_OSPF_PACKET (ospfh->type - 1, RECV))
2346        zlog_warn ("interface %s: Simple auth failed", IF_NAME (oi));
2347      return 0;
2348    }
2349    if (! ospf_check_sum (ospfh))
2350    {
2351      if (IS_DEBUG_OSPF_PACKET (ospfh->type - 1, RECV))
2352        zlog_warn ("interface %s: Simple auth OK, checksum error, Router-ID %s",
2353                   IF_NAME (oi), inet_ntoa (ospfh->router_id));
2354      return 0;
2355    }
2356    return 1;
2357  case OSPF_AUTH_CRYPTOGRAPHIC: /* RFC2328 D.5.3 */
2358    if (OSPF_AUTH_CRYPTOGRAPHIC != (iface_auth_type = ospf_auth_type (oi)))
2359    {
2360      if (IS_DEBUG_OSPF_PACKET (ospfh->type - 1, RECV))
2361        zlog_warn ("interface %s: auth-type mismatch, local %s, rcvd Cryptographic",
2362                   IF_NAME (oi), LOOKUP (ospf_auth_type_str, iface_auth_type));
2363      return 0;
2364    }
2365    if (ospfh->checksum)
2366    {
2367      if (IS_DEBUG_OSPF_PACKET (ospfh->type - 1, RECV))
2368        zlog_warn ("interface %s: OSPF header checksum is not 0", IF_NAME (oi));
2369      return 0;
2370    }
2371    /* only MD5 crypto method can pass ospf_packet_examin() */
2372    if
2373    (
2374      NULL == (ck = listgetdata (listtail(OSPF_IF_PARAM (oi,auth_crypt)))) ||
2375      ospfh->u.crypt.key_id != ck->key_id ||
2376      /* Condition above uses the last key ID on the list, which is
2377         different from what ospf_crypt_key_lookup() does. A bug? */
2378      ! ospf_check_md5_digest (oi, ospfh)
2379    )
2380    {
2381      if (IS_DEBUG_OSPF_PACKET (ospfh->type - 1, RECV))
2382        zlog_warn ("interface %s: MD5 auth failed", IF_NAME (oi));
2383      return 0;
2384    }
2385    return 1;
2386  default:
2387    if (IS_DEBUG_OSPF_PACKET (ospfh->type - 1, RECV))
2388      zlog_warn ("interface %s: invalid packet auth-type (%02x)",
2389                 IF_NAME (oi), pkt_auth_type);
2390    return 0;
2391  }
2392}
2393
2394static int
2395ospf_check_sum (struct ospf_header *ospfh)
2396{
2397  u_int32_t ret;
2398  u_int16_t sum;
2399
2400  /* clear auth_data for checksum. */
2401  memset (ospfh->u.auth_data, 0, OSPF_AUTH_SIMPLE_SIZE);
2402
2403  /* keep checksum and clear. */
2404  sum = ospfh->checksum;
2405  memset (&ospfh->checksum, 0, sizeof (u_int16_t));
2406
2407  /* calculate checksum. */
2408  ret = in_cksum (ospfh, ntohs (ospfh->length));
2409
2410  if (ret != sum)
2411    {
2412      zlog_info ("ospf_check_sum(): checksum mismatch, my %X, his %X",
2413		 ret, sum);
2414      return 0;
2415    }
2416
2417  return 1;
2418}
2419
2420/* Verify, that given link/TOS records are properly sized/aligned and match
2421   Router-LSA "# links" and "# TOS" fields as specified in RFC2328 A.4.2. */
2422static unsigned
2423ospf_router_lsa_links_examin
2424(
2425  struct router_lsa_link * link,
2426  u_int16_t linkbytes,
2427  const u_int16_t num_links
2428)
2429{
2430  unsigned counted_links = 0, thislinklen;
2431
2432  while (linkbytes)
2433  {
2434    thislinklen = OSPF_ROUTER_LSA_LINK_SIZE + 4 * link->m[0].tos_count;
2435    if (thislinklen > linkbytes)
2436    {
2437      if (IS_DEBUG_OSPF_PACKET (0, RECV))
2438        zlog_debug ("%s: length error in link block #%u", __func__, counted_links);
2439      return MSG_NG;
2440    }
2441    link = (struct router_lsa_link *)((caddr_t) link + thislinklen);
2442    linkbytes -= thislinklen;
2443    counted_links++;
2444  }
2445  if (counted_links != num_links)
2446  {
2447    if (IS_DEBUG_OSPF_PACKET (0, RECV))
2448      zlog_debug ("%s: %u link blocks declared, %u present",
2449                  __func__, num_links, counted_links);
2450    return MSG_NG;
2451  }
2452  return MSG_OK;
2453}
2454
2455/* Verify, that the given LSA is properly sized/aligned (including type-specific
2456   minimum length constraint). */
2457static unsigned
2458ospf_lsa_examin (struct lsa_header * lsah, const u_int16_t lsalen, const u_char headeronly)
2459{
2460  unsigned ret;
2461  struct router_lsa * rlsa;
2462  if
2463  (
2464    lsah->type < OSPF_MAX_LSA &&
2465    ospf_lsa_minlen[lsah->type] &&
2466    lsalen < OSPF_LSA_HEADER_SIZE + ospf_lsa_minlen[lsah->type]
2467  )
2468  {
2469    if (IS_DEBUG_OSPF_PACKET (0, RECV))
2470      zlog_debug ("%s: undersized (%u B) %s",
2471                  __func__, lsalen, LOOKUP (ospf_lsa_type_msg, lsah->type));
2472    return MSG_NG;
2473  }
2474  switch (lsah->type)
2475  {
2476  case OSPF_ROUTER_LSA:
2477    /* RFC2328 A.4.2, LSA header + 4 bytes followed by N>=1 (12+)-byte link blocks */
2478    if (headeronly)
2479    {
2480      ret = (lsalen - OSPF_LSA_HEADER_SIZE - OSPF_ROUTER_LSA_MIN_SIZE) % 4 ? MSG_NG : MSG_OK;
2481      break;
2482    }
2483    rlsa = (struct router_lsa *) lsah;
2484    ret = ospf_router_lsa_links_examin
2485    (
2486      (struct router_lsa_link *) rlsa->link,
2487      lsalen - OSPF_LSA_HEADER_SIZE - 4, /* skip: basic header, "flags", 0, "# links" */
2488      ntohs (rlsa->links) /* 16 bits */
2489    );
2490    break;
2491  case OSPF_AS_EXTERNAL_LSA:
2492    /* RFC2328 A.4.5, LSA header + 4 bytes followed by N>=1 12-bytes long blocks */
2493  case OSPF_AS_NSSA_LSA:
2494    /* RFC3101 C, idem */
2495    ret = (lsalen - OSPF_LSA_HEADER_SIZE - OSPF_AS_EXTERNAL_LSA_MIN_SIZE) % 12 ? MSG_NG : MSG_OK;
2496    break;
2497  /* Following LSA types are considered OK length-wise as soon as their minimum
2498   * length constraint is met and length of the whole LSA is a multiple of 4
2499   * (basic LSA header size is already a multiple of 4). */
2500  case OSPF_NETWORK_LSA:
2501    /* RFC2328 A.4.3, LSA header + 4 bytes followed by N>=1 router-IDs */
2502  case OSPF_SUMMARY_LSA:
2503  case OSPF_ASBR_SUMMARY_LSA:
2504    /* RFC2328 A.4.4, LSA header + 4 bytes followed by N>=1 4-bytes TOS blocks */
2505#ifdef HAVE_OPAQUE_LSA
2506  case OSPF_OPAQUE_LINK_LSA:
2507  case OSPF_OPAQUE_AREA_LSA:
2508  case OSPF_OPAQUE_AS_LSA:
2509    /* RFC5250 A.2, "some number of octets (of application-specific
2510     * data) padded to 32-bit alignment." This is considered equivalent
2511     * to 4-byte alignment of all other LSA types, see OSPF-ALIGNMENT.txt
2512     * file for the detailed analysis of this passage. */
2513#endif
2514    ret = lsalen % 4 ? MSG_NG : MSG_OK;
2515    break;
2516  default:
2517    if (IS_DEBUG_OSPF_PACKET (0, RECV))
2518      zlog_debug ("%s: unsupported LSA type 0x%02x", __func__, lsah->type);
2519    return MSG_NG;
2520  }
2521  if (ret != MSG_OK && IS_DEBUG_OSPF_PACKET (0, RECV))
2522    zlog_debug ("%s: alignment error in %s",
2523                __func__, LOOKUP (ospf_lsa_type_msg, lsah->type));
2524  return ret;
2525}
2526
2527/* Verify if the provided input buffer is a valid sequence of LSAs. This
2528   includes verification of LSA blocks length/alignment and dispatching
2529   of deeper-level checks. */
2530static unsigned
2531ospf_lsaseq_examin
2532(
2533  struct lsa_header *lsah, /* start of buffered data */
2534  size_t length,
2535  const u_char headeronly,
2536  /* When declared_num_lsas is not 0, compare it to the real number of LSAs
2537     and treat the difference as an error. */
2538  const u_int32_t declared_num_lsas
2539)
2540{
2541  u_int32_t counted_lsas = 0;
2542
2543  while (length)
2544  {
2545    u_int16_t lsalen;
2546    if (length < OSPF_LSA_HEADER_SIZE)
2547    {
2548      if (IS_DEBUG_OSPF_PACKET (0, RECV))
2549        zlog_debug ("%s: undersized (%zu B) trailing (#%u) LSA header",
2550                    __func__, length, counted_lsas);
2551      return MSG_NG;
2552    }
2553    /* save on ntohs() calls here and in the LSA validator */
2554    lsalen = ntohs (lsah->length);
2555    if (lsalen < OSPF_LSA_HEADER_SIZE)
2556    {
2557      if (IS_DEBUG_OSPF_PACKET (0, RECV))
2558        zlog_debug ("%s: malformed LSA header #%u, declared length is %u B",
2559                    __func__, counted_lsas, lsalen);
2560      return MSG_NG;
2561    }
2562    if (headeronly)
2563    {
2564      /* less checks here and in ospf_lsa_examin() */
2565      if (MSG_OK != ospf_lsa_examin (lsah, lsalen, 1))
2566      {
2567        if (IS_DEBUG_OSPF_PACKET (0, RECV))
2568          zlog_debug ("%s: malformed header-only LSA #%u", __func__, counted_lsas);
2569        return MSG_NG;
2570      }
2571      lsah = (struct lsa_header *) ((caddr_t) lsah + OSPF_LSA_HEADER_SIZE);
2572      length -= OSPF_LSA_HEADER_SIZE;
2573    }
2574    else
2575    {
2576      /* make sure the input buffer is deep enough before further checks */
2577      if (lsalen > length)
2578      {
2579        if (IS_DEBUG_OSPF_PACKET (0, RECV))
2580          zlog_debug ("%s: anomaly in LSA #%u: declared length is %u B, buffered length is %zu B",
2581                      __func__, counted_lsas, lsalen, length);
2582        return MSG_NG;
2583      }
2584      if (MSG_OK != ospf_lsa_examin (lsah, lsalen, 0))
2585      {
2586        if (IS_DEBUG_OSPF_PACKET (0, RECV))
2587          zlog_debug ("%s: malformed LSA #%u", __func__, counted_lsas);
2588        return MSG_NG;
2589      }
2590      lsah = (struct lsa_header *) ((caddr_t) lsah + lsalen);
2591      length -= lsalen;
2592    }
2593    counted_lsas++;
2594  }
2595
2596  if (declared_num_lsas && counted_lsas != declared_num_lsas)
2597  {
2598    if (IS_DEBUG_OSPF_PACKET (0, RECV))
2599      zlog_debug ("%s: #LSAs declared (%u) does not match actual (%u)",
2600                  __func__, declared_num_lsas, counted_lsas);
2601    return MSG_NG;
2602  }
2603  return MSG_OK;
2604}
2605
2606/* Verify a complete OSPF packet for proper sizing/alignment. */
2607static unsigned
2608ospf_packet_examin (struct ospf_header * oh, const unsigned bytesonwire)
2609{
2610  u_int16_t bytesdeclared, bytesauth;
2611  unsigned ret;
2612  struct ospf_ls_update * lsupd;
2613
2614  /* Length, 1st approximation. */
2615  if (bytesonwire < OSPF_HEADER_SIZE)
2616  {
2617    if (IS_DEBUG_OSPF_PACKET (0, RECV))
2618      zlog_debug ("%s: undersized (%u B) packet", __func__, bytesonwire);
2619    return MSG_NG;
2620  }
2621  /* Now it is safe to access header fields. Performing length check, allow
2622   * for possible extra bytes of crypto auth/padding, which are not counted
2623   * in the OSPF header "length" field. */
2624  if (oh->version != OSPF_VERSION)
2625  {
2626    if (IS_DEBUG_OSPF_PACKET (0, RECV))
2627      zlog_debug ("%s: invalid (%u) protocol version", __func__, oh->version);
2628    return MSG_NG;
2629  }
2630  bytesdeclared = ntohs (oh->length);
2631  if (ntohs (oh->auth_type) != OSPF_AUTH_CRYPTOGRAPHIC)
2632    bytesauth = 0;
2633  else
2634  {
2635    if (oh->u.crypt.auth_data_len != OSPF_AUTH_MD5_SIZE)
2636    {
2637      if (IS_DEBUG_OSPF_PACKET (0, RECV))
2638        zlog_debug ("%s: unsupported crypto auth length (%u B)",
2639                    __func__, oh->u.crypt.auth_data_len);
2640      return MSG_NG;
2641    }
2642    bytesauth = OSPF_AUTH_MD5_SIZE;
2643  }
2644  if (bytesdeclared + bytesauth > bytesonwire)
2645  {
2646    if (IS_DEBUG_OSPF_PACKET (0, RECV))
2647      zlog_debug ("%s: packet length error (%u real, %u+%u declared)",
2648                  __func__, bytesonwire, bytesdeclared, bytesauth);
2649    return MSG_NG;
2650  }
2651  /* Length, 2nd approximation. The type-specific constraint is checked
2652     against declared length, not amount of bytes on wire. */
2653  if
2654  (
2655    oh->type >= OSPF_MSG_HELLO &&
2656    oh->type <= OSPF_MSG_LS_ACK &&
2657    bytesdeclared < OSPF_HEADER_SIZE + ospf_packet_minlen[oh->type]
2658  )
2659  {
2660    if (IS_DEBUG_OSPF_PACKET (0, RECV))
2661      zlog_debug ("%s: undersized (%u B) %s packet", __func__,
2662                  bytesdeclared, LOOKUP (ospf_packet_type_str, oh->type));
2663    return MSG_NG;
2664  }
2665  switch (oh->type)
2666  {
2667  case OSPF_MSG_HELLO:
2668    /* RFC2328 A.3.2, packet header + OSPF_HELLO_MIN_SIZE bytes followed
2669       by N>=0 router-IDs. */
2670    ret = (bytesdeclared - OSPF_HEADER_SIZE - OSPF_HELLO_MIN_SIZE) % 4 ? MSG_NG : MSG_OK;
2671    break;
2672  case OSPF_MSG_DB_DESC:
2673    /* RFC2328 A.3.3, packet header + OSPF_DB_DESC_MIN_SIZE bytes followed
2674       by N>=0 header-only LSAs. */
2675    ret = ospf_lsaseq_examin
2676    (
2677      (struct lsa_header *) ((caddr_t) oh + OSPF_HEADER_SIZE + OSPF_DB_DESC_MIN_SIZE),
2678      bytesdeclared - OSPF_HEADER_SIZE - OSPF_DB_DESC_MIN_SIZE,
2679      1, /* header-only LSAs */
2680      0
2681    );
2682    break;
2683  case OSPF_MSG_LS_REQ:
2684    /* RFC2328 A.3.4, packet header followed by N>=0 12-bytes request blocks. */
2685    ret = (bytesdeclared - OSPF_HEADER_SIZE - OSPF_LS_REQ_MIN_SIZE) %
2686      OSPF_LSA_KEY_SIZE ? MSG_NG : MSG_OK;
2687    break;
2688  case OSPF_MSG_LS_UPD:
2689    /* RFC2328 A.3.5, packet header + OSPF_LS_UPD_MIN_SIZE bytes followed
2690       by N>=0 full LSAs (with N declared beforehand). */
2691    lsupd = (struct ospf_ls_update *) ((caddr_t) oh + OSPF_HEADER_SIZE);
2692    ret = ospf_lsaseq_examin
2693    (
2694      (struct lsa_header *) ((caddr_t) lsupd + OSPF_LS_UPD_MIN_SIZE),
2695      bytesdeclared - OSPF_HEADER_SIZE - OSPF_LS_UPD_MIN_SIZE,
2696      0, /* full LSAs */
2697      ntohl (lsupd->num_lsas) /* 32 bits */
2698    );
2699    break;
2700  case OSPF_MSG_LS_ACK:
2701    /* RFC2328 A.3.6, packet header followed by N>=0 header-only LSAs. */
2702    ret = ospf_lsaseq_examin
2703    (
2704      (struct lsa_header *) ((caddr_t) oh + OSPF_HEADER_SIZE + OSPF_LS_ACK_MIN_SIZE),
2705      bytesdeclared - OSPF_HEADER_SIZE - OSPF_LS_ACK_MIN_SIZE,
2706      1, /* header-only LSAs */
2707      0
2708    );
2709    break;
2710  default:
2711    if (IS_DEBUG_OSPF_PACKET (0, RECV))
2712      zlog_debug ("%s: invalid packet type 0x%02x", __func__, oh->type);
2713    return MSG_NG;
2714  }
2715  if (ret != MSG_OK && IS_DEBUG_OSPF_PACKET (0, RECV))
2716    zlog_debug ("%s: malformed %s packet", __func__, LOOKUP (ospf_packet_type_str, oh->type));
2717  return ret;
2718}
2719
2720/* OSPF Header verification. */
2721static int
2722ospf_verify_header (struct stream *ibuf, struct ospf_interface *oi,
2723		    struct ip *iph, struct ospf_header *ospfh)
2724{
2725  /* Check Area ID. */
2726  if (!ospf_check_area_id (oi, ospfh))
2727    {
2728      zlog_warn ("interface %s: ospf_read invalid Area ID %s.",
2729		 IF_NAME (oi), inet_ntoa (ospfh->area_id));
2730      return -1;
2731    }
2732
2733  /* Check network mask, Silently discarded. */
2734  if (! ospf_check_network_mask (oi, iph->ip_src))
2735    {
2736      zlog_warn ("interface %s: ospf_read network address is not same [%s]",
2737		 IF_NAME (oi), inet_ntoa (iph->ip_src));
2738      return -1;
2739    }
2740
2741  /* Check authentication. The function handles logging actions, where required. */
2742  if (! ospf_check_auth (oi, ospfh))
2743    return -1;
2744
2745  return 0;
2746}
2747
2748/* Starting point of packet process function. */
2749int
2750ospf_read (struct thread *thread)
2751{
2752  int ret;
2753  struct stream *ibuf;
2754  struct ospf *ospf;
2755  struct ospf_interface *oi;
2756  struct ip *iph;
2757  struct ospf_header *ospfh;
2758  u_int16_t length;
2759  struct interface *ifp;
2760
2761  /* first of all get interface pointer. */
2762  ospf = THREAD_ARG (thread);
2763
2764  /* prepare for next packet. */
2765  ospf->t_read = thread_add_read (master, ospf_read, ospf, ospf->fd);
2766
2767  stream_reset(ospf->ibuf);
2768  if (!(ibuf = ospf_recv_packet (ospf->fd, &ifp, ospf->ibuf)))
2769    return -1;
2770  /* This raw packet is known to be at least as big as its IP header. */
2771
2772  /* Note that there should not be alignment problems with this assignment
2773     because this is at the beginning of the stream data buffer. */
2774  iph = (struct ip *) STREAM_DATA (ibuf);
2775  /* Note that sockopt_iphdrincl_swab_systoh was called in ospf_recv_packet. */
2776
2777  if (ifp == NULL)
2778    /* Handle cases where the platform does not support retrieving the ifindex,
2779       and also platforms (such as Solaris 8) that claim to support ifindex
2780       retrieval but do not. */
2781    ifp = if_lookup_address (iph->ip_src);
2782
2783  if (ifp == NULL)
2784    return 0;
2785
2786  /* IP Header dump. */
2787    if (IS_DEBUG_OSPF_PACKET(0, RECV))
2788	    ospf_ip_header_dump (iph);
2789
2790  /* Self-originated packet should be discarded silently. */
2791  if (ospf_if_lookup_by_local_addr (ospf, NULL, iph->ip_src))
2792    {
2793      if (IS_DEBUG_OSPF_PACKET (0, RECV))
2794        {
2795          zlog_debug ("ospf_read[%s]: Dropping self-originated packet",
2796                     inet_ntoa (iph->ip_src));
2797        }
2798      return 0;
2799    }
2800
2801  /* Advance from IP header to OSPF header (iph->ip_hl has been verified
2802     by ospf_recv_packet() to be correct). */
2803  stream_forward_getp (ibuf, iph->ip_hl * 4);
2804
2805  ospfh = (struct ospf_header *) STREAM_PNT (ibuf);
2806  if (MSG_OK != ospf_packet_examin (ospfh, stream_get_endp (ibuf) - stream_get_getp (ibuf)))
2807    return -1;
2808  /* Now it is safe to access all fields of OSPF packet header. */
2809
2810  /* associate packet with ospf interface */
2811  oi = ospf_if_lookup_recv_if (ospf, iph->ip_src, ifp);
2812
2813  /* ospf_verify_header() relies on a valid "oi" and thus can be called only
2814     after the passive/backbone/other checks below are passed. These checks
2815     in turn access the fields of unverified "ospfh" structure for their own
2816     purposes and must remain very accurate in doing this. */
2817
2818  /* If incoming interface is passive one, ignore it. */
2819  if (oi && OSPF_IF_PASSIVE_STATUS (oi) == OSPF_IF_PASSIVE)
2820    {
2821      char buf[3][INET_ADDRSTRLEN];
2822
2823      if (IS_DEBUG_OSPF_EVENT)
2824	zlog_debug ("ignoring packet from router %s sent to %s, "
2825		    "received on a passive interface, %s",
2826		    inet_ntop(AF_INET, &ospfh->router_id, buf[0], sizeof(buf[0])),
2827		    inet_ntop(AF_INET, &iph->ip_dst, buf[1], sizeof(buf[1])),
2828		    inet_ntop(AF_INET, &oi->address->u.prefix4,
2829			      buf[2], sizeof(buf[2])));
2830
2831      if (iph->ip_dst.s_addr == htonl(OSPF_ALLSPFROUTERS))
2832	{
2833	  /* Try to fix multicast membership.
2834	   * Some OS:es may have problems in this area,
2835	   * make sure it is removed.
2836	   */
2837	  OI_MEMBER_JOINED(oi, MEMBER_ALLROUTERS);
2838	  ospf_if_set_multicast(oi);
2839	}
2840      return 0;
2841  }
2842
2843
2844  /* if no local ospf_interface,
2845   * or header area is backbone but ospf_interface is not
2846   * check for VLINK interface
2847   */
2848  if ( (oi == NULL) ||
2849      (OSPF_IS_AREA_ID_BACKBONE(ospfh->area_id)
2850      && !OSPF_IS_AREA_ID_BACKBONE(oi->area->area_id))
2851     )
2852    {
2853      if ((oi = ospf_associate_packet_vl (ospf, ifp, iph, ospfh)) == NULL)
2854        {
2855          if (IS_DEBUG_OSPF_EVENT)
2856            zlog_debug ("Packet from [%s] received on link %s"
2857                        " but no ospf_interface",
2858                        inet_ntoa (iph->ip_src), ifp->name);
2859          return 0;
2860        }
2861    }
2862
2863  /* else it must be a local ospf interface, check it was received on
2864   * correct link
2865   */
2866  else if (oi->ifp != ifp)
2867    {
2868      if (IS_DEBUG_OSPF_EVENT)
2869        zlog_warn ("Packet from [%s] received on wrong link %s",
2870                   inet_ntoa (iph->ip_src), ifp->name);
2871      return 0;
2872    }
2873  else if (oi->state == ISM_Down)
2874    {
2875      char buf[2][INET_ADDRSTRLEN];
2876      zlog_warn ("Ignoring packet from %s to %s received on interface that is "
2877      		 "down [%s]; interface flags are %s",
2878		 inet_ntop(AF_INET, &iph->ip_src, buf[0], sizeof(buf[0])),
2879		 inet_ntop(AF_INET, &iph->ip_dst, buf[1], sizeof(buf[1])),
2880	         ifp->name, if_flag_dump(ifp->flags));
2881      /* Fix multicast memberships? */
2882      if (iph->ip_dst.s_addr == htonl(OSPF_ALLSPFROUTERS))
2883        OI_MEMBER_JOINED(oi, MEMBER_ALLROUTERS);
2884      else if (iph->ip_dst.s_addr == htonl(OSPF_ALLDROUTERS))
2885	OI_MEMBER_JOINED(oi, MEMBER_DROUTERS);
2886      if (oi->multicast_memberships)
2887	ospf_if_set_multicast(oi);
2888      return 0;
2889    }
2890
2891  /*
2892   * If the received packet is destined for AllDRouters, the packet
2893   * should be accepted only if the received ospf interface state is
2894   * either DR or Backup -- endo.
2895   */
2896  if (iph->ip_dst.s_addr == htonl (OSPF_ALLDROUTERS)
2897  && (oi->state != ISM_DR && oi->state != ISM_Backup))
2898    {
2899      zlog_warn ("Dropping packet for AllDRouters from [%s] via [%s] (ISM: %s)",
2900                 inet_ntoa (iph->ip_src), IF_NAME (oi),
2901                 LOOKUP (ospf_ism_state_msg, oi->state));
2902      /* Try to fix multicast membership. */
2903      SET_FLAG(oi->multicast_memberships, MEMBER_DROUTERS);
2904      ospf_if_set_multicast(oi);
2905      return 0;
2906    }
2907
2908  /* Verify more OSPF header fields. */
2909  ret = ospf_verify_header (ibuf, oi, iph, ospfh);
2910  if (ret < 0)
2911  {
2912    if (IS_DEBUG_OSPF_PACKET (0, RECV))
2913      zlog_debug ("ospf_read[%s]: Header check failed, "
2914                  "dropping.",
2915                  inet_ntoa (iph->ip_src));
2916    return ret;
2917  }
2918
2919  /* Show debug receiving packet. */
2920  if (IS_DEBUG_OSPF_PACKET (ospfh->type - 1, RECV))
2921    {
2922      if (IS_DEBUG_OSPF_PACKET (ospfh->type - 1, DETAIL))
2923        {
2924          zlog_debug ("-----------------------------------------------------");
2925          ospf_packet_dump (ibuf);
2926        }
2927
2928      zlog_debug ("%s received from [%s] via [%s]",
2929                 LOOKUP (ospf_packet_type_str, ospfh->type),
2930                 inet_ntoa (ospfh->router_id), IF_NAME (oi));
2931      zlog_debug (" src [%s],", inet_ntoa (iph->ip_src));
2932      zlog_debug (" dst [%s]", inet_ntoa (iph->ip_dst));
2933
2934      if (IS_DEBUG_OSPF_PACKET (ospfh->type - 1, DETAIL))
2935	zlog_debug ("-----------------------------------------------------");
2936  }
2937
2938  stream_forward_getp (ibuf, OSPF_HEADER_SIZE);
2939
2940  /* Adjust size to message length. */
2941  length = ntohs (ospfh->length) - OSPF_HEADER_SIZE;
2942
2943  /* Read rest of the packet and call each sort of packet routine. */
2944  switch (ospfh->type)
2945    {
2946    case OSPF_MSG_HELLO:
2947      ospf_hello (iph, ospfh, ibuf, oi, length);
2948      break;
2949    case OSPF_MSG_DB_DESC:
2950      ospf_db_desc (iph, ospfh, ibuf, oi, length);
2951      break;
2952    case OSPF_MSG_LS_REQ:
2953      ospf_ls_req (iph, ospfh, ibuf, oi, length);
2954      break;
2955    case OSPF_MSG_LS_UPD:
2956      ospf_ls_upd (iph, ospfh, ibuf, oi, length);
2957      break;
2958    case OSPF_MSG_LS_ACK:
2959      ospf_ls_ack (iph, ospfh, ibuf, oi, length);
2960      break;
2961    default:
2962      zlog (NULL, LOG_WARNING,
2963	    "interface %s: OSPF packet header type %d is illegal",
2964	    IF_NAME (oi), ospfh->type);
2965      break;
2966    }
2967
2968  return 0;
2969}
2970
2971/* Make OSPF header. */
2972static void
2973ospf_make_header (int type, struct ospf_interface *oi, struct stream *s)
2974{
2975  struct ospf_header *ospfh;
2976
2977  ospfh = (struct ospf_header *) STREAM_DATA (s);
2978
2979  ospfh->version = (u_char) OSPF_VERSION;
2980  ospfh->type = (u_char) type;
2981
2982  ospfh->router_id = oi->ospf->router_id;
2983
2984  ospfh->checksum = 0;
2985  ospfh->area_id = oi->area->area_id;
2986  ospfh->auth_type = htons (ospf_auth_type (oi));
2987
2988  memset (ospfh->u.auth_data, 0, OSPF_AUTH_SIMPLE_SIZE);
2989
2990  stream_forward_endp (s, OSPF_HEADER_SIZE);
2991}
2992
2993/* Make Authentication Data. */
2994static int
2995ospf_make_auth (struct ospf_interface *oi, struct ospf_header *ospfh)
2996{
2997  struct crypt_key *ck;
2998
2999  switch (ospf_auth_type (oi))
3000    {
3001    case OSPF_AUTH_NULL:
3002      /* memset (ospfh->u.auth_data, 0, sizeof (ospfh->u.auth_data)); */
3003      break;
3004    case OSPF_AUTH_SIMPLE:
3005      memcpy (ospfh->u.auth_data, OSPF_IF_PARAM (oi, auth_simple),
3006	      OSPF_AUTH_SIMPLE_SIZE);
3007      break;
3008    case OSPF_AUTH_CRYPTOGRAPHIC:
3009      /* If key is not set, then set 0. */
3010      if (list_isempty (OSPF_IF_PARAM (oi, auth_crypt)))
3011	{
3012	  ospfh->u.crypt.zero = 0;
3013	  ospfh->u.crypt.key_id = 0;
3014	  ospfh->u.crypt.auth_data_len = OSPF_AUTH_MD5_SIZE;
3015	}
3016      else
3017	{
3018	  ck = listgetdata (listtail(OSPF_IF_PARAM (oi, auth_crypt)));
3019	  ospfh->u.crypt.zero = 0;
3020	  ospfh->u.crypt.key_id = ck->key_id;
3021	  ospfh->u.crypt.auth_data_len = OSPF_AUTH_MD5_SIZE;
3022	}
3023      /* note: the seq is done in ospf_make_md5_digest() */
3024      break;
3025    default:
3026      /* memset (ospfh->u.auth_data, 0, sizeof (ospfh->u.auth_data)); */
3027      break;
3028    }
3029
3030  return 0;
3031}
3032
3033/* Fill rest of OSPF header. */
3034static void
3035ospf_fill_header (struct ospf_interface *oi,
3036		  struct stream *s, u_int16_t length)
3037{
3038  struct ospf_header *ospfh;
3039
3040  ospfh = (struct ospf_header *) STREAM_DATA (s);
3041
3042  /* Fill length. */
3043  ospfh->length = htons (length);
3044
3045  /* Calculate checksum. */
3046  if (ntohs (ospfh->auth_type) != OSPF_AUTH_CRYPTOGRAPHIC)
3047    ospfh->checksum = in_cksum (ospfh, length);
3048  else
3049    ospfh->checksum = 0;
3050
3051  /* Add Authentication Data. */
3052  ospf_make_auth (oi, ospfh);
3053}
3054
3055static int
3056ospf_make_hello (struct ospf_interface *oi, struct stream *s)
3057{
3058  struct ospf_neighbor *nbr;
3059  struct route_node *rn;
3060  u_int16_t length = OSPF_HELLO_MIN_SIZE;
3061  struct in_addr mask;
3062  unsigned long p;
3063  int flag = 0;
3064
3065  /* Set netmask of interface. */
3066  if (oi->type != OSPF_IFTYPE_POINTOPOINT &&
3067      oi->type != OSPF_IFTYPE_VIRTUALLINK)
3068    masklen2ip (oi->address->prefixlen, &mask);
3069  else
3070    memset ((char *) &mask, 0, sizeof (struct in_addr));
3071  stream_put_ipv4 (s, mask.s_addr);
3072
3073  /* Set Hello Interval. */
3074  if (OSPF_IF_PARAM (oi, fast_hello) == 0)
3075    stream_putw (s, OSPF_IF_PARAM (oi, v_hello));
3076  else
3077    stream_putw (s, 0); /* hello-interval of 0 for fast-hellos */
3078
3079  if (IS_DEBUG_OSPF_EVENT)
3080    zlog_debug ("make_hello: options: %x, int: %s",
3081	       OPTIONS(oi), IF_NAME (oi));
3082
3083  /* Set Options. */
3084  stream_putc (s, OPTIONS (oi));
3085
3086  /* Set Router Priority. */
3087  stream_putc (s, PRIORITY (oi));
3088
3089  /* Set Router Dead Interval. */
3090  stream_putl (s, OSPF_IF_PARAM (oi, v_wait));
3091
3092  /* Set Designated Router. */
3093  stream_put_ipv4 (s, DR (oi).s_addr);
3094
3095  p = stream_get_endp (s);
3096
3097  /* Set Backup Designated Router. */
3098  stream_put_ipv4 (s, BDR (oi).s_addr);
3099
3100  /* Add neighbor seen. */
3101  for (rn = route_top (oi->nbrs); rn; rn = route_next (rn))
3102    if ((nbr = rn->info))
3103      if (nbr->router_id.s_addr != 0)	/* Ignore 0.0.0.0 node. */
3104	if (nbr->state != NSM_Attempt)  /* Ignore Down neighbor. */
3105	if (nbr->state != NSM_Down)     /* This is myself for DR election. */
3106	  if (!IPV4_ADDR_SAME (&nbr->router_id, &oi->ospf->router_id))
3107	    {
3108	      /* Check neighbor is sane? */
3109	      if (nbr->d_router.s_addr != 0
3110		  && IPV4_ADDR_SAME (&nbr->d_router, &oi->address->u.prefix4)
3111		  && IPV4_ADDR_SAME (&nbr->bd_router, &oi->address->u.prefix4))
3112		flag = 1;
3113
3114	      stream_put_ipv4 (s, nbr->router_id.s_addr);
3115	      length += 4;
3116	    }
3117
3118  /* Let neighbor generate BackupSeen. */
3119  if (flag == 1)
3120    stream_putl_at (s, p, 0); /* ipv4 address, normally */
3121
3122  return length;
3123}
3124
3125static int
3126ospf_make_db_desc (struct ospf_interface *oi, struct ospf_neighbor *nbr,
3127		   struct stream *s)
3128{
3129  struct ospf_lsa *lsa;
3130  u_int16_t length = OSPF_DB_DESC_MIN_SIZE;
3131  u_char options;
3132  unsigned long pp;
3133  int i;
3134  struct ospf_lsdb *lsdb;
3135
3136  /* Set Interface MTU. */
3137  if (oi->type == OSPF_IFTYPE_VIRTUALLINK)
3138    stream_putw (s, 0);
3139  else
3140    stream_putw (s, oi->ifp->mtu);
3141
3142  /* Set Options. */
3143  options = OPTIONS (oi);
3144#ifdef HAVE_OPAQUE_LSA
3145  if (CHECK_FLAG (oi->ospf->config, OSPF_OPAQUE_CAPABLE))
3146    SET_FLAG (options, OSPF_OPTION_O);
3147#endif /* HAVE_OPAQUE_LSA */
3148  stream_putc (s, options);
3149
3150  /* DD flags */
3151  pp = stream_get_endp (s);
3152  stream_putc (s, nbr->dd_flags);
3153
3154  /* Set DD Sequence Number. */
3155  stream_putl (s, nbr->dd_seqnum);
3156
3157  /* shortcut unneeded walk of (empty) summary LSDBs */
3158  if (ospf_db_summary_isempty (nbr))
3159    goto empty;
3160
3161  /* Describe LSA Header from Database Summary List. */
3162  lsdb = &nbr->db_sum;
3163
3164  for (i = OSPF_MIN_LSA; i < OSPF_MAX_LSA; i++)
3165    {
3166      struct route_table *table = lsdb->type[i].db;
3167      struct route_node *rn;
3168
3169      for (rn = route_top (table); rn; rn = route_next (rn))
3170	if ((lsa = rn->info) != NULL)
3171	  {
3172#ifdef HAVE_OPAQUE_LSA
3173            if (IS_OPAQUE_LSA (lsa->data->type)
3174            && (! CHECK_FLAG (options, OSPF_OPTION_O)))
3175              {
3176                /* Suppress advertising opaque-informations. */
3177                /* Remove LSA from DB summary list. */
3178                ospf_lsdb_delete (lsdb, lsa);
3179                continue;
3180              }
3181#endif /* HAVE_OPAQUE_LSA */
3182
3183	    if (!CHECK_FLAG (lsa->flags, OSPF_LSA_DISCARD))
3184	      {
3185		struct lsa_header *lsah;
3186		u_int16_t ls_age;
3187
3188		/* DD packet overflows interface MTU. */
3189		if (length + OSPF_LSA_HEADER_SIZE > ospf_packet_max (oi))
3190		  break;
3191
3192		/* Keep pointer to LS age. */
3193		lsah = (struct lsa_header *) (STREAM_DATA (s) +
3194					      stream_get_endp (s));
3195
3196		/* Proceed stream pointer. */
3197		stream_put (s, lsa->data, OSPF_LSA_HEADER_SIZE);
3198		length += OSPF_LSA_HEADER_SIZE;
3199
3200		/* Set LS age. */
3201		ls_age = LS_AGE (lsa);
3202		lsah->ls_age = htons (ls_age);
3203
3204	      }
3205
3206	    /* Remove LSA from DB summary list. */
3207	    ospf_lsdb_delete (lsdb, lsa);
3208	  }
3209    }
3210
3211  /* Update 'More' bit */
3212  if (ospf_db_summary_isempty (nbr))
3213    {
3214empty:
3215      if (nbr->state >= NSM_Exchange)
3216        {
3217          UNSET_FLAG (nbr->dd_flags, OSPF_DD_FLAG_M);
3218          /* Rewrite DD flags */
3219          stream_putc_at (s, pp, nbr->dd_flags);
3220        }
3221      else
3222        {
3223          assert (IS_SET_DD_M(nbr->dd_flags));
3224        }
3225    }
3226  return length;
3227}
3228
3229static int
3230ospf_make_ls_req_func (struct stream *s, u_int16_t *length,
3231		       unsigned long delta, struct ospf_neighbor *nbr,
3232		       struct ospf_lsa *lsa)
3233{
3234  struct ospf_interface *oi;
3235
3236  oi = nbr->oi;
3237
3238  /* LS Request packet overflows interface MTU. */
3239  if (*length + delta > ospf_packet_max(oi))
3240    return 0;
3241
3242  stream_putl (s, lsa->data->type);
3243  stream_put_ipv4 (s, lsa->data->id.s_addr);
3244  stream_put_ipv4 (s, lsa->data->adv_router.s_addr);
3245
3246  ospf_lsa_unlock (&nbr->ls_req_last);
3247  nbr->ls_req_last = ospf_lsa_lock (lsa);
3248
3249  *length += 12;
3250  return 1;
3251}
3252
3253static int
3254ospf_make_ls_req (struct ospf_neighbor *nbr, struct stream *s)
3255{
3256  struct ospf_lsa *lsa;
3257  u_int16_t length = OSPF_LS_REQ_MIN_SIZE;
3258  unsigned long delta = stream_get_endp(s)+12;
3259  struct route_table *table;
3260  struct route_node *rn;
3261  int i;
3262  struct ospf_lsdb *lsdb;
3263
3264  lsdb = &nbr->ls_req;
3265
3266  for (i = OSPF_MIN_LSA; i < OSPF_MAX_LSA; i++)
3267    {
3268      table = lsdb->type[i].db;
3269      for (rn = route_top (table); rn; rn = route_next (rn))
3270	if ((lsa = (rn->info)) != NULL)
3271	  if (ospf_make_ls_req_func (s, &length, delta, nbr, lsa) == 0)
3272	    {
3273	      route_unlock_node (rn);
3274	      break;
3275	    }
3276    }
3277  return length;
3278}
3279
3280static int
3281ls_age_increment (struct ospf_lsa *lsa, int delay)
3282{
3283  int age;
3284
3285  age = IS_LSA_MAXAGE (lsa) ? OSPF_LSA_MAXAGE : LS_AGE (lsa) + delay;
3286
3287  return (age > OSPF_LSA_MAXAGE ? OSPF_LSA_MAXAGE : age);
3288}
3289
3290static int
3291ospf_make_ls_upd (struct ospf_interface *oi, struct list *update, struct stream *s)
3292{
3293  struct ospf_lsa *lsa;
3294  struct listnode *node;
3295  u_int16_t length = 0;
3296  unsigned int size_noauth;
3297  unsigned long delta = stream_get_endp (s);
3298  unsigned long pp;
3299  int count = 0;
3300
3301  if (IS_DEBUG_OSPF_EVENT)
3302    zlog_debug ("ospf_make_ls_upd: Start");
3303
3304  pp = stream_get_endp (s);
3305  stream_forward_endp (s, OSPF_LS_UPD_MIN_SIZE);
3306  length += OSPF_LS_UPD_MIN_SIZE;
3307
3308  /* Calculate amount of packet usable for data. */
3309  size_noauth = stream_get_size(s) - ospf_packet_authspace(oi);
3310
3311  while ((node = listhead (update)) != NULL)
3312    {
3313      struct lsa_header *lsah;
3314      u_int16_t ls_age;
3315
3316      if (IS_DEBUG_OSPF_EVENT)
3317        zlog_debug ("ospf_make_ls_upd: List Iteration %d", count);
3318
3319      lsa = listgetdata (node);
3320
3321      assert (lsa->data);
3322
3323      /* Will it fit? */
3324      if (length + delta + ntohs (lsa->data->length) > size_noauth)
3325        break;
3326
3327      /* Keep pointer to LS age. */
3328      lsah = (struct lsa_header *) (STREAM_DATA (s) + stream_get_endp (s));
3329
3330      /* Put LSA to Link State Request. */
3331      stream_put (s, lsa->data, ntohs (lsa->data->length));
3332
3333      /* Set LS age. */
3334      /* each hop must increment an lsa_age by transmit_delay
3335         of OSPF interface */
3336      ls_age = ls_age_increment (lsa, OSPF_IF_PARAM (oi, transmit_delay));
3337      lsah->ls_age = htons (ls_age);
3338
3339      length += ntohs (lsa->data->length);
3340      count++;
3341
3342      list_delete_node (update, node);
3343      ospf_lsa_unlock (&lsa); /* oi->ls_upd_queue */
3344    }
3345
3346  /* Now set #LSAs. */
3347  stream_putl_at (s, pp, count);
3348
3349  if (IS_DEBUG_OSPF_EVENT)
3350    zlog_debug ("ospf_make_ls_upd: Stop");
3351  return length;
3352}
3353
3354static int
3355ospf_make_ls_ack (struct ospf_interface *oi, struct list *ack, struct stream *s)
3356{
3357  struct listnode *node, *nnode;
3358  u_int16_t length = OSPF_LS_ACK_MIN_SIZE;
3359  unsigned long delta = stream_get_endp(s) + 24;
3360  struct ospf_lsa *lsa;
3361
3362  for (ALL_LIST_ELEMENTS (ack, node, nnode, lsa))
3363    {
3364      assert (lsa);
3365
3366      if (length + delta > ospf_packet_max (oi))
3367	break;
3368
3369      stream_put (s, lsa->data, OSPF_LSA_HEADER_SIZE);
3370      length += OSPF_LSA_HEADER_SIZE;
3371
3372      listnode_delete (ack, lsa);
3373      ospf_lsa_unlock (&lsa); /* oi->ls_ack_direct.ls_ack */
3374    }
3375
3376  return length;
3377}
3378
3379static void
3380ospf_hello_send_sub (struct ospf_interface *oi, in_addr_t addr)
3381{
3382  struct ospf_packet *op;
3383  u_int16_t length = OSPF_HEADER_SIZE;
3384
3385  op = ospf_packet_new (oi->ifp->mtu);
3386
3387  /* Prepare OSPF common header. */
3388  ospf_make_header (OSPF_MSG_HELLO, oi, op->s);
3389
3390  /* Prepare OSPF Hello body. */
3391  length += ospf_make_hello (oi, op->s);
3392
3393  /* Fill OSPF header. */
3394  ospf_fill_header (oi, op->s, length);
3395
3396  /* Set packet length. */
3397  op->length = length;
3398
3399  op->dst.s_addr = addr;
3400
3401  /* Add packet to the top of the interface output queue, so that they
3402   * can't get delayed by things like long queues of LS Update packets
3403   */
3404  ospf_packet_add_top (oi, op);
3405
3406  /* Hook thread to write packet. */
3407  OSPF_ISM_WRITE_ON (oi->ospf);
3408}
3409
3410static void
3411ospf_poll_send (struct ospf_nbr_nbma *nbr_nbma)
3412{
3413  struct ospf_interface *oi;
3414
3415  oi = nbr_nbma->oi;
3416  assert(oi);
3417
3418  /* If this is passive interface, do not send OSPF Hello. */
3419  if (OSPF_IF_PASSIVE_STATUS (oi) == OSPF_IF_PASSIVE)
3420    return;
3421
3422  if (oi->type != OSPF_IFTYPE_NBMA)
3423    return;
3424
3425  if (nbr_nbma->nbr != NULL && nbr_nbma->nbr->state != NSM_Down)
3426    return;
3427
3428  if (PRIORITY(oi) == 0)
3429    return;
3430
3431  if (nbr_nbma->priority == 0
3432      && oi->state != ISM_DR && oi->state != ISM_Backup)
3433    return;
3434
3435  ospf_hello_send_sub (oi, nbr_nbma->addr.s_addr);
3436}
3437
3438int
3439ospf_poll_timer (struct thread *thread)
3440{
3441  struct ospf_nbr_nbma *nbr_nbma;
3442
3443  nbr_nbma = THREAD_ARG (thread);
3444  nbr_nbma->t_poll = NULL;
3445
3446  if (IS_DEBUG_OSPF (nsm, NSM_TIMERS))
3447    zlog (NULL, LOG_DEBUG, "NSM[%s:%s]: Timer (Poll timer expire)",
3448    IF_NAME (nbr_nbma->oi), inet_ntoa (nbr_nbma->addr));
3449
3450  ospf_poll_send (nbr_nbma);
3451
3452  if (nbr_nbma->v_poll > 0)
3453    OSPF_POLL_TIMER_ON (nbr_nbma->t_poll, ospf_poll_timer,
3454			nbr_nbma->v_poll);
3455
3456  return 0;
3457}
3458
3459
3460int
3461ospf_hello_reply_timer (struct thread *thread)
3462{
3463  struct ospf_neighbor *nbr;
3464
3465  nbr = THREAD_ARG (thread);
3466  nbr->t_hello_reply = NULL;
3467
3468  assert (nbr->oi);
3469
3470  if (IS_DEBUG_OSPF (nsm, NSM_TIMERS))
3471    zlog (NULL, LOG_DEBUG, "NSM[%s:%s]: Timer (hello-reply timer expire)",
3472	  IF_NAME (nbr->oi), inet_ntoa (nbr->router_id));
3473
3474  ospf_hello_send_sub (nbr->oi, nbr->address.u.prefix4.s_addr);
3475
3476  return 0;
3477}
3478
3479/* Send OSPF Hello. */
3480void
3481ospf_hello_send (struct ospf_interface *oi)
3482{
3483  /* If this is passive interface, do not send OSPF Hello. */
3484  if (OSPF_IF_PASSIVE_STATUS (oi) == OSPF_IF_PASSIVE)
3485    return;
3486
3487  if (oi->type == OSPF_IFTYPE_NBMA)
3488    {
3489      struct ospf_neighbor *nbr;
3490      struct route_node *rn;
3491
3492      for (rn = route_top (oi->nbrs); rn; rn = route_next (rn))
3493	if ((nbr = rn->info))
3494	  if (nbr != oi->nbr_self)
3495	    if (nbr->state != NSM_Down)
3496	      {
3497		/*  RFC 2328  Section 9.5.1
3498		    If the router is not eligible to become Designated Router,
3499		    it must periodically send Hello Packets to both the
3500		    Designated Router and the Backup Designated Router (if they
3501		    exist).  */
3502		if (PRIORITY(oi) == 0 &&
3503		    IPV4_ADDR_CMP(&DR(oi),  &nbr->address.u.prefix4) &&
3504		    IPV4_ADDR_CMP(&BDR(oi), &nbr->address.u.prefix4))
3505		  continue;
3506
3507		/*  If the router is eligible to become Designated Router, it
3508		    must periodically send Hello Packets to all neighbors that
3509		    are also eligible. In addition, if the router is itself the
3510		    Designated Router or Backup Designated Router, it must also
3511		    send periodic Hello Packets to all other neighbors. */
3512
3513		if (nbr->priority == 0 && oi->state == ISM_DROther)
3514		  continue;
3515		/* if oi->state == Waiting, send hello to all neighbors */
3516		ospf_hello_send_sub (oi, nbr->address.u.prefix4.s_addr);
3517	      }
3518    }
3519  else
3520    {
3521      /* Decide destination address. */
3522      if (oi->type == OSPF_IFTYPE_VIRTUALLINK)
3523        ospf_hello_send_sub (oi, oi->vl_data->peer_addr.s_addr);
3524      else
3525        ospf_hello_send_sub (oi, htonl (OSPF_ALLSPFROUTERS));
3526    }
3527}
3528
3529/* Send OSPF Database Description. */
3530void
3531ospf_db_desc_send (struct ospf_neighbor *nbr)
3532{
3533  struct ospf_interface *oi;
3534  struct ospf_packet *op;
3535  u_int16_t length = OSPF_HEADER_SIZE;
3536
3537  oi = nbr->oi;
3538  op = ospf_packet_new (oi->ifp->mtu);
3539
3540  /* Prepare OSPF common header. */
3541  ospf_make_header (OSPF_MSG_DB_DESC, oi, op->s);
3542
3543  /* Prepare OSPF Database Description body. */
3544  length += ospf_make_db_desc (oi, nbr, op->s);
3545
3546  /* Fill OSPF header. */
3547  ospf_fill_header (oi, op->s, length);
3548
3549  /* Set packet length. */
3550  op->length = length;
3551
3552  /* Decide destination address. */
3553  if (oi->type == OSPF_IFTYPE_POINTOPOINT)
3554    op->dst.s_addr = htonl (OSPF_ALLSPFROUTERS);
3555  else
3556    op->dst = nbr->address.u.prefix4;
3557
3558  /* Add packet to the interface output queue. */
3559  ospf_packet_add (oi, op);
3560
3561  /* Hook thread to write packet. */
3562  OSPF_ISM_WRITE_ON (oi->ospf);
3563
3564  /* Remove old DD packet, then copy new one and keep in neighbor structure. */
3565  if (nbr->last_send)
3566    ospf_packet_free (nbr->last_send);
3567  nbr->last_send = ospf_packet_dup (op);
3568  quagga_gettime (QUAGGA_CLK_MONOTONIC, &nbr->last_send_ts);
3569}
3570
3571/* Re-send Database Description. */
3572void
3573ospf_db_desc_resend (struct ospf_neighbor *nbr)
3574{
3575  struct ospf_interface *oi;
3576
3577  oi = nbr->oi;
3578
3579  /* Add packet to the interface output queue. */
3580  ospf_packet_add (oi, ospf_packet_dup (nbr->last_send));
3581
3582  /* Hook thread to write packet. */
3583  OSPF_ISM_WRITE_ON (oi->ospf);
3584}
3585
3586/* Send Link State Request. */
3587void
3588ospf_ls_req_send (struct ospf_neighbor *nbr)
3589{
3590  struct ospf_interface *oi;
3591  struct ospf_packet *op;
3592  u_int16_t length = OSPF_HEADER_SIZE;
3593
3594  oi = nbr->oi;
3595  op = ospf_packet_new (oi->ifp->mtu);
3596
3597  /* Prepare OSPF common header. */
3598  ospf_make_header (OSPF_MSG_LS_REQ, oi, op->s);
3599
3600  /* Prepare OSPF Link State Request body. */
3601  length += ospf_make_ls_req (nbr, op->s);
3602  if (length == OSPF_HEADER_SIZE)
3603    {
3604      ospf_packet_free (op);
3605      return;
3606    }
3607
3608  /* Fill OSPF header. */
3609  ospf_fill_header (oi, op->s, length);
3610
3611  /* Set packet length. */
3612  op->length = length;
3613
3614  /* Decide destination address. */
3615  if (oi->type == OSPF_IFTYPE_POINTOPOINT)
3616    op->dst.s_addr = htonl (OSPF_ALLSPFROUTERS);
3617  else
3618    op->dst = nbr->address.u.prefix4;
3619
3620  /* Add packet to the interface output queue. */
3621  ospf_packet_add (oi, op);
3622
3623  /* Hook thread to write packet. */
3624  OSPF_ISM_WRITE_ON (oi->ospf);
3625
3626  /* Add Link State Request Retransmission Timer. */
3627  OSPF_NSM_TIMER_ON (nbr->t_ls_req, ospf_ls_req_timer, nbr->v_ls_req);
3628}
3629
3630/* Send Link State Update with an LSA. */
3631void
3632ospf_ls_upd_send_lsa (struct ospf_neighbor *nbr, struct ospf_lsa *lsa,
3633		      int flag)
3634{
3635  struct list *update;
3636
3637  update = list_new ();
3638
3639  listnode_add (update, lsa);
3640  ospf_ls_upd_send (nbr, update, flag);
3641
3642  list_delete (update);
3643}
3644
3645/* Determine size for packet. Must be at least big enough to accomodate next
3646 * LSA on list, which may be bigger than MTU size.
3647 *
3648 * Return pointer to new ospf_packet
3649 * NULL if we can not allocate, eg because LSA is bigger than imposed limit
3650 * on packet sizes (in which case offending LSA is deleted from update list)
3651 */
3652static struct ospf_packet *
3653ospf_ls_upd_packet_new (struct list *update, struct ospf_interface *oi)
3654{
3655  struct ospf_lsa *lsa;
3656  struct listnode *ln;
3657  size_t size;
3658  static char warned = 0;
3659
3660  lsa = listgetdata((ln = listhead (update)));
3661  assert (lsa->data);
3662
3663  if ((OSPF_LS_UPD_MIN_SIZE + ntohs (lsa->data->length))
3664      > ospf_packet_max (oi))
3665    {
3666      if (!warned)
3667        {
3668          zlog_warn ("ospf_ls_upd_packet_new: oversized LSA encountered!"
3669                     "will need to fragment. Not optimal. Try divide up"
3670                     " your network with areas. Use 'debug ospf packet send'"
3671                     " to see details, or look at 'show ip ospf database ..'");
3672          warned = 1;
3673        }
3674
3675      if (IS_DEBUG_OSPF_PACKET (0, SEND))
3676        zlog_debug ("ospf_ls_upd_packet_new: oversized LSA id:%s,"
3677                   " %d bytes originated by %s, will be fragmented!",
3678                   inet_ntoa (lsa->data->id),
3679                   ntohs (lsa->data->length),
3680                   inet_ntoa (lsa->data->adv_router));
3681
3682      /*
3683       * Allocate just enough to fit this LSA only, to avoid including other
3684       * LSAs in fragmented LSA Updates.
3685       */
3686      size = ntohs (lsa->data->length) + (oi->ifp->mtu - ospf_packet_max (oi))
3687             + OSPF_LS_UPD_MIN_SIZE;
3688    }
3689  else
3690    size = oi->ifp->mtu;
3691
3692  if (size > OSPF_MAX_PACKET_SIZE)
3693    {
3694      zlog_warn ("ospf_ls_upd_packet_new: oversized LSA id:%s too big,"
3695                 " %d bytes, packet size %ld, dropping it completely."
3696                 " OSPF routing is broken!",
3697                 inet_ntoa (lsa->data->id), ntohs (lsa->data->length),
3698                 (long int) size);
3699      list_delete_node (update, ln);
3700      return NULL;
3701    }
3702
3703  /* IP header is built up separately by ospf_write(). This means, that we must
3704   * reduce the "affordable" size just calculated by length of an IP header.
3705   * This makes sure, that even if we manage to fill the payload with LSA data
3706   * completely, the final packet (our data plus IP header) still fits into
3707   * outgoing interface MTU. This correction isn't really meaningful for an
3708   * oversized LSA, but for consistency the correction is done for both cases.
3709   *
3710   * P.S. OSPF_MAX_PACKET_SIZE above already includes IP header size
3711   */
3712  return ospf_packet_new (size - sizeof (struct ip));
3713}
3714
3715static void
3716ospf_ls_upd_queue_send (struct ospf_interface *oi, struct list *update,
3717			struct in_addr addr)
3718{
3719  struct ospf_packet *op;
3720  u_int16_t length = OSPF_HEADER_SIZE;
3721
3722  if (IS_DEBUG_OSPF_EVENT)
3723    zlog_debug ("listcount = %d, [%s]dst %s", listcount (update), IF_NAME(oi),
3724			    inet_ntoa(addr));
3725
3726  op = ospf_ls_upd_packet_new (update, oi);
3727
3728  /* Prepare OSPF common header. */
3729  ospf_make_header (OSPF_MSG_LS_UPD, oi, op->s);
3730
3731  /* Prepare OSPF Link State Update body.
3732   * Includes Type-7 translation.
3733   */
3734  length += ospf_make_ls_upd (oi, update, op->s);
3735
3736  /* Fill OSPF header. */
3737  ospf_fill_header (oi, op->s, length);
3738
3739  /* Set packet length. */
3740  op->length = length;
3741
3742  /* Decide destination address. */
3743  if (oi->type == OSPF_IFTYPE_POINTOPOINT)
3744    op->dst.s_addr = htonl (OSPF_ALLSPFROUTERS);
3745  else
3746    op->dst.s_addr = addr.s_addr;
3747
3748  /* Add packet to the interface output queue. */
3749  ospf_packet_add (oi, op);
3750
3751  /* Hook thread to write packet. */
3752  OSPF_ISM_WRITE_ON (oi->ospf);
3753}
3754
3755static int
3756ospf_ls_upd_send_queue_event (struct thread *thread)
3757{
3758  struct ospf_interface *oi = THREAD_ARG(thread);
3759  struct route_node *rn;
3760  struct route_node *rnext;
3761  struct list *update;
3762  char again = 0;
3763
3764  oi->t_ls_upd_event = NULL;
3765
3766  if (IS_DEBUG_OSPF_EVENT)
3767    zlog_debug ("ospf_ls_upd_send_queue start");
3768
3769  for (rn = route_top (oi->ls_upd_queue); rn; rn = rnext)
3770    {
3771      rnext = route_next (rn);
3772
3773      if (rn->info == NULL)
3774        continue;
3775
3776      update = (struct list *)rn->info;
3777
3778      ospf_ls_upd_queue_send (oi, update, rn->p.u.prefix4);
3779
3780      /* list might not be empty. */
3781      if (listcount(update) == 0)
3782        {
3783          list_delete (rn->info);
3784          rn->info = NULL;
3785          route_unlock_node (rn);
3786        }
3787      else
3788        again = 1;
3789    }
3790
3791  if (again != 0)
3792    {
3793      if (IS_DEBUG_OSPF_EVENT)
3794        zlog_debug ("ospf_ls_upd_send_queue: update lists not cleared,"
3795                   " %d nodes to try again, raising new event", again);
3796      oi->t_ls_upd_event =
3797        thread_add_event (master, ospf_ls_upd_send_queue_event, oi, 0);
3798    }
3799
3800  if (IS_DEBUG_OSPF_EVENT)
3801    zlog_debug ("ospf_ls_upd_send_queue stop");
3802
3803  return 0;
3804}
3805
3806void
3807ospf_ls_upd_send (struct ospf_neighbor *nbr, struct list *update, int flag)
3808{
3809  struct ospf_interface *oi;
3810  struct ospf_lsa *lsa;
3811  struct prefix_ipv4 p;
3812  struct route_node *rn;
3813  struct listnode *node;
3814
3815  oi = nbr->oi;
3816
3817  p.family = AF_INET;
3818  p.prefixlen = IPV4_MAX_BITLEN;
3819
3820  /* Decide destination address. */
3821  if (oi->type == OSPF_IFTYPE_VIRTUALLINK)
3822    p.prefix = oi->vl_data->peer_addr;
3823  else if (oi->type == OSPF_IFTYPE_POINTOPOINT)
3824     p.prefix.s_addr = htonl (OSPF_ALLSPFROUTERS);
3825  else if (flag == OSPF_SEND_PACKET_DIRECT)
3826     p.prefix = nbr->address.u.prefix4;
3827  else if (oi->state == ISM_DR || oi->state == ISM_Backup)
3828     p.prefix.s_addr = htonl (OSPF_ALLSPFROUTERS);
3829  else if (oi->type == OSPF_IFTYPE_POINTOMULTIPOINT)
3830     p.prefix.s_addr = htonl (OSPF_ALLSPFROUTERS);
3831  else
3832     p.prefix.s_addr = htonl (OSPF_ALLDROUTERS);
3833
3834  if (oi->type == OSPF_IFTYPE_NBMA)
3835    {
3836      if (flag == OSPF_SEND_PACKET_INDIRECT)
3837	zlog_warn ("* LS-Update is directly sent on NBMA network.");
3838      if (IPV4_ADDR_SAME(&oi->address->u.prefix4, &p.prefix.s_addr))
3839	zlog_warn ("* LS-Update is sent to myself.");
3840    }
3841
3842  rn = route_node_get (oi->ls_upd_queue, (struct prefix *) &p);
3843
3844  if (rn->info == NULL)
3845    rn->info = list_new ();
3846
3847  for (ALL_LIST_ELEMENTS_RO (update, node, lsa))
3848    listnode_add (rn->info, ospf_lsa_lock (lsa)); /* oi->ls_upd_queue */
3849
3850  if (oi->t_ls_upd_event == NULL)
3851    oi->t_ls_upd_event =
3852      thread_add_event (master, ospf_ls_upd_send_queue_event, oi, 0);
3853}
3854
3855static void
3856ospf_ls_ack_send_list (struct ospf_interface *oi, struct list *ack,
3857		       struct in_addr dst)
3858{
3859  struct ospf_packet *op;
3860  u_int16_t length = OSPF_HEADER_SIZE;
3861
3862  op = ospf_packet_new (oi->ifp->mtu);
3863
3864  /* Prepare OSPF common header. */
3865  ospf_make_header (OSPF_MSG_LS_ACK, oi, op->s);
3866
3867  /* Prepare OSPF Link State Acknowledgment body. */
3868  length += ospf_make_ls_ack (oi, ack, op->s);
3869
3870  /* Fill OSPF header. */
3871  ospf_fill_header (oi, op->s, length);
3872
3873  /* Set packet length. */
3874  op->length = length;
3875
3876  /* Set destination IP address. */
3877  op->dst = dst;
3878
3879  /* Add packet to the interface output queue. */
3880  ospf_packet_add (oi, op);
3881
3882  /* Hook thread to write packet. */
3883  OSPF_ISM_WRITE_ON (oi->ospf);
3884}
3885
3886static int
3887ospf_ls_ack_send_event (struct thread *thread)
3888{
3889  struct ospf_interface *oi = THREAD_ARG (thread);
3890
3891  oi->t_ls_ack_direct = NULL;
3892
3893  while (listcount (oi->ls_ack_direct.ls_ack))
3894    ospf_ls_ack_send_list (oi, oi->ls_ack_direct.ls_ack,
3895			   oi->ls_ack_direct.dst);
3896
3897  return 0;
3898}
3899
3900void
3901ospf_ls_ack_send (struct ospf_neighbor *nbr, struct ospf_lsa *lsa)
3902{
3903  struct ospf_interface *oi = nbr->oi;
3904
3905  if (listcount (oi->ls_ack_direct.ls_ack) == 0)
3906    oi->ls_ack_direct.dst = nbr->address.u.prefix4;
3907
3908  listnode_add (oi->ls_ack_direct.ls_ack, ospf_lsa_lock (lsa));
3909
3910  if (oi->t_ls_ack_direct == NULL)
3911    oi->t_ls_ack_direct =
3912      thread_add_event (master, ospf_ls_ack_send_event, oi, 0);
3913}
3914
3915/* Send Link State Acknowledgment delayed. */
3916void
3917ospf_ls_ack_send_delayed (struct ospf_interface *oi)
3918{
3919  struct in_addr dst;
3920
3921  /* Decide destination address. */
3922  /* RFC2328 Section 13.5                           On non-broadcast
3923	networks, delayed Link State Acknowledgment packets must be
3924	unicast	separately over	each adjacency (i.e., neighbor whose
3925	state is >= Exchange).  */
3926  if (oi->type == OSPF_IFTYPE_NBMA)
3927    {
3928      struct ospf_neighbor *nbr;
3929      struct route_node *rn;
3930
3931      for (rn = route_top (oi->nbrs); rn; rn = route_next (rn))
3932	if ((nbr = rn->info) != NULL)
3933	  if (nbr != oi->nbr_self && nbr->state >= NSM_Exchange)
3934	    while (listcount (oi->ls_ack))
3935	      ospf_ls_ack_send_list (oi, oi->ls_ack, nbr->address.u.prefix4);
3936      return;
3937    }
3938  if (oi->type == OSPF_IFTYPE_VIRTUALLINK)
3939    dst.s_addr = oi->vl_data->peer_addr.s_addr;
3940  else if (oi->state == ISM_DR || oi->state == ISM_Backup)
3941    dst.s_addr = htonl (OSPF_ALLSPFROUTERS);
3942  else if (oi->type == OSPF_IFTYPE_POINTOPOINT)
3943    dst.s_addr = htonl (OSPF_ALLSPFROUTERS);
3944  else if (oi->type == OSPF_IFTYPE_POINTOMULTIPOINT)
3945    dst.s_addr = htonl (OSPF_ALLSPFROUTERS);
3946  else
3947    dst.s_addr = htonl (OSPF_ALLDROUTERS);
3948
3949  while (listcount (oi->ls_ack))
3950    ospf_ls_ack_send_list (oi, oi->ls_ack, dst);
3951}
3952