1/* BGP packet management routine.
2   Copyright (C) 1999 Kunihiro Ishiguro
3
4This file is part of GNU Zebra.
5
6GNU Zebra is free software; you can redistribute it and/or modify it
7under the terms of the GNU General Public License as published by the
8Free Software Foundation; either version 2, or (at your option) any
9later version.
10
11GNU Zebra is distributed in the hope that it will be useful, but
12WITHOUT ANY WARRANTY; without even the implied warranty of
13MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14General Public License for more details.
15
16You should have received a copy of the GNU General Public License
17along with GNU Zebra; see the file COPYING.  If not, write to the Free
18Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
1902111-1307, USA.  */
20
21#include <zebra.h>
22
23#include "thread.h"
24#include "stream.h"
25#include "network.h"
26#include "prefix.h"
27#include "command.h"
28#include "log.h"
29#include "memory.h"
30#include "sockunion.h"		/* for inet_ntop () */
31#include "linklist.h"
32#include "plist.h"
33
34#include "bgpd/bgpd.h"
35#include "bgpd/bgp_table.h"
36#include "bgpd/bgp_dump.h"
37#include "bgpd/bgp_attr.h"
38#include "bgpd/bgp_debug.h"
39#include "bgpd/bgp_fsm.h"
40#include "bgpd/bgp_route.h"
41#include "bgpd/bgp_packet.h"
42#include "bgpd/bgp_open.h"
43#include "bgpd/bgp_aspath.h"
44#include "bgpd/bgp_community.h"
45#include "bgpd/bgp_network.h"
46#include "bgpd/bgp_mplsvpn.h"
47#include "bgpd/bgp_advertise.h"
48
49int stream_put_prefix (struct stream *, struct prefix *);
50
51/* Set up BGP packet marker and packet type. */
52static int
53bgp_packet_set_marker (struct stream *s, u_char type)
54{
55  int i;
56
57  /* Fill in marker. */
58  for (i = 0; i < BGP_MARKER_SIZE; i++)
59    stream_putc (s, 0xff);
60
61  /* Dummy total length. This field is should be filled in later on. */
62  stream_putw (s, 0);
63
64  /* BGP packet type. */
65  stream_putc (s, type);
66
67  /* Return current stream size. */
68  return stream_get_putp (s);
69}
70
71/* Set BGP packet header size entry.  If size is zero then use current
72   stream size. */
73static int
74bgp_packet_set_size (struct stream *s)
75{
76  int cp;
77
78  /* Preserve current pointer. */
79  cp = stream_get_putp (s);
80  stream_set_putp (s, BGP_MARKER_SIZE);
81  stream_putw (s, cp);
82
83  /* Write back current pointer. */
84  stream_set_putp (s, cp);
85
86  return cp;
87}
88
89/* Add new packet to the peer. */
90void
91bgp_packet_add (struct peer *peer, struct stream *s)
92{
93  /* Add packet to the end of list. */
94  stream_fifo_push (peer->obuf, s);
95}
96
97/* Free first packet. */
98void
99bgp_packet_delete (struct peer *peer)
100{
101  stream_free (stream_fifo_pop (peer->obuf));
102}
103
104/* Duplicate packet. */
105struct stream *
106bgp_packet_dup (struct stream *s)
107{
108  struct stream *new;
109
110  new = stream_new (stream_get_endp (s));
111
112  new->endp = s->endp;
113  new->putp = s->putp;
114  new->getp = s->getp;
115
116  memcpy (new->data, s->data, stream_get_endp (s));
117
118  return new;
119}
120
121/* Check file descriptor whether connect is established. */
122static void
123bgp_connect_check (struct peer *peer)
124{
125  int status;
126  int slen;
127  int ret;
128
129  /* Anyway I have to reset read and write thread. */
130  BGP_READ_OFF (peer->t_read);
131  BGP_WRITE_OFF (peer->t_write);
132
133  /* Check file descriptor. */
134  slen = sizeof (status);
135  ret = getsockopt(peer->fd, SOL_SOCKET, SO_ERROR, (void *) &status, &slen);
136
137  /* If getsockopt is fail, this is fatal error. */
138  if (ret < 0)
139    {
140      zlog (peer->log, LOG_INFO, "can't get sockopt for nonblocking connect");
141      BGP_EVENT_ADD (peer, TCP_fatal_error);
142      return;
143    }
144
145  /* When status is 0 then TCP connection is established. */
146  if (status == 0)
147    {
148      BGP_EVENT_ADD (peer, TCP_connection_open);
149    }
150  else
151    {
152      if (BGP_DEBUG (events, EVENTS))
153	  plog_info (peer->log, "%s [Event] Connect failed (%s)",
154		     peer->host, strerror (errno));
155      BGP_EVENT_ADD (peer, TCP_connection_open_failed);
156    }
157}
158
159/* Make BGP update packet.  */
160struct stream *
161bgp_update_packet (struct peer *peer, afi_t afi, safi_t safi)
162{
163  struct stream *s;
164  struct bgp_adj_out *adj;
165  struct bgp_advertise *adv;
166  struct stream *packet;
167  struct bgp_node *rn = NULL;
168  struct bgp_info *binfo = NULL;
169  bgp_size_t total_attr_len = 0;
170  unsigned long pos;
171  char buf[BUFSIZ];
172  struct prefix_rd *prd = NULL;
173  char *tag = NULL;
174
175  s = peer->work;
176  stream_reset (s);
177
178  adv = FIFO_HEAD (&peer->sync[afi][safi]->update);
179
180  while (adv)
181    {
182      if (adv->rn)
183        rn = adv->rn;
184      adj = adv->adj;
185      if (adv->binfo)
186        binfo = adv->binfo;
187#ifdef MPLS_VPN
188      if (rn)
189        prd = (struct prefix_rd *) &rn->prn->p;
190      if (binfo)
191        tag = binfo->tag;
192#endif /* MPLS_VPN */
193
194      /* When remaining space can't include NLRI and it's length.  */
195      if (rn && STREAM_REMAIN (s) <= BGP_NLRI_LENGTH + PSIZE (rn->p.prefixlen))
196	break;
197
198      /* If packet is empty, set attribute. */
199      if (stream_empty (s))
200	{
201	  bgp_packet_set_marker (s, BGP_MSG_UPDATE);
202	  stream_putw (s, 0);
203	  pos = stream_get_putp (s);
204	  stream_putw (s, 0);
205	  total_attr_len = bgp_packet_attribute (NULL, peer, s,
206	                			 adv->baa->attr,
207						 &rn->p, afi, safi,
208						 binfo->peer, prd, tag);
209	  stream_putw_at (s, pos, total_attr_len);
210	}
211
212      if (afi == AFI_IP && safi == SAFI_UNICAST)
213	stream_put_prefix (s, &rn->p);
214
215      if (BGP_DEBUG (update, UPDATE_OUT))
216	zlog (peer->log, LOG_INFO, "%s send UPDATE %s/%d",
217	      peer->host,
218	      inet_ntop (rn->p.family, &(rn->p.u.prefix), buf, BUFSIZ),
219	      rn->p.prefixlen);
220
221      /* Synchnorize attribute.  */
222      if (adj->attr)
223	bgp_attr_unintern (adj->attr);
224      else
225	peer->scount[afi][safi]++;
226
227      adj->attr = bgp_attr_intern (adv->baa->attr);
228
229      adv = bgp_advertise_clean (peer, adj, afi, safi);
230
231      if (! (afi == AFI_IP && safi == SAFI_UNICAST))
232	break;
233    }
234
235  if (! stream_empty (s))
236    {
237      bgp_packet_set_size (s);
238      packet = bgp_packet_dup (s);
239      bgp_packet_add (peer, packet);
240      BGP_WRITE_ON (peer->t_write, bgp_write, peer->fd);
241      stream_reset (s);
242      return packet;
243    }
244  return NULL;
245
246}
247
248/* Make BGP withdraw packet.  */
249struct stream *
250bgp_withdraw_packet (struct peer *peer, afi_t afi, safi_t safi)
251{
252  struct stream *s;
253  struct stream *packet;
254  struct bgp_adj_out *adj;
255  struct bgp_advertise *adv;
256  struct bgp_node *rn;
257  unsigned long pos;
258  bgp_size_t unfeasible_len;
259  bgp_size_t total_attr_len;
260  char buf[BUFSIZ];
261  struct prefix_rd *prd = NULL;
262
263  s = peer->work;
264  stream_reset (s);
265
266  while ((adv = FIFO_HEAD (&peer->sync[afi][safi]->withdraw)) != NULL)
267    {
268      adj = adv->adj;
269      rn = adv->rn;
270#ifdef MPLS_VPN
271      prd = (struct prefix_rd *) &rn->prn->p;
272#endif /* MPLS_VPN */
273
274      if (STREAM_REMAIN (s)
275	  <= (BGP_NLRI_LENGTH + BGP_TOTAL_ATTR_LEN + PSIZE (rn->p.prefixlen)))
276	break;
277
278      if (stream_empty (s))
279	{
280	  bgp_packet_set_marker (s, BGP_MSG_UPDATE);
281	  stream_putw (s, 0);
282	}
283
284      if (afi == AFI_IP && safi == SAFI_UNICAST)
285	stream_put_prefix (s, &rn->p);
286      else
287	{
288	  pos = stream_get_putp (s);
289	  stream_putw (s, 0);
290	  total_attr_len
291	    = bgp_packet_withdraw (peer, s, &rn->p, afi, safi, prd, NULL);
292
293	  /* Set total path attribute length. */
294	  stream_putw_at (s, pos, total_attr_len);
295	}
296
297      if (BGP_DEBUG (update, UPDATE_OUT))
298	zlog (peer->log, LOG_INFO, "%s send UPDATE %s/%d -- unreachable",
299	      peer->host,
300	      inet_ntop (rn->p.family, &(rn->p.u.prefix), buf, BUFSIZ),
301	      rn->p.prefixlen);
302
303      peer->scount[afi][safi]--;
304
305      bgp_adj_out_remove (rn, adj, peer, afi, safi);
306      bgp_unlock_node (rn);
307
308      if (! (afi == AFI_IP && safi == SAFI_UNICAST))
309	break;
310    }
311
312  if (! stream_empty (s))
313    {
314      if (afi == AFI_IP && safi == SAFI_UNICAST)
315	{
316	  unfeasible_len
317	    = stream_get_putp (s) - BGP_HEADER_SIZE - BGP_UNFEASIBLE_LEN;
318	  stream_putw_at (s, BGP_HEADER_SIZE, unfeasible_len);
319	  stream_putw (s, 0);
320	}
321      bgp_packet_set_size (s);
322      packet = bgp_packet_dup (s);
323      bgp_packet_add (peer, packet);
324      stream_reset (s);
325      return packet;
326    }
327
328  return NULL;
329}
330
331void
332bgp_default_update_send (struct peer *peer, struct attr *attr,
333			 afi_t afi, safi_t safi, struct peer *from)
334{
335  struct stream *s;
336  struct stream *packet;
337  struct prefix p;
338  unsigned long pos;
339  bgp_size_t total_attr_len;
340  char attrstr[BUFSIZ];
341  char buf[BUFSIZ];
342
343#ifdef DISABLE_BGP_ANNOUNCE
344  return;
345#endif /* DISABLE_BGP_ANNOUNCE */
346
347  if (afi == AFI_IP)
348    str2prefix ("0.0.0.0/0", &p);
349#ifdef HAVE_IPV6
350  else
351    str2prefix ("::/0", &p);
352#endif /* HAVE_IPV6 */
353
354  /* Logging the attribute. */
355  if (BGP_DEBUG (update, UPDATE_OUT))
356    {
357      bgp_dump_attr (peer, attr, attrstr, BUFSIZ);
358      zlog (peer->log, LOG_INFO, "%s send UPDATE %s/%d %s",
359	    peer->host, inet_ntop(p.family, &(p.u.prefix), buf, BUFSIZ),
360	    p.prefixlen, attrstr);
361    }
362
363  s = stream_new (BGP_MAX_PACKET_SIZE);
364
365  /* Make BGP update packet. */
366  bgp_packet_set_marker (s, BGP_MSG_UPDATE);
367
368  /* Unfeasible Routes Length. */
369  stream_putw (s, 0);
370
371  /* Make place for total attribute length.  */
372  pos = stream_get_putp (s);
373  stream_putw (s, 0);
374  total_attr_len = bgp_packet_attribute (NULL, peer, s, attr, &p, afi, safi, from, NULL, NULL);
375
376  /* Set Total Path Attribute Length. */
377  stream_putw_at (s, pos, total_attr_len);
378
379  /* NLRI set. */
380  if (p.family == AF_INET && safi == SAFI_UNICAST)
381    stream_put_prefix (s, &p);
382
383  /* Set size. */
384  bgp_packet_set_size (s);
385
386  packet = bgp_packet_dup (s);
387  stream_free (s);
388
389  /* Dump packet if debug option is set. */
390#ifdef DEBUG
391  bgp_packet_dump (packet);
392#endif /* DEBUG */
393
394  /* Add packet to the peer. */
395  bgp_packet_add (peer, packet);
396
397  BGP_WRITE_ON (peer->t_write, bgp_write, peer->fd);
398}
399
400void
401bgp_default_withdraw_send (struct peer *peer, afi_t afi, safi_t safi)
402{
403  struct stream *s;
404  struct stream *packet;
405  struct prefix p;
406  unsigned long pos;
407  unsigned long cp;
408  bgp_size_t unfeasible_len;
409  bgp_size_t total_attr_len;
410  char buf[BUFSIZ];
411
412#ifdef DISABLE_BGP_ANNOUNCE
413  return;
414#endif /* DISABLE_BGP_ANNOUNCE */
415
416  if (afi == AFI_IP)
417    str2prefix ("0.0.0.0/0", &p);
418#ifdef HAVE_IPV6
419  else
420    str2prefix ("::/0", &p);
421#endif /* HAVE_IPV6 */
422
423  total_attr_len = 0;
424  pos = 0;
425
426  if (BGP_DEBUG (update, UPDATE_OUT))
427    zlog (peer->log, LOG_INFO, "%s send UPDATE %s/%d -- unreachable",
428          peer->host, inet_ntop(p.family, &(p.u.prefix), buf, BUFSIZ),
429          p.prefixlen);
430
431  s = stream_new (BGP_MAX_PACKET_SIZE);
432
433  /* Make BGP update packet. */
434  bgp_packet_set_marker (s, BGP_MSG_UPDATE);
435
436  /* Unfeasible Routes Length. */;
437  cp = stream_get_putp (s);
438  stream_putw (s, 0);
439
440  /* Withdrawn Routes. */
441  if (p.family == AF_INET && safi == SAFI_UNICAST)
442    {
443      stream_put_prefix (s, &p);
444
445      unfeasible_len = stream_get_putp (s) - cp - 2;
446
447      /* Set unfeasible len.  */
448      stream_putw_at (s, cp, unfeasible_len);
449
450      /* Set total path attribute length. */
451      stream_putw (s, 0);
452    }
453  else
454    {
455      pos = stream_get_putp (s);
456      stream_putw (s, 0);
457      total_attr_len = bgp_packet_withdraw (peer, s, &p, afi, safi, NULL, NULL);
458
459      /* Set total path attribute length. */
460      stream_putw_at (s, pos, total_attr_len);
461    }
462
463  bgp_packet_set_size (s);
464
465  packet = bgp_packet_dup (s);
466  stream_free (s);
467
468  /* Add packet to the peer. */
469  bgp_packet_add (peer, packet);
470
471  BGP_WRITE_ON (peer->t_write, bgp_write, peer->fd);
472}
473
474/* Get next packet to be written.  */
475struct stream *
476bgp_write_packet (struct peer *peer)
477{
478  afi_t afi;
479  safi_t safi;
480  struct stream *s = NULL;
481  struct bgp_advertise *adv;
482
483  s = stream_fifo_head (peer->obuf);
484  if (s)
485    return s;
486
487  for (afi = AFI_IP; afi < AFI_MAX; afi++)
488    for (safi = SAFI_UNICAST; safi < SAFI_MAX; safi++)
489      {
490	adv = FIFO_HEAD (&peer->sync[afi][safi]->withdraw);
491	if (adv)
492	  {
493	    s = bgp_withdraw_packet (peer, afi, safi);
494	    if (s)
495	      return s;
496	  }
497      }
498
499  for (afi = AFI_IP; afi < AFI_MAX; afi++)
500    for (safi = SAFI_UNICAST; safi < SAFI_MAX; safi++)
501      {
502	adv = FIFO_HEAD (&peer->sync[afi][safi]->update);
503	if (adv)
504	  {
505            if (adv->binfo && adv->binfo->uptime < peer->synctime)
506              s = bgp_update_packet (peer, afi, safi);
507
508	    if (s)
509	      return s;
510	  }
511      }
512
513  return NULL;
514}
515
516/* Is there partially written packet or updates we can send right
517   now.  */
518int
519bgp_write_proceed (struct peer *peer)
520{
521  afi_t afi;
522  safi_t safi;
523  struct bgp_advertise *adv;
524
525  if (stream_fifo_head (peer->obuf))
526    return 1;
527
528  for (afi = AFI_IP; afi < AFI_MAX; afi++)
529    for (safi = SAFI_UNICAST; safi < SAFI_MAX; safi++)
530      if (FIFO_HEAD (&peer->sync[afi][safi]->withdraw))
531	return 1;
532
533  for (afi = AFI_IP; afi < AFI_MAX; afi++)
534    for (safi = SAFI_UNICAST; safi < SAFI_MAX; safi++)
535      if ((adv = FIFO_HEAD (&peer->sync[afi][safi]->update)) != NULL)
536	if (adv->binfo->uptime < peer->synctime)
537	  return 1;
538
539  return 0;
540}
541
542/* Write packet to the peer. */
543int
544bgp_write (struct thread *thread)
545{
546  struct peer *peer;
547  u_char type;
548  struct stream *s;
549  int num;
550  int count = 0;
551  int write_errno;
552
553  /* Yes first of all get peer pointer. */
554  peer = THREAD_ARG (thread);
555  peer->t_write = NULL;
556
557  /* For non-blocking IO check. */
558  if (peer->status == Connect)
559    {
560      bgp_connect_check (peer);
561      return 0;
562    }
563
564    /* Nonblocking write until TCP output buffer is full.  */
565  while (1)
566    {
567      int writenum;
568
569      s = bgp_write_packet (peer);
570      if (! s)
571	return 0;
572
573      /* Number of bytes to be sent.  */
574      writenum = stream_get_endp (s) - stream_get_getp (s);
575
576      /* Call write() system call.  */
577      num = write (peer->fd, STREAM_PNT (s), writenum);
578      write_errno = errno;
579      if (num <= 0)
580	{
581	  /* Partial write. */
582	  if (write_errno == EWOULDBLOCK || write_errno == EAGAIN)
583	      break;
584
585	  bgp_stop (peer);
586	  peer->status = Idle;
587	  bgp_timer_set (peer);
588	  return 0;
589	}
590      if (num != writenum)
591	{
592	  stream_forward (s, num);
593
594	  if (write_errno == EAGAIN)
595	    break;
596
597	  continue;
598	}
599
600      /* Retrieve BGP packet type. */
601      stream_set_getp (s, BGP_MARKER_SIZE + 2);
602      type = stream_getc (s);
603
604      switch (type)
605	{
606	case BGP_MSG_OPEN:
607	  peer->open_out++;
608	  break;
609	case BGP_MSG_UPDATE:
610	  peer->update_out++;
611	  break;
612	case BGP_MSG_NOTIFY:
613	  peer->notify_out++;
614	  /* Double start timer. */
615	  peer->v_start *= 2;
616
617	  /* Overflow check. */
618	  if (peer->v_start >= (60 * 2))
619	    peer->v_start = (60 * 2);
620
621	  /* BGP_EVENT_ADD (peer, BGP_Stop); */
622	  bgp_stop (peer);
623	  peer->status = Idle;
624	  bgp_timer_set (peer);
625	  return 0;
626	  break;
627	case BGP_MSG_KEEPALIVE:
628	  peer->keepalive_out++;
629	  break;
630	case BGP_MSG_ROUTE_REFRESH_NEW:
631	case BGP_MSG_ROUTE_REFRESH_OLD:
632	  peer->refresh_out++;
633	  break;
634	}
635
636      /* OK we send packet so delete it. */
637      bgp_packet_delete (peer);
638
639      if (++count >= BGP_WRITE_PACKET_MAX)
640	break;
641    }
642
643  if (bgp_write_proceed (peer))
644    BGP_WRITE_ON (peer->t_write, bgp_write, peer->fd);
645
646  return 0;
647}
648
649/* This is only for sending NOTIFICATION message to neighbor. */
650int
651bgp_write_notify (struct peer *peer)
652{
653  int ret;
654  u_char type;
655  struct stream *s;
656
657  /* There should be at least one packet. */
658  s = stream_fifo_head (peer->obuf);
659  if (!s)
660    return 0;
661  assert (stream_get_endp (s) >= BGP_HEADER_SIZE);
662
663  /* I'm not sure fd is writable. */
664  ret = writen (peer->fd, STREAM_DATA (s), stream_get_endp (s));
665  if (ret <= 0)
666    {
667      bgp_stop (peer);
668      peer->status = Idle;
669      bgp_timer_set (peer);
670      return 0;
671    }
672
673  /* Retrieve BGP packet type. */
674  stream_set_getp (s, BGP_MARKER_SIZE + 2);
675  type = stream_getc (s);
676
677  assert (type == BGP_MSG_NOTIFY);
678
679  /* Type should be notify. */
680  peer->notify_out++;
681
682  /* Double start timer. */
683  peer->v_start *= 2;
684
685  /* Overflow check. */
686  if (peer->v_start >= (60 * 2))
687    peer->v_start = (60 * 2);
688
689  /* We don't call event manager at here for avoiding other events. */
690  bgp_stop (peer);
691  peer->status = Idle;
692  bgp_timer_set (peer);
693
694  return 0;
695}
696
697/* Make keepalive packet and send it to the peer. */
698void
699bgp_keepalive_send (struct peer *peer)
700{
701  struct stream *s;
702  int length;
703
704  s = stream_new (BGP_MAX_PACKET_SIZE);
705
706  /* Make keepalive packet. */
707  bgp_packet_set_marker (s, BGP_MSG_KEEPALIVE);
708
709  /* Set packet size. */
710  length = bgp_packet_set_size (s);
711
712  /* Dump packet if debug option is set. */
713  /* bgp_packet_dump (s); */
714
715  if (BGP_DEBUG (keepalive, KEEPALIVE))
716    zlog_info ("%s sending KEEPALIVE", peer->host);
717  if (BGP_DEBUG (normal, NORMAL))
718    zlog_info ("%s send message type %d, length (incl. header) %d",
719               peer->host, BGP_MSG_KEEPALIVE, length);
720
721  /* Add packet to the peer. */
722  bgp_packet_add (peer, s);
723
724  BGP_WRITE_ON (peer->t_write, bgp_write, peer->fd);
725}
726
727/* Make open packet and send it to the peer. */
728void
729bgp_open_send (struct peer *peer)
730{
731  struct stream *s;
732  int length;
733  u_int16_t send_holdtime;
734  as_t local_as;
735
736  if (CHECK_FLAG (peer->config, PEER_CONFIG_TIMER))
737    send_holdtime = peer->holdtime;
738  else
739    send_holdtime = peer->bgp->default_holdtime;
740
741  /* local-as Change */
742  if (peer->change_local_as)
743    local_as = peer->change_local_as;
744  else
745    local_as = peer->local_as;
746
747  s = stream_new (BGP_MAX_PACKET_SIZE);
748
749  /* Make open packet. */
750  bgp_packet_set_marker (s, BGP_MSG_OPEN);
751
752  /* Set open packet values. */
753  stream_putc (s, BGP_VERSION_4);        /* BGP version */
754  stream_putw (s, local_as);		 /* My Autonomous System*/
755  stream_putw (s, send_holdtime);     	 /* Hold Time */
756  stream_put_in_addr (s, &peer->local_id); /* BGP Identifier */
757
758  /* Set capability code. */
759  bgp_open_capability (s, peer);
760
761  /* Set BGP packet length. */
762  length = bgp_packet_set_size (s);
763
764  if (BGP_DEBUG (normal, NORMAL))
765    zlog_info ("%s sending OPEN, version %d, my as %d, holdtime %d, id %s",
766	       peer->host, BGP_VERSION_4, local_as,
767	       send_holdtime, inet_ntoa (peer->local_id));
768
769  if (BGP_DEBUG (normal, NORMAL))
770    zlog_info ("%s send message type %d, length (incl. header) %d",
771	       peer->host, BGP_MSG_OPEN, length);
772
773  /* Dump packet if debug option is set. */
774  /* bgp_packet_dump (s); */
775
776  /* Add packet to the peer. */
777  bgp_packet_add (peer, s);
778
779  BGP_WRITE_ON (peer->t_write, bgp_write, peer->fd);
780}
781
782/* Send BGP notify packet with data potion. */
783void
784bgp_notify_send_with_data (struct peer *peer, u_char code, u_char sub_code,
785			   u_char *data, size_t datalen)
786{
787  struct stream *s;
788  int length;
789
790  /* Allocate new stream. */
791  s = stream_new (BGP_MAX_PACKET_SIZE);
792
793  /* Make nitify packet. */
794  bgp_packet_set_marker (s, BGP_MSG_NOTIFY);
795
796  /* Set notify packet values. */
797  stream_putc (s, code);        /* BGP notify code */
798  stream_putc (s, sub_code);	/* BGP notify sub_code */
799
800  /* If notify data is present. */
801  if (data)
802    stream_write (s, data, datalen);
803
804  /* Set BGP packet length. */
805  length = bgp_packet_set_size (s);
806
807  /* Add packet to the peer. */
808  stream_fifo_clean (peer->obuf);
809  bgp_packet_add (peer, s);
810
811  /* For debug */
812  {
813    struct bgp_notify bgp_notify;
814    int first = 0;
815    int i;
816    char c[4];
817
818    bgp_notify.code = code;
819    bgp_notify.subcode = sub_code;
820    bgp_notify.data = NULL;
821    bgp_notify.length = length - BGP_MSG_NOTIFY_MIN_SIZE;
822
823    if (bgp_notify.length)
824      {
825	bgp_notify.data = XMALLOC (MTYPE_TMP, bgp_notify.length * 3);
826	for (i = 0; i < bgp_notify.length; i++)
827	  if (first)
828	    {
829	      sprintf (c, " %02x", data[i]);
830	      strcat (bgp_notify.data, c);
831	    }
832	  else
833	    {
834	      first = 1;
835	      sprintf (c, "%02x", data[i]);
836	      strcpy (bgp_notify.data, c);
837	    }
838      }
839    bgp_notify_print (peer, &bgp_notify, "sending");
840    if (bgp_notify.data)
841      XFREE (MTYPE_TMP, bgp_notify.data);
842  }
843
844  if (BGP_DEBUG (normal, NORMAL))
845    zlog_info ("%s send message type %d, length (incl. header) %d",
846	       peer->host, BGP_MSG_NOTIFY, length);
847
848  /* Call imidiately. */
849  BGP_WRITE_OFF (peer->t_write);
850
851  bgp_write_notify (peer);
852}
853
854/* Send BGP notify packet. */
855void
856bgp_notify_send (struct peer *peer, u_char code, u_char sub_code)
857{
858  bgp_notify_send_with_data (peer, code, sub_code, NULL, 0);
859}
860
861char *
862afi2str (afi_t afi)
863{
864  if (afi == AFI_IP)
865    return "AFI_IP";
866  else if (afi == AFI_IP6)
867    return "AFI_IP6";
868  else
869    return "Unknown AFI";
870}
871
872char *
873safi2str (safi_t safi)
874{
875  if (safi == SAFI_UNICAST)
876    return "SAFI_UNICAST";
877  else if (safi == SAFI_MULTICAST)
878    return "SAFI_MULTICAST";
879  else if (safi == SAFI_MPLS_VPN || safi == BGP_SAFI_VPNV4)
880    return "SAFI_MPLS_VPN";
881  else
882    return "Unknown SAFI";
883}
884
885/* Send route refresh message to the peer. */
886void
887bgp_route_refresh_send (struct peer *peer, afi_t afi, safi_t safi,
888			u_char orf_type, u_char when_to_refresh, int remove)
889{
890  struct stream *s;
891  struct stream *packet;
892  int length;
893  struct bgp_filter *filter;
894  int orf_refresh = 0;
895
896#ifdef DISABLE_BGP_ANNOUNCE
897  return;
898#endif /* DISABLE_BGP_ANNOUNCE */
899
900  filter = &peer->filter[afi][safi];
901
902  /* Adjust safi code. */
903  if (safi == SAFI_MPLS_VPN)
904    safi = BGP_SAFI_VPNV4;
905
906  s = stream_new (BGP_MAX_PACKET_SIZE);
907
908  /* Make BGP update packet. */
909  if (CHECK_FLAG (peer->cap, PEER_CAP_REFRESH_NEW_RCV))
910    bgp_packet_set_marker (s, BGP_MSG_ROUTE_REFRESH_NEW);
911  else
912    bgp_packet_set_marker (s, BGP_MSG_ROUTE_REFRESH_OLD);
913
914  /* Encode Route Refresh message. */
915  stream_putw (s, afi);
916  stream_putc (s, 0);
917  stream_putc (s, safi);
918
919  if (orf_type == ORF_TYPE_PREFIX
920      || orf_type == ORF_TYPE_PREFIX_OLD)
921    if (remove || filter->plist[FILTER_IN].plist)
922      {
923	u_int16_t orf_len;
924	unsigned long orfp;
925
926	orf_refresh = 1;
927	stream_putc (s, when_to_refresh);
928	stream_putc (s, orf_type);
929	orfp = stream_get_putp (s);
930	stream_putw (s, 0);
931
932	if (remove)
933	  {
934	    UNSET_FLAG (peer->af_sflags[afi][safi], PEER_STATUS_ORF_PREFIX_SEND);
935	    stream_putc (s, ORF_COMMON_PART_REMOVE_ALL);
936	    if (BGP_DEBUG (normal, NORMAL))
937	      zlog_info ("%s sending REFRESH_REQ to remove ORF(%d) (%s) for afi/safi: %d/%d",
938			 peer->host, orf_type,
939			 (when_to_refresh == REFRESH_DEFER ? "defer" : "immediate"),
940			 afi, safi);
941	  }
942	else
943	  {
944	    SET_FLAG (peer->af_sflags[afi][safi], PEER_STATUS_ORF_PREFIX_SEND);
945	    prefix_bgp_orf_entry (s, filter->plist[FILTER_IN].plist,
946				  ORF_COMMON_PART_ADD, ORF_COMMON_PART_PERMIT,
947				  ORF_COMMON_PART_DENY);
948	    if (BGP_DEBUG (normal, NORMAL))
949	      zlog_info ("%s sending REFRESH_REQ with pfxlist ORF(%d) (%s) for afi/safi: %d/%d",
950			 peer->host, orf_type,
951			 (when_to_refresh == REFRESH_DEFER ? "defer" : "immediate"),
952			 afi, safi);
953	  }
954
955	/* Total ORF Entry Len. */
956	orf_len = stream_get_putp (s) - orfp - 2;
957	stream_putw_at (s, orfp, orf_len);
958      }
959
960  /* Set packet size. */
961  length = bgp_packet_set_size (s);
962
963  if (BGP_DEBUG (normal, NORMAL))
964    {
965      if (! orf_refresh)
966	zlog_info ("%s sending REFRESH_REQ for afi/safi: %d/%d",
967		   peer->host, afi, safi);
968      zlog_info ("%s send message type %d, length (incl. header) %d",
969		 peer->host, CHECK_FLAG (peer->cap, PEER_CAP_REFRESH_NEW_RCV) ?
970		 BGP_MSG_ROUTE_REFRESH_NEW : BGP_MSG_ROUTE_REFRESH_OLD, length);
971    }
972
973  /* Make real packet. */
974  packet = bgp_packet_dup (s);
975  stream_free (s);
976
977  /* Add packet to the peer. */
978  bgp_packet_add (peer, packet);
979
980  BGP_WRITE_ON (peer->t_write, bgp_write, peer->fd);
981}
982
983/* Send capability message to the peer. */
984void
985bgp_capability_send (struct peer *peer, afi_t afi, safi_t safi,
986		     int capability_code, int action)
987{
988  struct stream *s;
989  struct stream *packet;
990  int length;
991
992  /* Adjust safi code. */
993  if (safi == SAFI_MPLS_VPN)
994    safi = BGP_SAFI_VPNV4;
995
996  s = stream_new (BGP_MAX_PACKET_SIZE);
997
998  /* Make BGP update packet. */
999  bgp_packet_set_marker (s, BGP_MSG_CAPABILITY);
1000
1001  /* Encode MP_EXT capability. */
1002  if (capability_code == CAPABILITY_CODE_MP)
1003    {
1004      stream_putc (s, action);
1005      stream_putc (s, CAPABILITY_CODE_MP);
1006      stream_putc (s, CAPABILITY_CODE_MP_LEN);
1007      stream_putw (s, afi);
1008      stream_putc (s, 0);
1009      stream_putc (s, safi);
1010
1011      if (BGP_DEBUG (normal, NORMAL))
1012        zlog_info ("%s sending CAPABILITY has %s MP_EXT CAP for afi/safi: %d/%d",
1013		   peer->host, action == CAPABILITY_ACTION_SET ?
1014		   "Advertising" : "Removing", afi, safi);
1015    }
1016
1017  /* Encode Route Refresh capability. */
1018  if (capability_code == CAPABILITY_CODE_REFRESH)
1019    {
1020      stream_putc (s, action);
1021      stream_putc (s, CAPABILITY_CODE_REFRESH);
1022      stream_putc (s, CAPABILITY_CODE_REFRESH_LEN);
1023      stream_putc (s, action);
1024      stream_putc (s, CAPABILITY_CODE_REFRESH_OLD);
1025      stream_putc (s, CAPABILITY_CODE_REFRESH_LEN);
1026
1027      if (BGP_DEBUG (normal, NORMAL))
1028        zlog_info ("%s sending CAPABILITY has %s ROUTE-REFRESH capability",
1029		   peer->host, action == CAPABILITY_ACTION_SET ?
1030		   "Advertising" : "Removing");
1031    }
1032
1033  /* Set packet size. */
1034  length = bgp_packet_set_size (s);
1035
1036  /* Make real packet. */
1037  packet = bgp_packet_dup (s);
1038  stream_free (s);
1039
1040  /* Add packet to the peer. */
1041  bgp_packet_add (peer, packet);
1042
1043  if (BGP_DEBUG (normal, NORMAL))
1044    zlog_info ("%s send message type %d, length (incl. header) %d",
1045	       peer->host, BGP_MSG_CAPABILITY, length);
1046
1047  BGP_WRITE_ON (peer->t_write, bgp_write, peer->fd);
1048}
1049
1050/* RFC1771 6.8 Connection collision detection. */
1051int
1052bgp_collision_detect (struct peer *new, struct in_addr remote_id)
1053{
1054  struct peer *peer;
1055  struct listnode *nn;
1056  struct bgp *bgp;
1057
1058  bgp = bgp_get_default ();
1059  if (! bgp)
1060    return 0;
1061
1062  /* Upon receipt of an OPEN message, the local system must examine
1063     all of its connections that are in the OpenConfirm state.  A BGP
1064     speaker may also examine connections in an OpenSent state if it
1065     knows the BGP Identifier of the peer by means outside of the
1066     protocol.  If among these connections there is a connection to a
1067     remote BGP speaker whose BGP Identifier equals the one in the
1068     OPEN message, then the local system performs the following
1069     collision resolution procedure: */
1070
1071  LIST_LOOP (bgp->peer, peer, nn)
1072    {
1073      /* Under OpenConfirm status, local peer structure already hold
1074         remote router ID. */
1075
1076      if (peer != new
1077	  && (peer->status == OpenConfirm || peer->status == OpenSent)
1078	  && sockunion_same (&peer->su, &new->su))
1079	{
1080	  /* 1. The BGP Identifier of the local system is compared to
1081	     the BGP Identifier of the remote system (as specified in
1082	     the OPEN message). */
1083
1084	  if (ntohl (peer->local_id.s_addr) < ntohl (remote_id.s_addr))
1085	    {
1086	      /* 2. If the value of the local BGP Identifier is less
1087		 than the remote one, the local system closes BGP
1088		 connection that already exists (the one that is
1089		 already in the OpenConfirm state), and accepts BGP
1090		 connection initiated by the remote system. */
1091
1092	      if (peer->fd >= 0)
1093		bgp_notify_send (peer, BGP_NOTIFY_CEASE, 0);
1094	      return 1;
1095	    }
1096	  else
1097	    {
1098	      /* 3. Otherwise, the local system closes newly created
1099		 BGP connection (the one associated with the newly
1100		 received OPEN message), and continues to use the
1101		 existing one (the one that is already in the
1102		 OpenConfirm state). */
1103
1104	      if (new->fd >= 0)
1105		bgp_notify_send (new, BGP_NOTIFY_CEASE, 0);
1106	      return -1;
1107	    }
1108	}
1109    }
1110  return 0;
1111}
1112
1113int
1114bgp_open_receive (struct peer *peer, bgp_size_t size)
1115{
1116  int ret;
1117  u_char version;
1118  u_char optlen;
1119  u_int16_t holdtime;
1120  u_int16_t send_holdtime;
1121  as_t remote_as;
1122  struct peer *realpeer;
1123  struct in_addr remote_id;
1124  int capability;
1125  char notify_data_remote_as[2];
1126  char notify_data_remote_id[4];
1127
1128  realpeer = NULL;
1129
1130  /* Parse open packet. */
1131  version = stream_getc (peer->ibuf);
1132  memcpy (notify_data_remote_as, stream_pnt (peer->ibuf), 2);
1133  remote_as  = stream_getw (peer->ibuf);
1134  holdtime = stream_getw (peer->ibuf);
1135  memcpy (notify_data_remote_id, stream_pnt (peer->ibuf), 4);
1136  remote_id.s_addr = stream_get_ipv4 (peer->ibuf);
1137
1138  /* Receive OPEN message log  */
1139  if (BGP_DEBUG (normal, NORMAL))
1140    zlog_info ("%s rcv OPEN, version %d, remote-as %d, holdtime %d, id %s",
1141	       peer->host, version, remote_as, holdtime,
1142	       inet_ntoa (remote_id));
1143
1144  /* Lookup peer from Open packet. */
1145  if (CHECK_FLAG (peer->sflags, PEER_STATUS_ACCEPT_PEER))
1146    {
1147      int as = 0;
1148
1149      realpeer = peer_lookup_with_open (&peer->su, remote_as, &remote_id, &as);
1150
1151      if (! realpeer)
1152	{
1153	  /* Peer's source IP address is check in bgp_accept(), so this
1154	     must be AS number mismatch or remote-id configuration
1155	     mismatch. */
1156	  if (as)
1157	    {
1158	      if (BGP_DEBUG (normal, NORMAL))
1159		zlog_info ("%s bad OPEN, wrong router identifier %s",
1160			   peer->host, inet_ntoa (remote_id));
1161	      bgp_notify_send_with_data (peer,
1162					 BGP_NOTIFY_OPEN_ERR,
1163					 BGP_NOTIFY_OPEN_BAD_BGP_IDENT,
1164					 notify_data_remote_id, 4);
1165	    }
1166	  else
1167	    {
1168	      if (BGP_DEBUG (normal, NORMAL))
1169		zlog_info ("%s bad OPEN, remote AS is %d, expected %d",
1170			   peer->host, remote_as, peer->as);
1171	      bgp_notify_send_with_data (peer,
1172					 BGP_NOTIFY_OPEN_ERR,
1173					 BGP_NOTIFY_OPEN_BAD_PEER_AS,
1174					 notify_data_remote_as, 2);
1175	    }
1176	  return -1;
1177	}
1178    }
1179
1180  /* When collision is detected and this peer is closed.  Retrun
1181     immidiately. */
1182  ret = bgp_collision_detect (peer, remote_id);
1183  if (ret < 0)
1184    return ret;
1185
1186  /* Hack part. */
1187  if (CHECK_FLAG (peer->sflags, PEER_STATUS_ACCEPT_PEER))
1188    {
1189      if (ret == 0 && realpeer->status != Active
1190	  && realpeer->status != OpenSent
1191	  && realpeer->status != OpenConfirm)
1192 	{
1193 	  if (BGP_DEBUG (events, EVENTS))
1194 	    zlog_info ("%s [Event] peer's status is %s close connection",
1195		       realpeer->host, LOOKUP (bgp_status_msg, peer->status));
1196 	  return -1;
1197 	}
1198
1199      if (BGP_DEBUG (events, EVENTS))
1200	zlog_info ("%s [Event] Transfer temporary BGP peer to existing one",
1201		   peer->host);
1202
1203      bgp_stop (realpeer);
1204
1205      /* Transfer file descriptor. */
1206      realpeer->fd = peer->fd;
1207      peer->fd = -1;
1208
1209      /* Transfer input buffer. */
1210      stream_free (realpeer->ibuf);
1211      realpeer->ibuf = peer->ibuf;
1212      realpeer->packet_size = peer->packet_size;
1213      peer->ibuf = NULL;
1214
1215      /* Transfer status. */
1216      realpeer->status = peer->status;
1217      bgp_stop (peer);
1218
1219      /* peer pointer change. Open packet send to neighbor. */
1220      peer = realpeer;
1221      bgp_open_send (peer);
1222      if (peer->fd < 0)
1223	{
1224	  zlog_err ("bgp_open_receive peer's fd is negative value %d",
1225		    peer->fd);
1226	  return -1;
1227	}
1228      BGP_READ_ON (peer->t_read, bgp_read, peer->fd);
1229    }
1230
1231  /* remote router-id check. */
1232  if (remote_id.s_addr == 0
1233      || ntohl (remote_id.s_addr) >= 0xe0000000
1234      || ntohl (peer->local_id.s_addr) == ntohl (remote_id.s_addr))
1235    {
1236      if (BGP_DEBUG (normal, NORMAL))
1237	zlog_info ("%s bad OPEN, wrong router identifier %s",
1238		   peer->host, inet_ntoa (remote_id));
1239      bgp_notify_send_with_data (peer,
1240				 BGP_NOTIFY_OPEN_ERR,
1241				 BGP_NOTIFY_OPEN_BAD_BGP_IDENT,
1242				 notify_data_remote_id, 4);
1243      return -1;
1244    }
1245
1246  /* Set remote router-id */
1247  peer->remote_id = remote_id;
1248
1249  /* Peer BGP version check. */
1250  if (version != BGP_VERSION_4)
1251    {
1252      if (BGP_DEBUG (normal, NORMAL))
1253	zlog_info ("%s bad protocol version, remote requested %d, local request %d",
1254		   peer->host, version, BGP_VERSION_4);
1255      bgp_notify_send_with_data (peer,
1256				 BGP_NOTIFY_OPEN_ERR,
1257				 BGP_NOTIFY_OPEN_UNSUP_VERSION,
1258				 "\x04", 1);
1259      return -1;
1260    }
1261
1262  /* Check neighbor as number. */
1263  if (remote_as != peer->as)
1264    {
1265      if (BGP_DEBUG (normal, NORMAL))
1266	zlog_info ("%s bad OPEN, remote AS is %d, expected %d",
1267		   peer->host, remote_as, peer->as);
1268      bgp_notify_send_with_data (peer,
1269				 BGP_NOTIFY_OPEN_ERR,
1270				 BGP_NOTIFY_OPEN_BAD_PEER_AS,
1271				 notify_data_remote_as, 2);
1272      return -1;
1273    }
1274
1275  /* From the rfc: Upon receipt of an OPEN message, a BGP speaker MUST
1276     calculate the value of the Hold Timer by using the smaller of its
1277     configured Hold Time and the Hold Time received in the OPEN message.
1278     The Hold Time MUST be either zero or at least three seconds.  An
1279     implementation may reject connections on the basis of the Hold Time. */
1280
1281  if (holdtime < 3 && holdtime != 0)
1282    {
1283      bgp_notify_send (peer,
1284		       BGP_NOTIFY_OPEN_ERR,
1285		       BGP_NOTIFY_OPEN_UNACEP_HOLDTIME);
1286      return -1;
1287    }
1288
1289  /* From the rfc: A reasonable maximum time between KEEPALIVE messages
1290     would be one third of the Hold Time interval.  KEEPALIVE messages
1291     MUST NOT be sent more frequently than one per second.  An
1292     implementation MAY adjust the rate at which it sends KEEPALIVE
1293     messages as a function of the Hold Time interval. */
1294
1295  if (CHECK_FLAG (peer->config, PEER_CONFIG_TIMER))
1296    send_holdtime = peer->holdtime;
1297  else
1298    send_holdtime = peer->bgp->default_holdtime;
1299
1300  if (holdtime < send_holdtime)
1301    peer->v_holdtime = holdtime;
1302  else
1303    peer->v_holdtime = send_holdtime;
1304
1305  peer->v_keepalive = peer->v_holdtime / 3;
1306
1307  /* Open option part parse. */
1308  capability = 0;
1309  optlen = stream_getc (peer->ibuf);
1310  if (optlen != 0)
1311    {
1312      ret = bgp_open_option_parse (peer, optlen, &capability);
1313      if (ret < 0)
1314	return ret;
1315
1316      stream_forward (peer->ibuf, optlen);
1317    }
1318  else
1319    {
1320      if (BGP_DEBUG (normal, NORMAL))
1321	zlog_info ("%s rcvd OPEN w/ OPTION parameter len: 0",
1322		   peer->host);
1323    }
1324
1325  /* Override capability. */
1326  if (! capability || CHECK_FLAG (peer->flags, PEER_FLAG_OVERRIDE_CAPABILITY))
1327    {
1328      peer->afc_nego[AFI_IP][SAFI_UNICAST] = peer->afc[AFI_IP][SAFI_UNICAST];
1329      peer->afc_nego[AFI_IP][SAFI_MULTICAST] = peer->afc[AFI_IP][SAFI_MULTICAST];
1330      peer->afc_nego[AFI_IP6][SAFI_UNICAST] = peer->afc[AFI_IP6][SAFI_UNICAST];
1331      peer->afc_nego[AFI_IP6][SAFI_MULTICAST] = peer->afc[AFI_IP6][SAFI_MULTICAST];
1332    }
1333
1334  /* Get sockname. */
1335  bgp_getsockname (peer);
1336
1337  BGP_EVENT_ADD (peer, Receive_OPEN_message);
1338
1339  peer->packet_size = 0;
1340  if (peer->ibuf)
1341    stream_reset (peer->ibuf);
1342
1343  return 0;
1344}
1345
1346/* Parse BGP Update packet and make attribute object. */
1347int
1348bgp_update_receive (struct peer *peer, bgp_size_t size)
1349{
1350  int ret;
1351  u_char *end;
1352  struct stream *s;
1353  struct attr attr;
1354  bgp_size_t attribute_len;
1355  bgp_size_t update_len;
1356  bgp_size_t withdraw_len;
1357  struct bgp_nlri update;
1358  struct bgp_nlri withdraw;
1359  struct bgp_nlri mp_update;
1360  struct bgp_nlri mp_withdraw;
1361  char attrstr[BUFSIZ];
1362
1363  /* Status must be Established. */
1364  if (peer->status != Established)
1365    {
1366      zlog_err ("%s [FSM] Update packet received under status %s",
1367		peer->host, LOOKUP (bgp_status_msg, peer->status));
1368      bgp_notify_send (peer, BGP_NOTIFY_FSM_ERR, 0);
1369      return -1;
1370    }
1371
1372  /* Set initial values. */
1373  memset (&attr, 0, sizeof (struct attr));
1374  memset (&update, 0, sizeof (struct bgp_nlri));
1375  memset (&withdraw, 0, sizeof (struct bgp_nlri));
1376  memset (&mp_update, 0, sizeof (struct bgp_nlri));
1377  memset (&mp_withdraw, 0, sizeof (struct bgp_nlri));
1378
1379  s = peer->ibuf;
1380  end = stream_pnt (s) + size;
1381
1382  /* RFC1771 6.3 If the Unfeasible Routes Length or Total Attribute
1383     Length is too large (i.e., if Unfeasible Routes Length + Total
1384     Attribute Length + 23 exceeds the message Length), then the Error
1385     Subcode is set to Malformed Attribute List.  */
1386  if (stream_pnt (s) + 2 > end)
1387    {
1388      zlog_err ("%s [Error] Update packet error"
1389		" (packet length is short for unfeasible length)",
1390		peer->host);
1391      bgp_notify_send (peer, BGP_NOTIFY_UPDATE_ERR,
1392		       BGP_NOTIFY_UPDATE_MAL_ATTR);
1393      return -1;
1394    }
1395
1396  /* Unfeasible Route Length. */
1397  withdraw_len = stream_getw (s);
1398
1399  /* Unfeasible Route Length check. */
1400  if (stream_pnt (s) + withdraw_len > end)
1401    {
1402      zlog_err ("%s [Error] Update packet error"
1403		" (packet unfeasible length overflow %d)",
1404		peer->host, withdraw_len);
1405      bgp_notify_send (peer, BGP_NOTIFY_UPDATE_ERR,
1406		       BGP_NOTIFY_UPDATE_MAL_ATTR);
1407      return -1;
1408    }
1409
1410  /* Unfeasible Route packet format check. */
1411  if (withdraw_len > 0)
1412    {
1413      ret = bgp_nlri_sanity_check (peer, AFI_IP, stream_pnt (s), withdraw_len);
1414      if (ret < 0)
1415	return -1;
1416
1417      if (BGP_DEBUG (packet, PACKET_RECV))
1418	  zlog_info ("%s [Update:RECV] Unfeasible NLRI received", peer->host);
1419
1420      withdraw.afi = AFI_IP;
1421      withdraw.safi = SAFI_UNICAST;
1422      withdraw.nlri = stream_pnt (s);
1423      withdraw.length = withdraw_len;
1424      stream_forward (s, withdraw_len);
1425    }
1426
1427  /* Attribute total length check. */
1428  if (stream_pnt (s) + 2 > end)
1429    {
1430      zlog_warn ("%s [Error] Packet Error"
1431		 " (update packet is short for attribute length)",
1432		 peer->host);
1433      bgp_notify_send (peer, BGP_NOTIFY_UPDATE_ERR,
1434		       BGP_NOTIFY_UPDATE_MAL_ATTR);
1435      return -1;
1436    }
1437
1438  /* Fetch attribute total length. */
1439  attribute_len = stream_getw (s);
1440
1441  /* Attribute length check. */
1442  if (stream_pnt (s) + attribute_len > end)
1443    {
1444      zlog_warn ("%s [Error] Packet Error"
1445		 " (update packet attribute length overflow %d)",
1446		 peer->host, attribute_len);
1447      bgp_notify_send (peer, BGP_NOTIFY_UPDATE_ERR,
1448		       BGP_NOTIFY_UPDATE_MAL_ATTR);
1449      return -1;
1450    }
1451
1452  /* Parse attribute when it exists. */
1453  if (attribute_len)
1454    {
1455      ret = bgp_attr_parse (peer, &attr, attribute_len,
1456			    &mp_update, &mp_withdraw);
1457      if (ret < 0)
1458	return -1;
1459    }
1460
1461  /* Logging the attribute. */
1462  if (BGP_DEBUG (update, UPDATE_IN))
1463    {
1464      bgp_dump_attr (peer, &attr, attrstr, BUFSIZ);
1465      zlog (peer->log, LOG_INFO, "%s rcvd UPDATE w/ attr: %s",
1466	    peer->host, attrstr);
1467    }
1468
1469  /* Network Layer Reachability Information. */
1470  update_len = end - stream_pnt (s);
1471
1472  if (update_len)
1473    {
1474      /* Check NLRI packet format and prefix length. */
1475      ret = bgp_nlri_sanity_check (peer, AFI_IP, stream_pnt (s), update_len);
1476      if (ret < 0)
1477	return -1;
1478
1479      /* Set NLRI portion to structure. */
1480      update.afi = AFI_IP;
1481      update.safi = SAFI_UNICAST;
1482      update.nlri = stream_pnt (s);
1483      update.length = update_len;
1484      stream_forward (s, update_len);
1485    }
1486
1487  /* NLRI is processed only when the peer is configured specific
1488     Address Family and Subsequent Address Family. */
1489  if (peer->afc[AFI_IP][SAFI_UNICAST])
1490    {
1491      if (withdraw.length)
1492	bgp_nlri_parse (peer, NULL, &withdraw);
1493
1494      if (update.length)
1495	{
1496	  /* We check well-known attribute only for IPv4 unicast
1497	     update. */
1498	  ret = bgp_attr_check (peer, &attr);
1499	  if (ret < 0)
1500	    return -1;
1501
1502	  bgp_nlri_parse (peer, &attr, &update);
1503	}
1504    }
1505  if (peer->afc[AFI_IP][SAFI_MULTICAST])
1506    {
1507      if (mp_update.length
1508	  && mp_update.afi == AFI_IP
1509	  && mp_update.safi == SAFI_MULTICAST)
1510	bgp_nlri_parse (peer, &attr, &mp_update);
1511
1512      if (mp_withdraw.length
1513	  && mp_withdraw.afi == AFI_IP
1514	  && mp_withdraw.safi == SAFI_MULTICAST)
1515	bgp_nlri_parse (peer, NULL, &mp_withdraw);
1516    }
1517  if (peer->afc[AFI_IP6][SAFI_UNICAST])
1518    {
1519      if (mp_update.length
1520	  && mp_update.afi == AFI_IP6
1521	  && mp_update.safi == SAFI_UNICAST)
1522	bgp_nlri_parse (peer, &attr, &mp_update);
1523
1524      if (mp_withdraw.length
1525	  && mp_withdraw.afi == AFI_IP6
1526	  && mp_withdraw.safi == SAFI_UNICAST)
1527	bgp_nlri_parse (peer, NULL, &mp_withdraw);
1528    }
1529  if (peer->afc[AFI_IP6][SAFI_MULTICAST])
1530    {
1531      if (mp_update.length
1532	  && mp_update.afi == AFI_IP6
1533	  && mp_update.safi == SAFI_MULTICAST)
1534	bgp_nlri_parse (peer, &attr, &mp_update);
1535
1536      if (mp_withdraw.length
1537	  && mp_withdraw.afi == AFI_IP6
1538	  && mp_withdraw.safi == SAFI_MULTICAST)
1539	bgp_nlri_parse (peer, NULL, &mp_withdraw);
1540    }
1541  if (peer->afc[AFI_IP][SAFI_MPLS_VPN])
1542    {
1543      if (mp_update.length
1544	  && mp_update.afi == AFI_IP
1545	  && mp_update.safi == BGP_SAFI_VPNV4)
1546	bgp_nlri_parse_vpnv4 (peer, &attr, &mp_update);
1547
1548      if (mp_withdraw.length
1549	  && mp_withdraw.afi == AFI_IP
1550	  && mp_withdraw.safi == BGP_SAFI_VPNV4)
1551	bgp_nlri_parse_vpnv4 (peer, NULL, &mp_withdraw);
1552    }
1553
1554  /* Everything is done.  We unintern temporary structures which
1555     interned in bgp_attr_parse(). */
1556  if (attr.aspath)
1557    aspath_unintern (attr.aspath);
1558  if (attr.community)
1559    community_unintern (attr.community);
1560  if (attr.cluster)
1561    cluster_unintern (attr.cluster);
1562  if (attr.transit)
1563    transit_unintern (attr.transit);
1564
1565  /* If peering is stopped due to some reason, do not generate BGP
1566     event.  */
1567  if (peer->status != Established)
1568    return 0;
1569
1570  /* Increment packet counter. */
1571  peer->update_in++;
1572  peer->update_time = time (NULL);
1573
1574  /* Generate BGP event. */
1575  BGP_EVENT_ADD (peer, Receive_UPDATE_message);
1576
1577  return 0;
1578}
1579
1580/* Notify message treatment function. */
1581void
1582bgp_notify_receive (struct peer *peer, bgp_size_t size)
1583{
1584  struct bgp_notify bgp_notify;
1585
1586  if (peer->notify.data)
1587    {
1588      XFREE (MTYPE_TMP, peer->notify.data);
1589      peer->notify.data = NULL;
1590      peer->notify.length = 0;
1591    }
1592
1593  bgp_notify.code = stream_getc (peer->ibuf);
1594  bgp_notify.subcode = stream_getc (peer->ibuf);
1595  bgp_notify.length = size - 2;
1596  bgp_notify.data = NULL;
1597
1598  /* Preserv notify code and sub code. */
1599  peer->notify.code = bgp_notify.code;
1600  peer->notify.subcode = bgp_notify.subcode;
1601  /* For further diagnostic record returned Data. */
1602  if (bgp_notify.length)
1603    {
1604      peer->notify.length = size - 2;
1605      peer->notify.data = XMALLOC (MTYPE_TMP, size - 2);
1606      memcpy (peer->notify.data, stream_pnt (peer->ibuf), size - 2);
1607    }
1608
1609  /* For debug */
1610  {
1611    int i;
1612    int first = 0;
1613    char c[4];
1614
1615    if (bgp_notify.length)
1616      {
1617	bgp_notify.data = XMALLOC (MTYPE_TMP, bgp_notify.length * 3);
1618	for (i = 0; i < bgp_notify.length; i++)
1619	  if (first)
1620	    {
1621	      sprintf (c, " %02x", stream_getc (peer->ibuf));
1622	      strcat (bgp_notify.data, c);
1623	    }
1624	  else
1625	    {
1626	      first = 1;
1627	      sprintf (c, "%02x", stream_getc (peer->ibuf));
1628	      strcpy (bgp_notify.data, c);
1629	    }
1630      }
1631
1632    bgp_notify_print(peer, &bgp_notify, "received");
1633    if (bgp_notify.data)
1634      XFREE (MTYPE_TMP, bgp_notify.data);
1635  }
1636
1637  /* peer count update */
1638  peer->notify_in++;
1639
1640  /* We have to check for Notify with Unsupported Optional Parameter.
1641     in that case we fallback to open without the capability option.
1642     But this done in bgp_stop. We just mark it here to avoid changing
1643     the fsm tables.  */
1644  if (bgp_notify.code == BGP_NOTIFY_OPEN_ERR &&
1645      bgp_notify.subcode == BGP_NOTIFY_OPEN_UNSUP_PARAM )
1646    UNSET_FLAG (peer->sflags, PEER_STATUS_CAPABILITY_OPEN);
1647
1648  /* Also apply to Unsupported Capability until remote router support
1649     capability. */
1650  if (bgp_notify.code == BGP_NOTIFY_OPEN_ERR &&
1651      bgp_notify.subcode == BGP_NOTIFY_OPEN_UNSUP_CAPBL)
1652    UNSET_FLAG (peer->sflags, PEER_STATUS_CAPABILITY_OPEN);
1653
1654  BGP_EVENT_ADD (peer, Receive_NOTIFICATION_message);
1655}
1656
1657/* Keepalive treatment function -- get keepalive send keepalive */
1658void
1659bgp_keepalive_receive (struct peer *peer, bgp_size_t size)
1660{
1661  if (BGP_DEBUG (keepalive, KEEPALIVE))
1662    zlog_info ("%s KEEPALIVE rcvd", peer->host);
1663
1664  BGP_EVENT_ADD (peer, Receive_KEEPALIVE_message);
1665}
1666
1667/* Route refresh message is received. */
1668void
1669bgp_route_refresh_receive (struct peer *peer, bgp_size_t size)
1670{
1671  afi_t afi;
1672  safi_t safi;
1673  u_char reserved;
1674  struct stream *s;
1675
1676  /* If peer does not have the capability, send notification. */
1677  if (! CHECK_FLAG (peer->cap, PEER_CAP_REFRESH_ADV))
1678    {
1679      plog_err (peer->log, "%s [Error] BGP route refresh is not enabled",
1680		peer->host);
1681      bgp_notify_send (peer,
1682		       BGP_NOTIFY_HEADER_ERR,
1683		       BGP_NOTIFY_HEADER_BAD_MESTYPE);
1684      return;
1685    }
1686
1687  /* Status must be Established. */
1688  if (peer->status != Established)
1689    {
1690      plog_err (peer->log,
1691		"%s [Error] Route refresh packet received under status %s",
1692		peer->host, LOOKUP (bgp_status_msg, peer->status));
1693      bgp_notify_send (peer, BGP_NOTIFY_FSM_ERR, 0);
1694      return;
1695    }
1696
1697  s = peer->ibuf;
1698
1699  /* Parse packet. */
1700  afi = stream_getw (s);
1701  reserved = stream_getc (s);
1702  safi = stream_getc (s);
1703
1704  if (BGP_DEBUG (normal, NORMAL))
1705    zlog_info ("%s rcvd REFRESH_REQ for afi/safi: %d/%d",
1706	       peer->host, afi, safi);
1707
1708  /* Check AFI and SAFI. */
1709  if ((afi != AFI_IP && afi != AFI_IP6)
1710      || (safi != SAFI_UNICAST && safi != SAFI_MULTICAST
1711	  && safi != BGP_SAFI_VPNV4))
1712    {
1713      if (BGP_DEBUG (normal, NORMAL))
1714	{
1715	  zlog_info ("%s REFRESH_REQ for unrecognized afi/safi: %d/%d - ignored",
1716		     peer->host, afi, safi);
1717	}
1718      return;
1719    }
1720
1721  /* Adjust safi code. */
1722  if (safi == BGP_SAFI_VPNV4)
1723    safi = SAFI_MPLS_VPN;
1724
1725  if (size != BGP_MSG_ROUTE_REFRESH_MIN_SIZE - BGP_HEADER_SIZE)
1726    {
1727      u_char *end;
1728      u_char when_to_refresh;
1729      u_char orf_type;
1730      u_int16_t orf_len;
1731
1732      if (size - (BGP_MSG_ROUTE_REFRESH_MIN_SIZE - BGP_HEADER_SIZE) < 5)
1733        {
1734          zlog_info ("%s ORF route refresh length error", peer->host);
1735          bgp_notify_send (peer, BGP_NOTIFY_CEASE, 0);
1736          return;
1737        }
1738
1739      when_to_refresh = stream_getc (s);
1740      end = stream_pnt (s) + (size - 5);
1741
1742      while (stream_pnt (s) < end)
1743	{
1744	  orf_type = stream_getc (s);
1745	  orf_len = stream_getw (s);
1746
1747	  if (orf_type == ORF_TYPE_PREFIX
1748	      || orf_type == ORF_TYPE_PREFIX_OLD)
1749	    {
1750	      u_char *p_pnt = stream_pnt (s);
1751	      u_char *p_end = stream_pnt (s) + orf_len;
1752	      struct orf_prefix orfp;
1753	      u_char common = 0;
1754	      u_int32_t seq;
1755	      int psize;
1756	      char name[BUFSIZ];
1757	      char buf[BUFSIZ];
1758	      int ret;
1759
1760	      if (BGP_DEBUG (normal, NORMAL))
1761		{
1762		  zlog_info ("%s rcvd Prefixlist ORF(%d) length %d",
1763			     peer->host, orf_type, orf_len);
1764		}
1765
1766	      /* ORF prefix-list name */
1767	      sprintf (name, "%s.%d.%d", peer->host, afi, safi);
1768
1769	      while (p_pnt < p_end)
1770		{
1771		  memset (&orfp, 0, sizeof (struct orf_prefix));
1772		  common = *p_pnt++;
1773		  if (common & ORF_COMMON_PART_REMOVE_ALL)
1774		    {
1775		      if (BGP_DEBUG (normal, NORMAL))
1776			zlog_info ("%s rcvd Remove-All pfxlist ORF request", peer->host);
1777		      prefix_bgp_orf_remove_all (name);
1778		      break;
1779		    }
1780		  memcpy (&seq, p_pnt, sizeof (u_int32_t));
1781		  p_pnt += sizeof (u_int32_t);
1782		  orfp.seq = ntohl (seq);
1783		  orfp.ge = *p_pnt++;
1784		  orfp.le = *p_pnt++;
1785		  orfp.p.prefixlen = *p_pnt++;
1786		  orfp.p.family = afi2family (afi);
1787		  psize = PSIZE (orfp.p.prefixlen);
1788		  memcpy (&orfp.p.u.prefix, p_pnt, psize);
1789		  p_pnt += psize;
1790
1791		  if (BGP_DEBUG (normal, NORMAL))
1792		    zlog_info ("%s rcvd %s %s seq %u %s/%d ge %d le %d",
1793			       peer->host,
1794			       (common & ORF_COMMON_PART_REMOVE ? "Remove" : "Add"),
1795			       (common & ORF_COMMON_PART_DENY ? "deny" : "permit"),
1796			       orfp.seq,
1797			       inet_ntop (orfp.p.family, &orfp.p.u.prefix, buf, BUFSIZ),
1798			       orfp.p.prefixlen, orfp.ge, orfp.le);
1799
1800		  ret = prefix_bgp_orf_set (name, afi, &orfp,
1801				 (common & ORF_COMMON_PART_DENY ? 0 : 1 ),
1802				 (common & ORF_COMMON_PART_REMOVE ? 0 : 1));
1803
1804		  if (ret != CMD_SUCCESS)
1805		    {
1806		      if (BGP_DEBUG (normal, NORMAL))
1807			zlog_info ("%s Received misformatted prefixlist ORF. Remove All pfxlist", peer->host);
1808		      prefix_bgp_orf_remove_all (name);
1809		      break;
1810		    }
1811		}
1812	      peer->orf_plist[afi][safi] =
1813			 prefix_list_lookup (AFI_ORF_PREFIX, name);
1814	    }
1815	  stream_forward (s, orf_len);
1816	}
1817      if (BGP_DEBUG (normal, NORMAL))
1818	zlog_info ("%s rcvd Refresh %s ORF request", peer->host,
1819		   when_to_refresh == REFRESH_DEFER ? "Defer" : "Immediate");
1820      if (when_to_refresh == REFRESH_DEFER)
1821	return;
1822    }
1823
1824  /* First update is deferred until ORF or ROUTE-REFRESH is received */
1825  if (CHECK_FLAG (peer->af_sflags[afi][safi], PEER_STATUS_ORF_WAIT_REFRESH))
1826    UNSET_FLAG (peer->af_sflags[afi][safi], PEER_STATUS_ORF_WAIT_REFRESH);
1827
1828  /* Perform route refreshment to the peer */
1829  bgp_announce_route (peer, afi, safi);
1830}
1831
1832int
1833bgp_capability_msg_parse (struct peer *peer, u_char *pnt, bgp_size_t length)
1834{
1835  u_char *end;
1836  struct capability cap;
1837  u_char action;
1838  struct bgp *bgp;
1839  afi_t afi;
1840  safi_t safi;
1841
1842  bgp = peer->bgp;
1843  end = pnt + length;
1844
1845  while (pnt < end)
1846    {
1847      /* We need at least action, capability code and capability length. */
1848      if (pnt + 3 > end)
1849        {
1850          zlog_info ("%s Capability length error", peer->host);
1851          bgp_notify_send (peer, BGP_NOTIFY_CEASE, 0);
1852          return -1;
1853        }
1854
1855      action = *pnt;
1856
1857      /* Fetch structure to the byte stream. */
1858      memcpy (&cap, pnt + 1, sizeof (struct capability));
1859
1860      /* Action value check.  */
1861      if (action != CAPABILITY_ACTION_SET
1862	  && action != CAPABILITY_ACTION_UNSET)
1863        {
1864          zlog_info ("%s Capability Action Value error %d",
1865		     peer->host, action);
1866          bgp_notify_send (peer, BGP_NOTIFY_CEASE, 0);
1867          return -1;
1868        }
1869
1870      if (BGP_DEBUG (normal, NORMAL))
1871	zlog_info ("%s CAPABILITY has action: %d, code: %u, length %u",
1872		   peer->host, action, cap.code, cap.length);
1873
1874      /* Capability length check. */
1875      if (pnt + (cap.length + 3) > end)
1876        {
1877          zlog_info ("%s Capability length error", peer->host);
1878          bgp_notify_send (peer, BGP_NOTIFY_CEASE, 0);
1879          return -1;
1880        }
1881
1882      /* We know MP Capability Code. */
1883      if (cap.code == CAPABILITY_CODE_MP)
1884        {
1885	  afi = ntohs (cap.mpc.afi);
1886	  safi = cap.mpc.safi;
1887
1888          /* Ignore capability when override-capability is set. */
1889          if (CHECK_FLAG (peer->flags, PEER_FLAG_OVERRIDE_CAPABILITY))
1890	    continue;
1891
1892	  /* Address family check.  */
1893	  if ((afi == AFI_IP
1894	       || afi == AFI_IP6)
1895	      && (safi == SAFI_UNICAST
1896		  || safi == SAFI_MULTICAST
1897		  || safi == BGP_SAFI_VPNV4))
1898	    {
1899	      if (BGP_DEBUG (normal, NORMAL))
1900		zlog_info ("%s CAPABILITY has %s MP_EXT CAP for afi/safi: %u/%u",
1901			   peer->host,
1902			   action == CAPABILITY_ACTION_SET
1903			   ? "Advertising" : "Removing",
1904			   ntohs(cap.mpc.afi) , cap.mpc.safi);
1905
1906	      /* Adjust safi code. */
1907	      if (safi == BGP_SAFI_VPNV4)
1908		safi = SAFI_MPLS_VPN;
1909
1910	      if (action == CAPABILITY_ACTION_SET)
1911		{
1912		  peer->afc_recv[afi][safi] = 1;
1913		  if (peer->afc[afi][safi])
1914		    {
1915		      peer->afc_nego[afi][safi] = 1;
1916		      bgp_announce_route (peer, afi, safi);
1917		    }
1918		}
1919	      else
1920		{
1921		  peer->afc_recv[afi][safi] = 0;
1922		  peer->afc_nego[afi][safi] = 0;
1923
1924		  if (peer_active_nego (peer))
1925		    bgp_clear_route (peer, afi, safi);
1926		  else
1927		    BGP_EVENT_ADD (peer, BGP_Stop);
1928		}
1929	    }
1930        }
1931      else if (cap.code == CAPABILITY_CODE_REFRESH
1932	       || cap.code == CAPABILITY_CODE_REFRESH_OLD)
1933        {
1934          /* Check length. */
1935          if (cap.length != 0)
1936            {
1937              zlog_info ("%s Route Refresh Capability length error %d",
1938                         peer->host, cap.length);
1939              bgp_notify_send (peer, BGP_NOTIFY_CEASE, 0);
1940              return -1;
1941            }
1942
1943          if (BGP_DEBUG (normal, NORMAL))
1944            zlog_info ("%s CAPABILITY has %s ROUTE-REFRESH capability(%s) for all address-families",
1945		       peer->host,
1946		       action == CAPABILITY_ACTION_SET
1947		       ? "Advertising" : "Removing",
1948		       cap.code == CAPABILITY_CODE_REFRESH_OLD
1949		       ? "old" : "new");
1950
1951          /* BGP refresh capability */
1952	  if (action == CAPABILITY_ACTION_SET)
1953	    {
1954	      if (cap.code == CAPABILITY_CODE_REFRESH_OLD)
1955		SET_FLAG (peer->cap, PEER_CAP_REFRESH_OLD_RCV);
1956	      else
1957		SET_FLAG (peer->cap, PEER_CAP_REFRESH_NEW_RCV);
1958	    }
1959	  else
1960	    {
1961	      if (cap.code == CAPABILITY_CODE_REFRESH_OLD)
1962		UNSET_FLAG (peer->cap, PEER_CAP_REFRESH_OLD_RCV);
1963	      else
1964		UNSET_FLAG (peer->cap, PEER_CAP_REFRESH_NEW_RCV);
1965	    }
1966        }
1967      else
1968        {
1969          zlog_warn ("%s unrecognized capability code: %d - ignored",
1970                     peer->host, cap.code);
1971        }
1972      pnt += cap.length + 3;
1973    }
1974  return 0;
1975}
1976
1977/* Dynamic Capability is received. */
1978void
1979bgp_capability_receive (struct peer *peer, bgp_size_t size)
1980{
1981  u_char *pnt;
1982  int ret;
1983
1984  /* Fetch pointer. */
1985  pnt = stream_pnt (peer->ibuf);
1986
1987  if (BGP_DEBUG (normal, NORMAL))
1988    zlog_info ("%s rcv CAPABILITY", peer->host);
1989
1990  /* If peer does not have the capability, send notification. */
1991  if (! CHECK_FLAG (peer->cap, PEER_CAP_DYNAMIC_ADV))
1992    {
1993      plog_err (peer->log, "%s [Error] BGP dynamic capability is not enabled",
1994		peer->host);
1995      bgp_notify_send (peer,
1996		       BGP_NOTIFY_HEADER_ERR,
1997		       BGP_NOTIFY_HEADER_BAD_MESTYPE);
1998      return;
1999    }
2000
2001  /* Status must be Established. */
2002  if (peer->status != Established)
2003    {
2004      plog_err (peer->log,
2005		"%s [Error] Dynamic capability packet received under status %s", peer->host, LOOKUP (bgp_status_msg, peer->status));
2006      bgp_notify_send (peer, BGP_NOTIFY_FSM_ERR, 0);
2007      return;
2008    }
2009
2010  /* Parse packet. */
2011  ret = bgp_capability_msg_parse (peer, pnt, size);
2012}
2013
2014/* BGP read utility function. */
2015int
2016bgp_read_packet (struct peer *peer)
2017{
2018  int nbytes;
2019  int readsize;
2020
2021  readsize = peer->packet_size - peer->ibuf->putp;
2022
2023  /* If size is zero then return. */
2024  if (! readsize)
2025    return 0;
2026
2027  /* Read packet from fd. */
2028  nbytes = stream_read_unblock (peer->ibuf, peer->fd, readsize);
2029
2030  /* If read byte is smaller than zero then error occured. */
2031  if (nbytes < 0)
2032    {
2033      if (errno == EAGAIN)
2034	return -1;
2035
2036      plog_err (peer->log, "%s [Error] bgp_read_packet error: %s",
2037		 peer->host, strerror (errno));
2038      BGP_EVENT_ADD (peer, TCP_fatal_error);
2039      return -1;
2040    }
2041
2042  /* When read byte is zero : clear bgp peer and return */
2043  if (nbytes == 0)
2044    {
2045      if (BGP_DEBUG (events, EVENTS))
2046	plog_info (peer->log, "%s [Event] BGP connection closed fd %d",
2047		   peer->host, peer->fd);
2048      BGP_EVENT_ADD (peer, TCP_connection_closed);
2049      return -1;
2050    }
2051
2052  /* We read partial packet. */
2053  if (peer->ibuf->putp != peer->packet_size)
2054    return -1;
2055
2056  return 0;
2057}
2058
2059/* Marker check. */
2060int
2061bgp_marker_all_one (struct stream *s, int length)
2062{
2063  int i;
2064
2065  for (i = 0; i < length; i++)
2066    if (s->data[i] != 0xff)
2067      return 0;
2068
2069  return 1;
2070}
2071
2072/* Starting point of packet process function. */
2073int
2074bgp_read (struct thread *thread)
2075{
2076  int ret;
2077  u_char type = 0;
2078  struct peer *peer;
2079  bgp_size_t size;
2080  char notify_data_length[2];
2081
2082  /* Yes first of all get peer pointer. */
2083  peer = THREAD_ARG (thread);
2084  peer->t_read = NULL;
2085
2086  /* For non-blocking IO check. */
2087  if (peer->status == Connect)
2088    {
2089      bgp_connect_check (peer);
2090      goto done;
2091    }
2092  else
2093    {
2094      if (peer->fd < 0)
2095	{
2096	  zlog_err ("bgp_read peer's fd is negative value %d", peer->fd);
2097	  return -1;
2098	}
2099      BGP_READ_ON (peer->t_read, bgp_read, peer->fd);
2100    }
2101
2102  /* Read packet header to determine type of the packet */
2103  if (peer->packet_size == 0)
2104    peer->packet_size = BGP_HEADER_SIZE;
2105
2106  if (peer->ibuf->putp < BGP_HEADER_SIZE)
2107    {
2108      ret = bgp_read_packet (peer);
2109
2110      /* Header read error or partial read packet. */
2111      if (ret < 0)
2112	goto done;
2113
2114      /* Get size and type. */
2115      stream_forward (peer->ibuf, BGP_MARKER_SIZE);
2116      memcpy (notify_data_length, stream_pnt (peer->ibuf), 2);
2117      size = stream_getw (peer->ibuf);
2118      type = stream_getc (peer->ibuf);
2119
2120      if (BGP_DEBUG (normal, NORMAL) && type != 2 && type != 0)
2121	zlog_info ("%s rcv message type %d, length (excl. header) %d",
2122		   peer->host, type, size - BGP_HEADER_SIZE);
2123
2124      /* Marker check */
2125      if (type == BGP_MSG_OPEN
2126	  && ! bgp_marker_all_one (peer->ibuf, BGP_MARKER_SIZE))
2127	{
2128	  bgp_notify_send (peer,
2129			   BGP_NOTIFY_HEADER_ERR,
2130			   BGP_NOTIFY_HEADER_NOT_SYNC);
2131	  goto done;
2132	}
2133
2134      /* BGP type check. */
2135      if (type != BGP_MSG_OPEN && type != BGP_MSG_UPDATE
2136	  && type != BGP_MSG_NOTIFY && type != BGP_MSG_KEEPALIVE
2137	  && type != BGP_MSG_ROUTE_REFRESH_NEW
2138	  && type != BGP_MSG_ROUTE_REFRESH_OLD
2139	  && type != BGP_MSG_CAPABILITY)
2140	{
2141	  if (BGP_DEBUG (normal, NORMAL))
2142	    plog_err (peer->log,
2143		      "%s unknown message type 0x%02x",
2144		      peer->host, type);
2145	  bgp_notify_send_with_data (peer,
2146				     BGP_NOTIFY_HEADER_ERR,
2147			 	     BGP_NOTIFY_HEADER_BAD_MESTYPE,
2148				     &type, 1);
2149	  goto done;
2150	}
2151      /* Mimimum packet length check. */
2152      if ((size < BGP_HEADER_SIZE)
2153	  || (size > BGP_MAX_PACKET_SIZE)
2154	  || (type == BGP_MSG_OPEN && size < BGP_MSG_OPEN_MIN_SIZE)
2155	  || (type == BGP_MSG_UPDATE && size < BGP_MSG_UPDATE_MIN_SIZE)
2156	  || (type == BGP_MSG_NOTIFY && size < BGP_MSG_NOTIFY_MIN_SIZE)
2157	  || (type == BGP_MSG_KEEPALIVE && size != BGP_MSG_KEEPALIVE_MIN_SIZE)
2158	  || (type == BGP_MSG_ROUTE_REFRESH_NEW && size < BGP_MSG_ROUTE_REFRESH_MIN_SIZE)
2159	  || (type == BGP_MSG_ROUTE_REFRESH_OLD && size < BGP_MSG_ROUTE_REFRESH_MIN_SIZE)
2160	  || (type == BGP_MSG_CAPABILITY && size < BGP_MSG_CAPABILITY_MIN_SIZE))
2161	{
2162	  if (BGP_DEBUG (normal, NORMAL))
2163	    plog_err (peer->log,
2164		      "%s bad message length - %d for %s",
2165		      peer->host, size,
2166		      type == 128 ? "ROUTE-REFRESH" :
2167		      bgp_type_str[(int) type]);
2168	  bgp_notify_send_with_data (peer,
2169				     BGP_NOTIFY_HEADER_ERR,
2170			  	     BGP_NOTIFY_HEADER_BAD_MESLEN,
2171				     notify_data_length, 2);
2172	  goto done;
2173	}
2174
2175      /* Adjust size to message length. */
2176      peer->packet_size = size;
2177    }
2178
2179  ret = bgp_read_packet (peer);
2180  if (ret < 0)
2181    goto done;
2182
2183  /* Get size and type again. */
2184  size = stream_getw_from (peer->ibuf, BGP_MARKER_SIZE);
2185  type = stream_getc_from (peer->ibuf, BGP_MARKER_SIZE + 2);
2186
2187  /* BGP packet dump function. */
2188  bgp_dump_packet (peer, type, peer->ibuf);
2189
2190  size = (peer->packet_size - BGP_HEADER_SIZE);
2191
2192  /* Read rest of the packet and call each sort of packet routine */
2193  switch (type)
2194    {
2195    case BGP_MSG_OPEN:
2196      peer->open_in++;
2197      bgp_open_receive (peer, size);
2198      break;
2199    case BGP_MSG_UPDATE:
2200      peer->readtime = time(NULL);    /* Last read timer reset */
2201      bgp_update_receive (peer, size);
2202      break;
2203    case BGP_MSG_NOTIFY:
2204      bgp_notify_receive (peer, size);
2205      break;
2206    case BGP_MSG_KEEPALIVE:
2207      peer->readtime = time(NULL);    /* Last read timer reset */
2208      bgp_keepalive_receive (peer, size);
2209      break;
2210    case BGP_MSG_ROUTE_REFRESH_NEW:
2211    case BGP_MSG_ROUTE_REFRESH_OLD:
2212      peer->refresh_in++;
2213      bgp_route_refresh_receive (peer, size);
2214      break;
2215    case BGP_MSG_CAPABILITY:
2216      bgp_capability_receive (peer, size);
2217      break;
2218    }
2219
2220  /* Clear input buffer. */
2221  peer->packet_size = 0;
2222  if (peer->ibuf)
2223    stream_reset (peer->ibuf);
2224
2225 done:
2226  if (CHECK_FLAG (peer->sflags, PEER_STATUS_ACCEPT_PEER))
2227    {
2228      if (BGP_DEBUG (events, EVENTS))
2229	zlog_info ("%s [Event] Accepting BGP peer delete", peer->host);
2230      peer_delete (peer);
2231    }
2232  return 0;
2233}
2234