bundle.c revision 53830
1/*- 2 * Copyright (c) 1998 Brian Somers <brian@Awfulhak.org> 3 * All rights reserved. 4 * 5 * Redistribution and use in source and binary forms, with or without 6 * modification, are permitted provided that the following conditions 7 * are met: 8 * 1. Redistributions of source code must retain the above copyright 9 * notice, this list of conditions and the following disclaimer. 10 * 2. Redistributions in binary form must reproduce the above copyright 11 * notice, this list of conditions and the following disclaimer in the 12 * documentation and/or other materials provided with the distribution. 13 * 14 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND 15 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 16 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 17 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE 18 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 19 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 20 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 21 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 22 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 23 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 24 * SUCH DAMAGE. 25 * 26 * $FreeBSD: head/usr.sbin/ppp/bundle.c 53830 1999-11-28 15:50:08Z brian $ 27 */ 28 29#include <sys/param.h> 30#include <sys/socket.h> 31#include <netinet/in.h> 32#include <net/if.h> 33#include <net/if_tun.h> /* For TUNSIFMODE & TUNSLMODE */ 34#include <arpa/inet.h> 35#include <net/route.h> 36#include <netinet/in_systm.h> 37#include <netinet/ip.h> 38#include <sys/un.h> 39 40#include <errno.h> 41#include <fcntl.h> 42#ifdef __OpenBSD__ 43#include <util.h> 44#else 45#include <libutil.h> 46#endif 47#include <paths.h> 48#include <stdio.h> 49#include <stdlib.h> 50#include <string.h> 51#include <sys/uio.h> 52#include <sys/wait.h> 53#if defined(__FreeBSD__) && !defined(NOKLDLOAD) 54#include <sys/linker.h> 55#include <sys/module.h> 56#endif 57#include <termios.h> 58#include <unistd.h> 59 60#include "layer.h" 61#include "defs.h" 62#include "command.h" 63#include "mbuf.h" 64#include "log.h" 65#include "id.h" 66#include "timer.h" 67#include "fsm.h" 68#include "iplist.h" 69#include "lqr.h" 70#include "hdlc.h" 71#include "throughput.h" 72#include "slcompress.h" 73#include "ipcp.h" 74#include "filter.h" 75#include "descriptor.h" 76#include "route.h" 77#include "lcp.h" 78#include "ccp.h" 79#include "link.h" 80#include "mp.h" 81#ifndef NORADIUS 82#include "radius.h" 83#endif 84#include "bundle.h" 85#include "async.h" 86#include "physical.h" 87#include "auth.h" 88#include "proto.h" 89#include "chap.h" 90#include "tun.h" 91#include "prompt.h" 92#include "chat.h" 93#include "cbcp.h" 94#include "datalink.h" 95#include "ip.h" 96#include "iface.h" 97 98#define SCATTER_SEGMENTS 6 /* version, datalink, name, physical, 99 throughput, device */ 100 101#define SEND_MAXFD 3 /* Max file descriptors passed through 102 the local domain socket */ 103 104static int bundle_RemainingIdleTime(struct bundle *); 105 106static const char *PhaseNames[] = { 107 "Dead", "Establish", "Authenticate", "Network", "Terminate" 108}; 109 110const char * 111bundle_PhaseName(struct bundle *bundle) 112{ 113 return bundle->phase <= PHASE_TERMINATE ? 114 PhaseNames[bundle->phase] : "unknown"; 115} 116 117void 118bundle_NewPhase(struct bundle *bundle, u_int new) 119{ 120 if (new == bundle->phase) 121 return; 122 123 if (new <= PHASE_TERMINATE) 124 log_Printf(LogPHASE, "bundle: %s\n", PhaseNames[new]); 125 126 switch (new) { 127 case PHASE_DEAD: 128 log_DisplayPrompts(); 129 bundle->phase = new; 130 break; 131 132 case PHASE_ESTABLISH: 133 bundle->phase = new; 134 break; 135 136 case PHASE_AUTHENTICATE: 137 bundle->phase = new; 138 log_DisplayPrompts(); 139 break; 140 141 case PHASE_NETWORK: 142 fsm_Up(&bundle->ncp.ipcp.fsm); 143 fsm_Open(&bundle->ncp.ipcp.fsm); 144 bundle->phase = new; 145 log_DisplayPrompts(); 146 break; 147 148 case PHASE_TERMINATE: 149 bundle->phase = new; 150 mp_Down(&bundle->ncp.mp); 151 log_DisplayPrompts(); 152 break; 153 } 154} 155 156static void 157bundle_LayerStart(void *v, struct fsm *fp) 158{ 159 /* The given FSM is about to start up ! */ 160} 161 162 163static void 164bundle_Notify(struct bundle *bundle, char c) 165{ 166 if (bundle->notify.fd != -1) { 167 if (write(bundle->notify.fd, &c, 1) == 1) 168 log_Printf(LogPHASE, "Parent notified of success.\n"); 169 else 170 log_Printf(LogPHASE, "Failed to notify parent of success.\n"); 171 close(bundle->notify.fd); 172 bundle->notify.fd = -1; 173 } 174} 175 176static void 177bundle_ClearQueues(void *v) 178{ 179 struct bundle *bundle = (struct bundle *)v; 180 struct datalink *dl; 181 182 log_Printf(LogPHASE, "Clearing choked output queue\n"); 183 timer_Stop(&bundle->choked.timer); 184 185 /* 186 * Emergency time: 187 * 188 * We've had a full queue for PACKET_DEL_SECS seconds without being 189 * able to get rid of any of the packets. We've probably given up 190 * on the redials at this point, and the queued data has almost 191 * definitely been timed out by the layer above. As this is preventing 192 * us from reading the TUN_NAME device (we don't want to buffer stuff 193 * indefinitely), we may as well nuke this data and start with a clean 194 * slate ! 195 * 196 * Unfortunately, this has the side effect of shafting any compression 197 * dictionaries in use (causing the relevant RESET_REQ/RESET_ACK). 198 */ 199 200 ip_DeleteQueue(&bundle->ncp.ipcp); 201 mp_DeleteQueue(&bundle->ncp.mp); 202 for (dl = bundle->links; dl; dl = dl->next) 203 physical_DeleteQueue(dl->physical); 204} 205 206static void 207bundle_LinkAdded(struct bundle *bundle, struct datalink *dl) 208{ 209 bundle->phys_type.all |= dl->physical->type; 210 if (dl->state == DATALINK_OPEN) 211 bundle->phys_type.open |= dl->physical->type; 212 213 if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL)) 214 != bundle->phys_type.open && bundle->idle.timer.state == TIMER_STOPPED) 215 /* We may need to start our idle timer */ 216 bundle_StartIdleTimer(bundle); 217} 218 219void 220bundle_LinksRemoved(struct bundle *bundle) 221{ 222 struct datalink *dl; 223 224 bundle->phys_type.all = bundle->phys_type.open = 0; 225 for (dl = bundle->links; dl; dl = dl->next) 226 bundle_LinkAdded(bundle, dl); 227 228 bundle_CalculateBandwidth(bundle); 229 mp_CheckAutoloadTimer(&bundle->ncp.mp); 230 231 if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL)) 232 == bundle->phys_type.open) 233 bundle_StopIdleTimer(bundle); 234} 235 236static void 237bundle_LayerUp(void *v, struct fsm *fp) 238{ 239 /* 240 * The given fsm is now up 241 * If it's an LCP, adjust our phys_mode.open value and check the 242 * autoload timer. 243 * If it's the first NCP, calculate our bandwidth 244 * If it's the first NCP, set our ``upat'' time 245 * If it's the first NCP, start the idle timer. 246 * If it's an NCP, tell our -background parent to go away. 247 * If it's the first NCP, start the autoload timer 248 */ 249 struct bundle *bundle = (struct bundle *)v; 250 251 if (fp->proto == PROTO_LCP) { 252 struct physical *p = link2physical(fp->link); 253 254 bundle_LinkAdded(bundle, p->dl); 255 mp_CheckAutoloadTimer(&bundle->ncp.mp); 256 } else if (fp->proto == PROTO_IPCP) { 257 bundle_CalculateBandwidth(fp->bundle); 258 time(&bundle->upat); 259 bundle_StartIdleTimer(bundle); 260 bundle_Notify(bundle, EX_NORMAL); 261 mp_CheckAutoloadTimer(&fp->bundle->ncp.mp); 262 } 263} 264 265static void 266bundle_LayerDown(void *v, struct fsm *fp) 267{ 268 /* 269 * The given FSM has been told to come down. 270 * If it's our last NCP, stop the idle timer. 271 * If it's our last NCP, clear our ``upat'' value. 272 * If it's our last NCP, stop the autoload timer 273 * If it's an LCP, adjust our phys_type.open value and any timers. 274 * If it's an LCP and we're in multilink mode, adjust our tun 275 * speed and make sure our minimum sequence number is adjusted. 276 */ 277 278 struct bundle *bundle = (struct bundle *)v; 279 280 if (fp->proto == PROTO_IPCP) { 281 bundle_StopIdleTimer(bundle); 282 bundle->upat = 0; 283 mp_StopAutoloadTimer(&bundle->ncp.mp); 284 } else if (fp->proto == PROTO_LCP) { 285 bundle_LinksRemoved(bundle); /* adjust timers & phys_type values */ 286 if (bundle->ncp.mp.active) { 287 struct datalink *dl; 288 struct datalink *lost; 289 290 lost = NULL; 291 for (dl = bundle->links; dl; dl = dl->next) 292 if (fp == &dl->physical->link.lcp.fsm) 293 lost = dl; 294 295 bundle_CalculateBandwidth(bundle); 296 297 if (lost) 298 mp_LinkLost(&bundle->ncp.mp, lost); 299 else 300 log_Printf(LogALERT, "Oops, lost an unrecognised datalink (%s) !\n", 301 fp->link->name); 302 } 303 } 304} 305 306static void 307bundle_LayerFinish(void *v, struct fsm *fp) 308{ 309 /* The given fsm is now down (fp cannot be NULL) 310 * 311 * If it's the last LCP, fsm_Down all NCPs 312 * If it's the last NCP, fsm_Close all LCPs 313 */ 314 315 struct bundle *bundle = (struct bundle *)v; 316 struct datalink *dl; 317 318 if (fp->proto == PROTO_IPCP) { 319 if (bundle_Phase(bundle) != PHASE_DEAD) 320 bundle_NewPhase(bundle, PHASE_TERMINATE); 321 for (dl = bundle->links; dl; dl = dl->next) 322 datalink_Close(dl, CLOSE_STAYDOWN); 323 fsm2initial(fp); 324 } else if (fp->proto == PROTO_LCP) { 325 int others_active; 326 327 others_active = 0; 328 for (dl = bundle->links; dl; dl = dl->next) 329 if (fp != &dl->physical->link.lcp.fsm && 330 dl->state != DATALINK_CLOSED && dl->state != DATALINK_HANGUP) 331 others_active++; 332 333 if (!others_active) 334 fsm2initial(&bundle->ncp.ipcp.fsm); 335 } 336} 337 338int 339bundle_LinkIsUp(const struct bundle *bundle) 340{ 341 return bundle->ncp.ipcp.fsm.state == ST_OPENED; 342} 343 344void 345bundle_Close(struct bundle *bundle, const char *name, int how) 346{ 347 /* 348 * Please close the given datalink. 349 * If name == NULL or name is the last datalink, fsm_Close all NCPs 350 * (except our MP) 351 * If it isn't the last datalink, just Close that datalink. 352 */ 353 354 struct datalink *dl, *this_dl; 355 int others_active; 356 357 others_active = 0; 358 this_dl = NULL; 359 360 for (dl = bundle->links; dl; dl = dl->next) { 361 if (name && !strcasecmp(name, dl->name)) 362 this_dl = dl; 363 if (name == NULL || this_dl == dl) { 364 switch (how) { 365 case CLOSE_LCP: 366 datalink_DontHangup(dl); 367 /* fall through */ 368 case CLOSE_STAYDOWN: 369 datalink_StayDown(dl); 370 break; 371 } 372 } else if (dl->state != DATALINK_CLOSED && dl->state != DATALINK_HANGUP) 373 others_active++; 374 } 375 376 if (name && this_dl == NULL) { 377 log_Printf(LogWARN, "%s: Invalid datalink name\n", name); 378 return; 379 } 380 381 if (!others_active) { 382 bundle_StopIdleTimer(bundle); 383 if (bundle->ncp.ipcp.fsm.state > ST_CLOSED || 384 bundle->ncp.ipcp.fsm.state == ST_STARTING) 385 fsm_Close(&bundle->ncp.ipcp.fsm); 386 else { 387 fsm2initial(&bundle->ncp.ipcp.fsm); 388 for (dl = bundle->links; dl; dl = dl->next) 389 datalink_Close(dl, how); 390 } 391 } else if (this_dl && this_dl->state != DATALINK_CLOSED && 392 this_dl->state != DATALINK_HANGUP) 393 datalink_Close(this_dl, how); 394} 395 396void 397bundle_Down(struct bundle *bundle, int how) 398{ 399 struct datalink *dl; 400 401 for (dl = bundle->links; dl; dl = dl->next) 402 datalink_Down(dl, how); 403} 404 405static int 406bundle_UpdateSet(struct descriptor *d, fd_set *r, fd_set *w, fd_set *e, int *n) 407{ 408 struct bundle *bundle = descriptor2bundle(d); 409 struct datalink *dl; 410 int result, queued, nlinks; 411 412 result = 0; 413 414 /* If there are aren't many packets queued, look for some more. */ 415 for (nlinks = 0, dl = bundle->links; dl; dl = dl->next) 416 nlinks++; 417 418 if (nlinks) { 419 queued = r ? bundle_FillQueues(bundle) : ip_QueueLen(&bundle->ncp.ipcp); 420 421 if (r && (bundle->phase == PHASE_NETWORK || 422 bundle->phys_type.all & PHYS_AUTO)) { 423 /* enough surplus so that we can tell if we're getting swamped */ 424 if (queued < 30) { 425 /* Not enough - select() for more */ 426 if (bundle->choked.timer.state == TIMER_RUNNING) 427 timer_Stop(&bundle->choked.timer); /* Not needed any more */ 428 FD_SET(bundle->dev.fd, r); 429 if (*n < bundle->dev.fd + 1) 430 *n = bundle->dev.fd + 1; 431 log_Printf(LogTIMER, "%s: fdset(r) %d\n", TUN_NAME, bundle->dev.fd); 432 result++; 433 } else if (bundle->choked.timer.state == TIMER_STOPPED) { 434 bundle->choked.timer.func = bundle_ClearQueues; 435 bundle->choked.timer.name = "output choke"; 436 bundle->choked.timer.load = bundle->cfg.choked.timeout * SECTICKS; 437 bundle->choked.timer.arg = bundle; 438 timer_Start(&bundle->choked.timer); 439 } 440 } 441 } 442 443#ifndef NORADIUS 444 result += descriptor_UpdateSet(&bundle->radius.desc, r, w, e, n); 445#endif 446 447 /* Which links need a select() ? */ 448 for (dl = bundle->links; dl; dl = dl->next) 449 result += descriptor_UpdateSet(&dl->desc, r, w, e, n); 450 451 /* 452 * This *MUST* be called after the datalink UpdateSet()s as it 453 * might be ``holding'' one of the datalinks (death-row) and 454 * wants to be able to de-select() it from the descriptor set. 455 */ 456 result += descriptor_UpdateSet(&bundle->ncp.mp.server.desc, r, w, e, n); 457 458 return result; 459} 460 461static int 462bundle_IsSet(struct descriptor *d, const fd_set *fdset) 463{ 464 struct bundle *bundle = descriptor2bundle(d); 465 struct datalink *dl; 466 467 for (dl = bundle->links; dl; dl = dl->next) 468 if (descriptor_IsSet(&dl->desc, fdset)) 469 return 1; 470 471#ifndef NORADIUS 472 if (descriptor_IsSet(&bundle->radius.desc, fdset)) 473 return 1; 474#endif 475 476 if (descriptor_IsSet(&bundle->ncp.mp.server.desc, fdset)) 477 return 1; 478 479 return FD_ISSET(bundle->dev.fd, fdset); 480} 481 482static void 483bundle_DescriptorRead(struct descriptor *d, struct bundle *bundle, 484 const fd_set *fdset) 485{ 486 struct datalink *dl; 487 488 if (descriptor_IsSet(&bundle->ncp.mp.server.desc, fdset)) 489 descriptor_Read(&bundle->ncp.mp.server.desc, bundle, fdset); 490 491 for (dl = bundle->links; dl; dl = dl->next) 492 if (descriptor_IsSet(&dl->desc, fdset)) 493 descriptor_Read(&dl->desc, bundle, fdset); 494 495#ifndef NORADIUS 496 if (descriptor_IsSet(&bundle->radius.desc, fdset)) 497 descriptor_Read(&bundle->radius.desc, bundle, fdset); 498#endif 499 500 if (FD_ISSET(bundle->dev.fd, fdset)) { 501 struct tun_data tun; 502 int n, pri; 503 504 /* something to read from tun */ 505 n = read(bundle->dev.fd, &tun, sizeof tun); 506 if (n < 0) { 507 log_Printf(LogWARN, "read from %s: %s\n", TUN_NAME, strerror(errno)); 508 return; 509 } 510 n -= sizeof tun - sizeof tun.data; 511 if (n <= 0) { 512 log_Printf(LogERROR, "read from %s: Only %d bytes read ?\n", TUN_NAME, n); 513 return; 514 } 515 if (!tun_check_header(tun, AF_INET)) 516 return; 517 518 if (((struct ip *)tun.data)->ip_dst.s_addr == 519 bundle->ncp.ipcp.my_ip.s_addr) { 520 /* we've been asked to send something addressed *to* us :( */ 521 if (Enabled(bundle, OPT_LOOPBACK)) { 522 pri = PacketCheck(bundle, tun.data, n, &bundle->filter.in); 523 if (pri >= 0) { 524 n += sizeof tun - sizeof tun.data; 525 write(bundle->dev.fd, &tun, n); 526 log_Printf(LogDEBUG, "Looped back packet addressed to myself\n"); 527 } 528 return; 529 } else 530 log_Printf(LogDEBUG, "Oops - forwarding packet addressed to myself\n"); 531 } 532 533 /* 534 * Process on-demand dialup. Output packets are queued within tunnel 535 * device until IPCP is opened. 536 */ 537 538 if (bundle_Phase(bundle) == PHASE_DEAD) { 539 /* 540 * Note, we must be in AUTO mode :-/ otherwise our interface should 541 * *not* be UP and we can't receive data 542 */ 543 if ((pri = PacketCheck(bundle, tun.data, n, &bundle->filter.dial)) >= 0) 544 bundle_Open(bundle, NULL, PHYS_AUTO, 0); 545 else 546 /* 547 * Drop the packet. If we were to queue it, we'd just end up with 548 * a pile of timed-out data in our output queue by the time we get 549 * around to actually dialing. We'd also prematurely reach the 550 * threshold at which we stop select()ing to read() the tun 551 * device - breaking auto-dial. 552 */ 553 return; 554 } 555 556 pri = PacketCheck(bundle, tun.data, n, &bundle->filter.out); 557 if (pri >= 0) 558 ip_Enqueue(&bundle->ncp.ipcp, pri, tun.data, n); 559 } 560} 561 562static int 563bundle_DescriptorWrite(struct descriptor *d, struct bundle *bundle, 564 const fd_set *fdset) 565{ 566 struct datalink *dl; 567 int result = 0; 568 569 /* This is not actually necessary as struct mpserver doesn't Write() */ 570 if (descriptor_IsSet(&bundle->ncp.mp.server.desc, fdset)) 571 descriptor_Write(&bundle->ncp.mp.server.desc, bundle, fdset); 572 573 for (dl = bundle->links; dl; dl = dl->next) 574 if (descriptor_IsSet(&dl->desc, fdset)) 575 result += descriptor_Write(&dl->desc, bundle, fdset); 576 577 return result; 578} 579 580void 581bundle_LockTun(struct bundle *bundle) 582{ 583 FILE *lockfile; 584 char pidfile[MAXPATHLEN]; 585 586 snprintf(pidfile, sizeof pidfile, "%stun%d.pid", _PATH_VARRUN, bundle->unit); 587 lockfile = ID0fopen(pidfile, "w"); 588 if (lockfile != NULL) { 589 fprintf(lockfile, "%d\n", (int)getpid()); 590 fclose(lockfile); 591 } 592#ifndef RELEASE_CRUNCH 593 else 594 log_Printf(LogERROR, "Warning: Can't create %s: %s\n", 595 pidfile, strerror(errno)); 596#endif 597} 598 599static void 600bundle_UnlockTun(struct bundle *bundle) 601{ 602 char pidfile[MAXPATHLEN]; 603 604 snprintf(pidfile, sizeof pidfile, "%stun%d.pid", _PATH_VARRUN, bundle->unit); 605 ID0unlink(pidfile); 606} 607 608struct bundle * 609bundle_Create(const char *prefix, int type, int unit) 610{ 611 static struct bundle bundle; /* there can be only one */ 612 int enoentcount, err, minunit, maxunit; 613 const char *ifname; 614#if defined(__FreeBSD__) && !defined(NOKLDLOAD) 615 int kldtried; 616#endif 617#if defined(TUNSIFMODE) || defined(TUNSLMODE) 618 int iff; 619#endif 620 621 if (bundle.iface != NULL) { /* Already allocated ! */ 622 log_Printf(LogALERT, "bundle_Create: There's only one BUNDLE !\n"); 623 return NULL; 624 } 625 626 if (unit == -1) { 627 minunit = 0; 628 maxunit = -1; 629 } else { 630 minunit = unit; 631 maxunit = unit + 1; 632 } 633 err = ENOENT; 634 enoentcount = 0; 635#if defined(__FreeBSD__) && !defined(NOKLDLOAD) 636 kldtried = 0; 637#endif 638 for (bundle.unit = minunit; bundle.unit != maxunit; bundle.unit++) { 639 snprintf(bundle.dev.Name, sizeof bundle.dev.Name, "%s%d", 640 prefix, bundle.unit); 641 bundle.dev.fd = ID0open(bundle.dev.Name, O_RDWR); 642 if (bundle.dev.fd >= 0) 643 break; 644 else if (errno == ENXIO) { 645#if defined(__FreeBSD__) && !defined(NOKLDLOAD) 646 if (bundle.unit == minunit && !kldtried++) { 647 /* 648 * Attempt to load the tunnel interface KLD if it isn't loaded 649 * already. 650 */ 651 if (modfind("if_tun") == -1) { 652 if (ID0kldload("if_tun") != -1) { 653 bundle.unit--; 654 continue; 655 } 656 log_Printf(LogWARN, "kldload: if_tun: %s\n", strerror(errno)); 657 } 658 } 659#endif 660 err = errno; 661 break; 662 } else if (errno == ENOENT) { 663 if (++enoentcount > 2) 664 break; 665 } else 666 err = errno; 667 } 668 669 if (bundle.dev.fd < 0) { 670 if (unit == -1) 671 log_Printf(LogWARN, "No available tunnel devices found (%s)\n", 672 strerror(err)); 673 else 674 log_Printf(LogWARN, "%s%d: %s\n", prefix, unit, strerror(err)); 675 return NULL; 676 } 677 678 log_SetTun(bundle.unit); 679 680 ifname = strrchr(bundle.dev.Name, '/'); 681 if (ifname == NULL) 682 ifname = bundle.dev.Name; 683 else 684 ifname++; 685 686 bundle.iface = iface_Create(ifname); 687 if (bundle.iface == NULL) { 688 close(bundle.dev.fd); 689 return NULL; 690 } 691 692#ifdef TUNSIFMODE 693 /* Make sure we're POINTOPOINT */ 694 iff = IFF_POINTOPOINT; 695 if (ID0ioctl(bundle.dev.fd, TUNSIFMODE, &iff) < 0) 696 log_Printf(LogERROR, "bundle_Create: ioctl(TUNSIFMODE): %s\n", 697 strerror(errno)); 698#endif 699 700#ifdef TUNSLMODE 701 /* Make sure we're POINTOPOINT */ 702 iff = 0; 703 if (ID0ioctl(bundle.dev.fd, TUNSLMODE, &iff) < 0) 704 log_Printf(LogERROR, "bundle_Create: ioctl(TUNSLMODE): %s\n", 705 strerror(errno)); 706#endif 707 708 if (!iface_SetFlags(bundle.iface, IFF_UP)) { 709 iface_Destroy(bundle.iface); 710 bundle.iface = NULL; 711 close(bundle.dev.fd); 712 return NULL; 713 } 714 715 log_Printf(LogPHASE, "Using interface: %s\n", ifname); 716 717 bundle.bandwidth = 0; 718 bundle.routing_seq = 0; 719 bundle.phase = PHASE_DEAD; 720 bundle.CleaningUp = 0; 721 bundle.NatEnabled = 0; 722 723 bundle.fsm.LayerStart = bundle_LayerStart; 724 bundle.fsm.LayerUp = bundle_LayerUp; 725 bundle.fsm.LayerDown = bundle_LayerDown; 726 bundle.fsm.LayerFinish = bundle_LayerFinish; 727 bundle.fsm.object = &bundle; 728 729 bundle.cfg.idle.timeout = NCP_IDLE_TIMEOUT; 730 bundle.cfg.idle.min_timeout = 0; 731 *bundle.cfg.auth.name = '\0'; 732 *bundle.cfg.auth.key = '\0'; 733 bundle.cfg.opt = OPT_SROUTES | OPT_IDCHECK | OPT_LOOPBACK | 734 OPT_THROUGHPUT | OPT_UTMP; 735 *bundle.cfg.label = '\0'; 736 bundle.cfg.mtu = DEF_MTU; 737 bundle.cfg.choked.timeout = CHOKED_TIMEOUT; 738 bundle.phys_type.all = type; 739 bundle.phys_type.open = 0; 740 bundle.upat = 0; 741 742 bundle.links = datalink_Create("deflink", &bundle, type); 743 if (bundle.links == NULL) { 744 log_Printf(LogALERT, "Cannot create data link: %s\n", strerror(errno)); 745 iface_Destroy(bundle.iface); 746 bundle.iface = NULL; 747 close(bundle.dev.fd); 748 return NULL; 749 } 750 751 bundle.desc.type = BUNDLE_DESCRIPTOR; 752 bundle.desc.UpdateSet = bundle_UpdateSet; 753 bundle.desc.IsSet = bundle_IsSet; 754 bundle.desc.Read = bundle_DescriptorRead; 755 bundle.desc.Write = bundle_DescriptorWrite; 756 757 mp_Init(&bundle.ncp.mp, &bundle); 758 759 /* Send over the first physical link by default */ 760 ipcp_Init(&bundle.ncp.ipcp, &bundle, &bundle.links->physical->link, 761 &bundle.fsm); 762 763 memset(&bundle.filter, '\0', sizeof bundle.filter); 764 bundle.filter.in.fragok = bundle.filter.in.logok = 1; 765 bundle.filter.in.name = "IN"; 766 bundle.filter.out.fragok = bundle.filter.out.logok = 1; 767 bundle.filter.out.name = "OUT"; 768 bundle.filter.dial.name = "DIAL"; 769 bundle.filter.dial.logok = 1; 770 bundle.filter.alive.name = "ALIVE"; 771 bundle.filter.alive.logok = 1; 772 { 773 int i; 774 for (i = 0; i < MAXFILTERS; i++) { 775 bundle.filter.in.rule[i].f_action = A_NONE; 776 bundle.filter.out.rule[i].f_action = A_NONE; 777 bundle.filter.dial.rule[i].f_action = A_NONE; 778 bundle.filter.alive.rule[i].f_action = A_NONE; 779 } 780 } 781 memset(&bundle.idle.timer, '\0', sizeof bundle.idle.timer); 782 bundle.idle.done = 0; 783 bundle.notify.fd = -1; 784 memset(&bundle.choked.timer, '\0', sizeof bundle.choked.timer); 785#ifndef NORADIUS 786 radius_Init(&bundle.radius); 787#endif 788 789 /* Clean out any leftover crud */ 790 iface_Clear(bundle.iface, IFACE_CLEAR_ALL); 791 792 bundle_LockTun(&bundle); 793 794 return &bundle; 795} 796 797static void 798bundle_DownInterface(struct bundle *bundle) 799{ 800 route_IfDelete(bundle, 1); 801 iface_ClearFlags(bundle->iface, IFF_UP); 802} 803 804void 805bundle_Destroy(struct bundle *bundle) 806{ 807 struct datalink *dl; 808 809 /* 810 * Clean up the interface. We don't need to timer_Stop()s, mp_Down(), 811 * ipcp_CleanInterface() and bundle_DownInterface() unless we're getting 812 * out under exceptional conditions such as a descriptor exception. 813 */ 814 timer_Stop(&bundle->idle.timer); 815 timer_Stop(&bundle->choked.timer); 816 mp_Down(&bundle->ncp.mp); 817 ipcp_CleanInterface(&bundle->ncp.ipcp); 818 bundle_DownInterface(bundle); 819 820#ifndef NORADIUS 821 /* Tell the radius server the bad news */ 822 radius_Destroy(&bundle->radius); 823#endif 824 825 /* Again, these are all DATALINK_CLOSED unless we're abending */ 826 dl = bundle->links; 827 while (dl) 828 dl = datalink_Destroy(dl); 829 830 ipcp_Destroy(&bundle->ncp.ipcp); 831 832 close(bundle->dev.fd); 833 bundle_UnlockTun(bundle); 834 835 /* In case we never made PHASE_NETWORK */ 836 bundle_Notify(bundle, EX_ERRDEAD); 837 838 iface_Destroy(bundle->iface); 839 bundle->iface = NULL; 840} 841 842struct rtmsg { 843 struct rt_msghdr m_rtm; 844 char m_space[64]; 845}; 846 847int 848bundle_SetRoute(struct bundle *bundle, int cmd, struct in_addr dst, 849 struct in_addr gateway, struct in_addr mask, int bang, int ssh) 850{ 851 struct rtmsg rtmes; 852 int s, nb, wb; 853 char *cp; 854 const char *cmdstr; 855 struct sockaddr_in rtdata; 856 int result = 1; 857 858 if (bang) 859 cmdstr = (cmd == RTM_ADD ? "Add!" : "Delete!"); 860 else 861 cmdstr = (cmd == RTM_ADD ? "Add" : "Delete"); 862 s = ID0socket(PF_ROUTE, SOCK_RAW, 0); 863 if (s < 0) { 864 log_Printf(LogERROR, "bundle_SetRoute: socket(): %s\n", strerror(errno)); 865 return result; 866 } 867 memset(&rtmes, '\0', sizeof rtmes); 868 rtmes.m_rtm.rtm_version = RTM_VERSION; 869 rtmes.m_rtm.rtm_type = cmd; 870 rtmes.m_rtm.rtm_addrs = RTA_DST; 871 rtmes.m_rtm.rtm_seq = ++bundle->routing_seq; 872 rtmes.m_rtm.rtm_pid = getpid(); 873 rtmes.m_rtm.rtm_flags = RTF_UP | RTF_GATEWAY | RTF_STATIC; 874 875 if (cmd == RTM_ADD || cmd == RTM_CHANGE) { 876 if (bundle->ncp.ipcp.cfg.sendpipe > 0) { 877 rtmes.m_rtm.rtm_rmx.rmx_sendpipe = bundle->ncp.ipcp.cfg.sendpipe; 878 rtmes.m_rtm.rtm_inits |= RTV_SPIPE; 879 } 880 if (bundle->ncp.ipcp.cfg.recvpipe > 0) { 881 rtmes.m_rtm.rtm_rmx.rmx_recvpipe = bundle->ncp.ipcp.cfg.recvpipe; 882 rtmes.m_rtm.rtm_inits |= RTV_RPIPE; 883 } 884 } 885 886 memset(&rtdata, '\0', sizeof rtdata); 887 rtdata.sin_len = sizeof rtdata; 888 rtdata.sin_family = AF_INET; 889 rtdata.sin_port = 0; 890 rtdata.sin_addr = dst; 891 892 cp = rtmes.m_space; 893 memcpy(cp, &rtdata, rtdata.sin_len); 894 cp += rtdata.sin_len; 895 if (cmd == RTM_ADD) { 896 if (gateway.s_addr == INADDR_ANY) { 897 if (!ssh) 898 log_Printf(LogERROR, "bundle_SetRoute: Cannot add a route with" 899 " destination 0.0.0.0\n"); 900 close(s); 901 return result; 902 } else { 903 rtdata.sin_addr = gateway; 904 memcpy(cp, &rtdata, rtdata.sin_len); 905 cp += rtdata.sin_len; 906 rtmes.m_rtm.rtm_addrs |= RTA_GATEWAY; 907 } 908 } 909 910 if (dst.s_addr == INADDR_ANY) 911 mask.s_addr = INADDR_ANY; 912 913 if (cmd == RTM_ADD || dst.s_addr == INADDR_ANY) { 914 rtdata.sin_addr = mask; 915 memcpy(cp, &rtdata, rtdata.sin_len); 916 cp += rtdata.sin_len; 917 rtmes.m_rtm.rtm_addrs |= RTA_NETMASK; 918 } 919 920 nb = cp - (char *) &rtmes; 921 rtmes.m_rtm.rtm_msglen = nb; 922 wb = ID0write(s, &rtmes, nb); 923 if (wb < 0) { 924 log_Printf(LogTCPIP, "bundle_SetRoute failure:\n"); 925 log_Printf(LogTCPIP, "bundle_SetRoute: Cmd = %s\n", cmdstr); 926 log_Printf(LogTCPIP, "bundle_SetRoute: Dst = %s\n", inet_ntoa(dst)); 927 log_Printf(LogTCPIP, "bundle_SetRoute: Gateway = %s\n", 928 inet_ntoa(gateway)); 929 log_Printf(LogTCPIP, "bundle_SetRoute: Mask = %s\n", inet_ntoa(mask)); 930failed: 931 if (cmd == RTM_ADD && (rtmes.m_rtm.rtm_errno == EEXIST || 932 (rtmes.m_rtm.rtm_errno == 0 && errno == EEXIST))) { 933 if (!bang) { 934 log_Printf(LogWARN, "Add route failed: %s already exists\n", 935 dst.s_addr == 0 ? "default" : inet_ntoa(dst)); 936 result = 0; /* Don't add to our dynamic list */ 937 } else { 938 rtmes.m_rtm.rtm_type = cmd = RTM_CHANGE; 939 if ((wb = ID0write(s, &rtmes, nb)) < 0) 940 goto failed; 941 } 942 } else if (cmd == RTM_DELETE && 943 (rtmes.m_rtm.rtm_errno == ESRCH || 944 (rtmes.m_rtm.rtm_errno == 0 && errno == ESRCH))) { 945 if (!bang) 946 log_Printf(LogWARN, "Del route failed: %s: Non-existent\n", 947 inet_ntoa(dst)); 948 } else if (rtmes.m_rtm.rtm_errno == 0) { 949 if (!ssh || errno != ENETUNREACH) 950 log_Printf(LogWARN, "%s route failed: %s: errno: %s\n", cmdstr, 951 inet_ntoa(dst), strerror(errno)); 952 } else 953 log_Printf(LogWARN, "%s route failed: %s: %s\n", 954 cmdstr, inet_ntoa(dst), strerror(rtmes.m_rtm.rtm_errno)); 955 } 956 log_Printf(LogDEBUG, "wrote %d: cmd = %s, dst = %x, gateway = %x\n", 957 wb, cmdstr, (unsigned)dst.s_addr, (unsigned)gateway.s_addr); 958 close(s); 959 960 return result; 961} 962 963void 964bundle_LinkClosed(struct bundle *bundle, struct datalink *dl) 965{ 966 /* 967 * Our datalink has closed. 968 * CleanDatalinks() (called from DoLoop()) will remove closed 969 * BACKGROUND, FOREGROUND and DIRECT links. 970 * If it's the last data link, enter phase DEAD. 971 * 972 * NOTE: dl may not be in our list (bundle_SendDatalink()) ! 973 */ 974 975 struct datalink *odl; 976 int other_links; 977 978 log_SetTtyCommandMode(dl); 979 980 other_links = 0; 981 for (odl = bundle->links; odl; odl = odl->next) 982 if (odl != dl && odl->state != DATALINK_CLOSED) 983 other_links++; 984 985 if (!other_links) { 986 if (dl->physical->type != PHYS_AUTO) /* Not in -auto mode */ 987 bundle_DownInterface(bundle); 988 fsm2initial(&bundle->ncp.ipcp.fsm); 989 bundle_NewPhase(bundle, PHASE_DEAD); 990 bundle_StopIdleTimer(bundle); 991 } 992} 993 994void 995bundle_Open(struct bundle *bundle, const char *name, int mask, int force) 996{ 997 /* 998 * Please open the given datalink, or all if name == NULL 999 */ 1000 struct datalink *dl; 1001 1002 for (dl = bundle->links; dl; dl = dl->next) 1003 if (name == NULL || !strcasecmp(dl->name, name)) { 1004 if ((mask & dl->physical->type) && 1005 (dl->state == DATALINK_CLOSED || 1006 (force && dl->state == DATALINK_OPENING && 1007 dl->dial.timer.state == TIMER_RUNNING))) { 1008 if (force) /* Ignore redial timeout ? */ 1009 timer_Stop(&dl->dial.timer); 1010 datalink_Up(dl, 1, 1); 1011 if (mask & PHYS_AUTO) 1012 /* Only one AUTO link at a time */ 1013 break; 1014 } 1015 if (name != NULL) 1016 break; 1017 } 1018} 1019 1020struct datalink * 1021bundle2datalink(struct bundle *bundle, const char *name) 1022{ 1023 struct datalink *dl; 1024 1025 if (name != NULL) { 1026 for (dl = bundle->links; dl; dl = dl->next) 1027 if (!strcasecmp(dl->name, name)) 1028 return dl; 1029 } else if (bundle->links && !bundle->links->next) 1030 return bundle->links; 1031 1032 return NULL; 1033} 1034 1035int 1036bundle_FillQueues(struct bundle *bundle) 1037{ 1038 int total; 1039 1040 if (bundle->ncp.mp.active) 1041 total = mp_FillQueues(bundle); 1042 else { 1043 struct datalink *dl; 1044 int add; 1045 1046 for (total = 0, dl = bundle->links; dl; dl = dl->next) 1047 if (dl->state == DATALINK_OPEN) { 1048 add = link_QueueLen(&dl->physical->link); 1049 if (add == 0 && dl->physical->out == NULL) 1050 add = ip_PushPacket(&dl->physical->link, bundle); 1051 total += add; 1052 } 1053 } 1054 1055 return total + ip_QueueLen(&bundle->ncp.ipcp); 1056} 1057 1058int 1059bundle_ShowLinks(struct cmdargs const *arg) 1060{ 1061 struct datalink *dl; 1062 struct pppThroughput *t; 1063 int secs; 1064 1065 for (dl = arg->bundle->links; dl; dl = dl->next) { 1066 prompt_Printf(arg->prompt, "Name: %s [%s, %s]", 1067 dl->name, mode2Nam(dl->physical->type), datalink_State(dl)); 1068 if (dl->physical->link.throughput.rolling && dl->state == DATALINK_OPEN) 1069 prompt_Printf(arg->prompt, " bandwidth %d, %llu bps (%llu bytes/sec)", 1070 dl->mp.bandwidth ? dl->mp.bandwidth : 1071 physical_GetSpeed(dl->physical), 1072 dl->physical->link.throughput.OctetsPerSecond * 8, 1073 dl->physical->link.throughput.OctetsPerSecond); 1074 prompt_Printf(arg->prompt, "\n"); 1075 } 1076 1077 t = &arg->bundle->ncp.mp.link.throughput; 1078 secs = t->downtime ? 0 : throughput_uptime(t); 1079 if (secs > t->SamplePeriod) 1080 secs = t->SamplePeriod; 1081 if (secs) 1082 prompt_Printf(arg->prompt, "Currently averaging %llu bps (%llu bytes/sec)" 1083 " over the last %d secs\n", t->OctetsPerSecond * 8, 1084 t->OctetsPerSecond, secs); 1085 1086 return 0; 1087} 1088 1089static const char * 1090optval(struct bundle *bundle, int bit) 1091{ 1092 return (bundle->cfg.opt & bit) ? "enabled" : "disabled"; 1093} 1094 1095int 1096bundle_ShowStatus(struct cmdargs const *arg) 1097{ 1098 int remaining; 1099 1100 prompt_Printf(arg->prompt, "Phase %s\n", bundle_PhaseName(arg->bundle)); 1101 prompt_Printf(arg->prompt, " Device: %s\n", arg->bundle->dev.Name); 1102 prompt_Printf(arg->prompt, " Interface: %s @ %lubps", 1103 arg->bundle->iface->name, arg->bundle->bandwidth); 1104 1105 if (arg->bundle->upat) { 1106 int secs = time(NULL) - arg->bundle->upat; 1107 1108 prompt_Printf(arg->prompt, ", up time %d:%02d:%02d", secs / 3600, 1109 (secs / 60) % 60, secs % 60); 1110 } 1111 1112 prompt_Printf(arg->prompt, "\n\nDefaults:\n"); 1113 prompt_Printf(arg->prompt, " Label: %s\n", arg->bundle->cfg.label); 1114 prompt_Printf(arg->prompt, " Auth name: %s\n", 1115 arg->bundle->cfg.auth.name); 1116 1117 prompt_Printf(arg->prompt, " Choked Timer: %ds\n", 1118 arg->bundle->cfg.choked.timeout); 1119 1120#ifndef NORADIUS 1121 radius_Show(&arg->bundle->radius, arg->prompt); 1122#endif 1123 1124 prompt_Printf(arg->prompt, " Idle Timer: "); 1125 if (arg->bundle->cfg.idle.timeout) { 1126 prompt_Printf(arg->prompt, "%ds", arg->bundle->cfg.idle.timeout); 1127 if (arg->bundle->cfg.idle.min_timeout) 1128 prompt_Printf(arg->prompt, ", min %ds", 1129 arg->bundle->cfg.idle.min_timeout); 1130 remaining = bundle_RemainingIdleTime(arg->bundle); 1131 if (remaining != -1) 1132 prompt_Printf(arg->prompt, " (%ds remaining)", remaining); 1133 prompt_Printf(arg->prompt, "\n"); 1134 } else 1135 prompt_Printf(arg->prompt, "disabled\n"); 1136 prompt_Printf(arg->prompt, " MTU: "); 1137 if (arg->bundle->cfg.mtu) 1138 prompt_Printf(arg->prompt, "%d\n", arg->bundle->cfg.mtu); 1139 else 1140 prompt_Printf(arg->prompt, "unspecified\n"); 1141 1142 prompt_Printf(arg->prompt, " sendpipe: "); 1143 if (arg->bundle->ncp.ipcp.cfg.sendpipe > 0) 1144 prompt_Printf(arg->prompt, "%-20ld", arg->bundle->ncp.ipcp.cfg.sendpipe); 1145 else 1146 prompt_Printf(arg->prompt, "unspecified "); 1147 prompt_Printf(arg->prompt, " recvpipe: "); 1148 if (arg->bundle->ncp.ipcp.cfg.recvpipe > 0) 1149 prompt_Printf(arg->prompt, "%ld\n", arg->bundle->ncp.ipcp.cfg.recvpipe); 1150 else 1151 prompt_Printf(arg->prompt, "unspecified\n"); 1152 1153 prompt_Printf(arg->prompt, " Sticky Routes: %-20.20s", 1154 optval(arg->bundle, OPT_SROUTES)); 1155 prompt_Printf(arg->prompt, " ID check: %s\n", 1156 optval(arg->bundle, OPT_IDCHECK)); 1157 prompt_Printf(arg->prompt, " Keep-Session: %-20.20s", 1158 optval(arg->bundle, OPT_KEEPSESSION)); 1159 prompt_Printf(arg->prompt, " Loopback: %s\n", 1160 optval(arg->bundle, OPT_LOOPBACK)); 1161 prompt_Printf(arg->prompt, " PasswdAuth: %-20.20s", 1162 optval(arg->bundle, OPT_PASSWDAUTH)); 1163 prompt_Printf(arg->prompt, " Proxy: %s\n", 1164 optval(arg->bundle, OPT_PROXY)); 1165 prompt_Printf(arg->prompt, " Proxyall: %-20.20s", 1166 optval(arg->bundle, OPT_PROXYALL)); 1167 prompt_Printf(arg->prompt, " Throughput: %s\n", 1168 optval(arg->bundle, OPT_THROUGHPUT)); 1169 prompt_Printf(arg->prompt, " Utmp Logging: %-20.20s", 1170 optval(arg->bundle, OPT_UTMP)); 1171 prompt_Printf(arg->prompt, " Iface-Alias: %s\n", 1172 optval(arg->bundle, OPT_IFACEALIAS)); 1173 1174 return 0; 1175} 1176 1177static void 1178bundle_IdleTimeout(void *v) 1179{ 1180 struct bundle *bundle = (struct bundle *)v; 1181 1182 log_Printf(LogPHASE, "Idle timer expired.\n"); 1183 bundle_StopIdleTimer(bundle); 1184 bundle_Close(bundle, NULL, CLOSE_STAYDOWN); 1185} 1186 1187/* 1188 * Start Idle timer. If timeout is reached, we call bundle_Close() to 1189 * close LCP and link. 1190 */ 1191void 1192bundle_StartIdleTimer(struct bundle *bundle) 1193{ 1194 timer_Stop(&bundle->idle.timer); 1195 if ((bundle->phys_type.open & (PHYS_DEDICATED|PHYS_DDIAL)) != 1196 bundle->phys_type.open && bundle->cfg.idle.timeout) { 1197 int secs; 1198 1199 secs = bundle->cfg.idle.timeout; 1200 if (bundle->cfg.idle.min_timeout > secs && bundle->upat) { 1201 int up = time(NULL) - bundle->upat; 1202 1203 if ((long long)bundle->cfg.idle.min_timeout - up > (long long)secs) 1204 secs = bundle->cfg.idle.min_timeout - up; 1205 } 1206 bundle->idle.timer.func = bundle_IdleTimeout; 1207 bundle->idle.timer.name = "idle"; 1208 bundle->idle.timer.load = secs * SECTICKS; 1209 bundle->idle.timer.arg = bundle; 1210 timer_Start(&bundle->idle.timer); 1211 bundle->idle.done = time(NULL) + secs; 1212 } 1213} 1214 1215void 1216bundle_SetIdleTimer(struct bundle *bundle, int timeout, int min_timeout) 1217{ 1218 bundle->cfg.idle.timeout = timeout; 1219 if (min_timeout >= 0) 1220 bundle->cfg.idle.min_timeout = min_timeout; 1221 if (bundle_LinkIsUp(bundle)) 1222 bundle_StartIdleTimer(bundle); 1223} 1224 1225void 1226bundle_StopIdleTimer(struct bundle *bundle) 1227{ 1228 timer_Stop(&bundle->idle.timer); 1229 bundle->idle.done = 0; 1230} 1231 1232static int 1233bundle_RemainingIdleTime(struct bundle *bundle) 1234{ 1235 if (bundle->idle.done) 1236 return bundle->idle.done - time(NULL); 1237 return -1; 1238} 1239 1240int 1241bundle_IsDead(struct bundle *bundle) 1242{ 1243 return !bundle->links || (bundle->phase == PHASE_DEAD && bundle->CleaningUp); 1244} 1245 1246static struct datalink * 1247bundle_DatalinkLinkout(struct bundle *bundle, struct datalink *dl) 1248{ 1249 struct datalink **dlp; 1250 1251 for (dlp = &bundle->links; *dlp; dlp = &(*dlp)->next) 1252 if (*dlp == dl) { 1253 *dlp = dl->next; 1254 dl->next = NULL; 1255 bundle_LinksRemoved(bundle); 1256 return dl; 1257 } 1258 1259 return NULL; 1260} 1261 1262static void 1263bundle_DatalinkLinkin(struct bundle *bundle, struct datalink *dl) 1264{ 1265 struct datalink **dlp = &bundle->links; 1266 1267 while (*dlp) 1268 dlp = &(*dlp)->next; 1269 1270 *dlp = dl; 1271 dl->next = NULL; 1272 1273 bundle_LinkAdded(bundle, dl); 1274 mp_CheckAutoloadTimer(&bundle->ncp.mp); 1275} 1276 1277void 1278bundle_CleanDatalinks(struct bundle *bundle) 1279{ 1280 struct datalink **dlp = &bundle->links; 1281 int found = 0; 1282 1283 while (*dlp) 1284 if ((*dlp)->state == DATALINK_CLOSED && 1285 (*dlp)->physical->type & 1286 (PHYS_DIRECT|PHYS_BACKGROUND|PHYS_FOREGROUND)) { 1287 *dlp = datalink_Destroy(*dlp); 1288 found++; 1289 } else 1290 dlp = &(*dlp)->next; 1291 1292 if (found) 1293 bundle_LinksRemoved(bundle); 1294} 1295 1296int 1297bundle_DatalinkClone(struct bundle *bundle, struct datalink *dl, 1298 const char *name) 1299{ 1300 if (bundle2datalink(bundle, name)) { 1301 log_Printf(LogWARN, "Clone: %s: name already exists\n", name); 1302 return 0; 1303 } 1304 1305 bundle_DatalinkLinkin(bundle, datalink_Clone(dl, name)); 1306 return 1; 1307} 1308 1309void 1310bundle_DatalinkRemove(struct bundle *bundle, struct datalink *dl) 1311{ 1312 dl = bundle_DatalinkLinkout(bundle, dl); 1313 if (dl) 1314 datalink_Destroy(dl); 1315} 1316 1317void 1318bundle_SetLabel(struct bundle *bundle, const char *label) 1319{ 1320 if (label) 1321 strncpy(bundle->cfg.label, label, sizeof bundle->cfg.label - 1); 1322 else 1323 *bundle->cfg.label = '\0'; 1324} 1325 1326const char * 1327bundle_GetLabel(struct bundle *bundle) 1328{ 1329 return *bundle->cfg.label ? bundle->cfg.label : NULL; 1330} 1331 1332int 1333bundle_LinkSize() 1334{ 1335 struct iovec iov[SCATTER_SEGMENTS]; 1336 int niov, expect, f; 1337 1338 iov[0].iov_len = strlen(Version) + 1; 1339 iov[0].iov_base = NULL; 1340 niov = 1; 1341 if (datalink2iov(NULL, iov, &niov, SCATTER_SEGMENTS, NULL, NULL) == -1) { 1342 log_Printf(LogERROR, "Cannot determine space required for link\n"); 1343 return 0; 1344 } 1345 1346 for (f = expect = 0; f < niov; f++) 1347 expect += iov[f].iov_len; 1348 1349 return expect; 1350} 1351 1352void 1353bundle_ReceiveDatalink(struct bundle *bundle, int s) 1354{ 1355 char cmsgbuf[sizeof(struct cmsghdr) + sizeof(int) * SEND_MAXFD]; 1356 int niov, expect, f, *fd, nfd, onfd; 1357 struct iovec iov[SCATTER_SEGMENTS]; 1358 struct cmsghdr *cmsg; 1359 struct msghdr msg; 1360 struct datalink *dl; 1361 pid_t pid; 1362 char ack; 1363 1364 log_Printf(LogPHASE, "Receiving datalink\n"); 1365 1366 /* 1367 * Create our scatter/gather array - passing NULL gets the space 1368 * allocation requirement rather than actually flattening the 1369 * structures. 1370 */ 1371 iov[0].iov_len = strlen(Version) + 1; 1372 iov[0].iov_base = NULL; 1373 niov = 1; 1374 if (datalink2iov(NULL, iov, &niov, SCATTER_SEGMENTS, NULL, NULL) == -1) { 1375 log_Printf(LogERROR, "Cannot determine space required for link\n"); 1376 return; 1377 } 1378 1379 /* Allocate the scatter/gather array for recvmsg() */ 1380 for (f = expect = 0; f < niov; f++) { 1381 if ((iov[f].iov_base = malloc(iov[f].iov_len)) == NULL) { 1382 log_Printf(LogERROR, "Cannot allocate space to receive link\n"); 1383 return; 1384 } 1385 expect += iov[f].iov_len; 1386 } 1387 1388 /* Set up our message */ 1389 cmsg = (struct cmsghdr *)cmsgbuf; 1390 cmsg->cmsg_len = sizeof cmsgbuf; 1391 cmsg->cmsg_level = SOL_SOCKET; 1392 cmsg->cmsg_type = 0; 1393 1394 memset(&msg, '\0', sizeof msg); 1395 msg.msg_name = NULL; 1396 msg.msg_namelen = 0; 1397 msg.msg_iov = iov; 1398 msg.msg_iovlen = niov; 1399 msg.msg_control = cmsgbuf; 1400 msg.msg_controllen = sizeof cmsgbuf; 1401 1402 log_Printf(LogDEBUG, "Expecting %d scatter/gather bytes\n", expect); 1403 1404 if ((f = recvmsg(s, &msg, MSG_WAITALL)) != expect) { 1405 if (f == -1) 1406 log_Printf(LogERROR, "Failed recvmsg: %s\n", strerror(errno)); 1407 else 1408 log_Printf(LogERROR, "Failed recvmsg: Got %d, not %d\n", f, expect); 1409 while (niov--) 1410 free(iov[niov].iov_base); 1411 return; 1412 } 1413 1414 if (cmsg->cmsg_level != SOL_SOCKET || cmsg->cmsg_type != SCM_RIGHTS) { 1415 log_Printf(LogERROR, "Recvmsg: no descriptors received !\n"); 1416 while (niov--) 1417 free(iov[niov].iov_base); 1418 return; 1419 } 1420 1421 fd = (int *)(cmsg + 1); 1422 nfd = (cmsg->cmsg_len - sizeof *cmsg) / sizeof(int); 1423 1424 if (nfd < 2) { 1425 log_Printf(LogERROR, "Recvmsg: %d descriptor%s received (too few) !\n", 1426 nfd, nfd == 1 ? "" : "s"); 1427 while (nfd--) 1428 close(fd[nfd]); 1429 while (niov--) 1430 free(iov[niov].iov_base); 1431 return; 1432 } 1433 1434 /* 1435 * We've successfully received one or more open file descriptors 1436 * through our socket 1437 */ 1438 log_Printf(LogDEBUG, "Receiving device descriptor\n"); 1439 1440 if (strncmp(Version, iov[0].iov_base, iov[0].iov_len)) { 1441 log_Printf(LogWARN, "Cannot receive datalink, incorrect version" 1442 " (\"%.*s\", not \"%s\")\n", (int)iov[0].iov_len, 1443 (char *)iov[0].iov_base, Version); 1444 while (nfd--) 1445 close(fd[nfd]); 1446 while (niov--) 1447 free(iov[niov].iov_base); 1448 return; 1449 } 1450 1451 onfd = nfd; /* We've got this many in our array */ 1452 nfd -= 2; /* Don't include p->fd and our reply descriptor */ 1453 niov = 1; /* Skip the version id */ 1454 dl = iov2datalink(bundle, iov, &niov, sizeof iov / sizeof *iov, fd[0], 1455 fd + 2, &nfd); 1456 if (dl) { 1457 pid = getpid(); 1458 write(fd[1], &pid, sizeof pid); /* Please hand me any locks */ 1459 read(fd[1], &ack, 1); /* Thanks (ACK) ! */ 1460 close(fd[1]); 1461 1462 if (nfd) { 1463 log_Printf(LogERROR, "bundle_ReceiveDatalink: Failed to handle %d " 1464 "auxiliary file descriptors (%d remain)\n", onfd, nfd); 1465 datalink_Destroy(dl); 1466 while (nfd--) 1467 close(fd[onfd--]); 1468 close(fd[0]); 1469 } else { 1470 bundle_DatalinkLinkin(bundle, dl); 1471 datalink_AuthOk(dl); 1472 bundle_CalculateBandwidth(dl->bundle); 1473 } 1474 } else { 1475 while (nfd--) 1476 close(fd[onfd--]); 1477 close(fd[0]); 1478 close(fd[1]); 1479 } 1480 1481 free(iov[0].iov_base); 1482} 1483 1484void 1485bundle_SendDatalink(struct datalink *dl, int s, struct sockaddr_un *sun) 1486{ 1487 char cmsgbuf[sizeof(struct cmsghdr) + sizeof(int) * SEND_MAXFD]; 1488 const char *constlock; 1489 char *lock; 1490 struct cmsghdr *cmsg; 1491 struct msghdr msg; 1492 struct iovec iov[SCATTER_SEGMENTS]; 1493 int niov, f, expect, newsid, fd[SEND_MAXFD], nfd, reply[2], got; 1494 pid_t newpid; 1495 1496 log_Printf(LogPHASE, "Transmitting datalink %s\n", dl->name); 1497 1498 /* Record the base device name for a lock transfer later */ 1499 constlock = physical_LockedDevice(dl->physical); 1500 if (constlock) { 1501 lock = alloca(strlen(constlock) + 1); 1502 strcpy(lock, constlock); 1503 } else 1504 lock = NULL; 1505 1506 bundle_LinkClosed(dl->bundle, dl); 1507 bundle_DatalinkLinkout(dl->bundle, dl); 1508 1509 /* Build our scatter/gather array */ 1510 iov[0].iov_len = strlen(Version) + 1; 1511 iov[0].iov_base = strdup(Version); 1512 niov = 1; 1513 nfd = 0; 1514 1515 fd[0] = datalink2iov(dl, iov, &niov, SCATTER_SEGMENTS, fd + 2, &nfd); 1516 1517 if (fd[0] != -1 && socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC, reply) != -1) { 1518 /* 1519 * fd[1] is used to get the peer process id back, then to confirm that 1520 * we've transferred any device locks to that process id. 1521 */ 1522 fd[1] = reply[1]; 1523 1524 nfd += 2; /* Include fd[0] and fd[1] */ 1525 memset(&msg, '\0', sizeof msg); 1526 1527 msg.msg_name = NULL; 1528 msg.msg_namelen = 0; 1529 msg.msg_iov = iov; 1530 msg.msg_iovlen = niov; 1531 msg.msg_control = cmsgbuf; 1532 msg.msg_controllen = sizeof *cmsg + sizeof(int) * nfd; 1533 msg.msg_flags = 0; 1534 1535 cmsg = (struct cmsghdr *)cmsgbuf; 1536 cmsg->cmsg_len = msg.msg_controllen; 1537 cmsg->cmsg_level = SOL_SOCKET; 1538 cmsg->cmsg_type = SCM_RIGHTS; 1539 1540 for (f = 0; f < nfd; f++) 1541 *((int *)(cmsg + 1) + f) = fd[f]; 1542 1543 for (f = expect = 0; f < niov; f++) 1544 expect += iov[f].iov_len; 1545 1546 log_Printf(LogDEBUG, "Sending %d descriptor%s and %d bytes in scatter" 1547 "/gather array\n", nfd, nfd == 1 ? "" : "s", expect); 1548 1549 if ((got = sendmsg(s, &msg, 0)) == -1) 1550 log_Printf(LogERROR, "Failed sendmsg: %s: %s\n", 1551 sun->sun_path, strerror(errno)); 1552 else if (got != expect) 1553 log_Printf(LogERROR, "Failed sendmsg: %s: Only sent %d of %d\n", 1554 sun->sun_path, got, expect); 1555 else { 1556 /* We must get the ACK before closing the descriptor ! */ 1557 int res; 1558 1559 read(reply[0], &newpid, sizeof newpid); 1560 log_Printf(LogDEBUG, "Received confirmation from pid %d\n", (int)newpid); 1561 if (lock && (res = ID0uu_lock_txfr(lock, newpid)) != UU_LOCK_OK) 1562 log_Printf(LogPHASE, "uu_lock_txfr: %s\n", uu_lockerr(res)); 1563 1564 write(reply[1], "!", 1); /* Thanks (ACK) ! */ 1565 } 1566 1567 close(reply[0]); 1568 close(reply[1]); 1569 1570 newsid = Enabled(dl->bundle, OPT_KEEPSESSION) || 1571 tcgetpgrp(fd[0]) == getpgrp(); 1572 while (nfd) 1573 close(fd[--nfd]); 1574 if (newsid) 1575 bundle_setsid(dl->bundle, got != -1); 1576 } 1577 close(s); 1578 1579 while (niov--) 1580 free(iov[niov].iov_base); 1581} 1582 1583int 1584bundle_RenameDatalink(struct bundle *bundle, struct datalink *ndl, 1585 const char *name) 1586{ 1587 struct datalink *dl; 1588 1589 if (!strcasecmp(ndl->name, name)) 1590 return 1; 1591 1592 for (dl = bundle->links; dl; dl = dl->next) 1593 if (!strcasecmp(dl->name, name)) 1594 return 0; 1595 1596 datalink_Rename(ndl, name); 1597 return 1; 1598} 1599 1600int 1601bundle_SetMode(struct bundle *bundle, struct datalink *dl, int mode) 1602{ 1603 int omode; 1604 1605 omode = dl->physical->type; 1606 if (omode == mode) 1607 return 1; 1608 1609 if (mode == PHYS_AUTO && !(bundle->phys_type.all & PHYS_AUTO)) 1610 /* First auto link */ 1611 if (bundle->ncp.ipcp.peer_ip.s_addr == INADDR_ANY) { 1612 log_Printf(LogWARN, "You must `set ifaddr' or `open' before" 1613 " changing mode to %s\n", mode2Nam(mode)); 1614 return 0; 1615 } 1616 1617 if (!datalink_SetMode(dl, mode)) 1618 return 0; 1619 1620 if (mode == PHYS_AUTO && !(bundle->phys_type.all & PHYS_AUTO) && 1621 bundle->phase != PHASE_NETWORK) 1622 /* First auto link, we need an interface */ 1623 ipcp_InterfaceUp(&bundle->ncp.ipcp); 1624 1625 /* Regenerate phys_type and adjust idle timer */ 1626 bundle_LinksRemoved(bundle); 1627 1628 return 1; 1629} 1630 1631void 1632bundle_setsid(struct bundle *bundle, int holdsession) 1633{ 1634 /* 1635 * Lose the current session. This means getting rid of our pid 1636 * too so that the tty device will really go away, and any getty 1637 * etc will be allowed to restart. 1638 */ 1639 pid_t pid, orig; 1640 int fds[2]; 1641 char done; 1642 struct datalink *dl; 1643 1644 orig = getpid(); 1645 if (pipe(fds) == -1) { 1646 log_Printf(LogERROR, "pipe: %s\n", strerror(errno)); 1647 return; 1648 } 1649 switch ((pid = fork())) { 1650 case -1: 1651 log_Printf(LogERROR, "fork: %s\n", strerror(errno)); 1652 close(fds[0]); 1653 close(fds[1]); 1654 return; 1655 case 0: 1656 close(fds[1]); 1657 read(fds[0], &done, 1); /* uu_locks are mine ! */ 1658 close(fds[0]); 1659 if (pipe(fds) == -1) { 1660 log_Printf(LogERROR, "pipe(2): %s\n", strerror(errno)); 1661 return; 1662 } 1663 switch ((pid = fork())) { 1664 case -1: 1665 log_Printf(LogERROR, "fork(2): %s\n", strerror(errno)); 1666 close(fds[0]); 1667 close(fds[1]); 1668 return; 1669 case 0: 1670 close(fds[1]); 1671 bundle_LockTun(bundle); /* update pid */ 1672 read(fds[0], &done, 1); /* uu_locks are mine ! */ 1673 close(fds[0]); 1674 setsid(); 1675 log_Printf(LogPHASE, "%d -> %d: %s session control\n", 1676 (int)orig, (int)getpid(), 1677 holdsession ? "Passed" : "Dropped"); 1678 timer_InitService(0); /* Start the Timer Service */ 1679 break; 1680 default: 1681 close(fds[0]); 1682 /* Give away all our physical locks (to the final process) */ 1683 for (dl = bundle->links; dl; dl = dl->next) 1684 if (dl->state != DATALINK_CLOSED) 1685 physical_ChangedPid(dl->physical, pid); 1686 write(fds[1], "!", 1); /* done */ 1687 close(fds[1]); 1688 _exit(0); 1689 break; 1690 } 1691 break; 1692 default: 1693 close(fds[0]); 1694 /* Give away all our physical locks (to the intermediate process) */ 1695 for (dl = bundle->links; dl; dl = dl->next) 1696 if (dl->state != DATALINK_CLOSED) 1697 physical_ChangedPid(dl->physical, pid); 1698 write(fds[1], "!", 1); /* done */ 1699 close(fds[1]); 1700 if (holdsession) { 1701 int fd, status; 1702 1703 timer_TermService(); 1704 signal(SIGPIPE, SIG_DFL); 1705 signal(SIGALRM, SIG_DFL); 1706 signal(SIGHUP, SIG_DFL); 1707 signal(SIGTERM, SIG_DFL); 1708 signal(SIGINT, SIG_DFL); 1709 signal(SIGQUIT, SIG_DFL); 1710 for (fd = getdtablesize(); fd >= 0; fd--) 1711 close(fd); 1712 /* 1713 * Reap the intermediate process. As we're not exiting but the 1714 * intermediate is, we don't want it to become defunct. 1715 */ 1716 waitpid(pid, &status, 0); 1717 /* Tweak our process arguments.... */ 1718 ID0setproctitle("session owner"); 1719 setuid(geteuid()); 1720 /* 1721 * Hang around for a HUP. This should happen as soon as the 1722 * ppp that we passed our ctty descriptor to closes it. 1723 * NOTE: If this process dies, the passed descriptor becomes 1724 * invalid and will give a select() error by setting one 1725 * of the error fds, aborting the other ppp. We don't 1726 * want that to happen ! 1727 */ 1728 pause(); 1729 } 1730 _exit(0); 1731 break; 1732 } 1733} 1734 1735int 1736bundle_HighestState(struct bundle *bundle) 1737{ 1738 struct datalink *dl; 1739 int result = DATALINK_CLOSED; 1740 1741 for (dl = bundle->links; dl; dl = dl->next) 1742 if (result < dl->state) 1743 result = dl->state; 1744 1745 return result; 1746} 1747 1748int 1749bundle_Exception(struct bundle *bundle, int fd) 1750{ 1751 struct datalink *dl; 1752 1753 for (dl = bundle->links; dl; dl = dl->next) 1754 if (dl->physical->fd == fd) { 1755 datalink_Down(dl, CLOSE_NORMAL); 1756 return 1; 1757 } 1758 1759 return 0; 1760} 1761 1762void 1763bundle_AdjustFilters(struct bundle *bundle, struct in_addr *my_ip, 1764 struct in_addr *peer_ip) 1765{ 1766 filter_AdjustAddr(&bundle->filter.in, my_ip, peer_ip); 1767 filter_AdjustAddr(&bundle->filter.out, my_ip, peer_ip); 1768 filter_AdjustAddr(&bundle->filter.dial, my_ip, peer_ip); 1769 filter_AdjustAddr(&bundle->filter.alive, my_ip, peer_ip); 1770} 1771 1772void 1773bundle_CalculateBandwidth(struct bundle *bundle) 1774{ 1775 struct datalink *dl; 1776 int mtu, sp; 1777 1778 bundle->bandwidth = 0; 1779 mtu = 0; 1780 for (dl = bundle->links; dl; dl = dl->next) 1781 if (dl->state == DATALINK_OPEN) { 1782 if ((sp = dl->mp.bandwidth) == 0 && 1783 (sp = physical_GetSpeed(dl->physical)) == 0) 1784 log_Printf(LogDEBUG, "%s: %s: Cannot determine bandwidth\n", 1785 dl->name, dl->physical->name.full); 1786 else 1787 bundle->bandwidth += sp; 1788 if (!bundle->ncp.mp.active) { 1789 mtu = dl->physical->link.lcp.his_mru; 1790 break; 1791 } 1792 } 1793 1794 if(bundle->bandwidth == 0) 1795 bundle->bandwidth = 115200; /* Shrug */ 1796 1797 if (bundle->ncp.mp.active) 1798 mtu = bundle->ncp.mp.peer_mrru; 1799 else if (!mtu) 1800 mtu = 1500; 1801 1802#ifndef NORADIUS 1803 if (bundle->radius.valid && bundle->radius.mtu && bundle->radius.mtu < mtu) { 1804 log_Printf(LogLCP, "Reducing MTU to radius value %lu\n", 1805 bundle->radius.mtu); 1806 mtu = bundle->radius.mtu; 1807 } 1808#endif 1809 1810 tun_configure(bundle, mtu); 1811} 1812 1813void 1814bundle_AutoAdjust(struct bundle *bundle, int percent, int what) 1815{ 1816 struct datalink *dl, *choice, *otherlinkup; 1817 1818 choice = otherlinkup = NULL; 1819 for (dl = bundle->links; dl; dl = dl->next) 1820 if (dl->physical->type == PHYS_AUTO) { 1821 if (dl->state == DATALINK_OPEN) { 1822 if (what == AUTO_DOWN) { 1823 if (choice) 1824 otherlinkup = choice; 1825 choice = dl; 1826 } 1827 } else if (dl->state == DATALINK_CLOSED) { 1828 if (what == AUTO_UP) { 1829 choice = dl; 1830 break; 1831 } 1832 } else { 1833 /* An auto link in an intermediate state - forget it for the moment */ 1834 choice = NULL; 1835 break; 1836 } 1837 } else if (dl->state == DATALINK_OPEN && what == AUTO_DOWN) 1838 otherlinkup = dl; 1839 1840 if (choice) { 1841 if (what == AUTO_UP) { 1842 log_Printf(LogPHASE, "%d%% saturation -> Opening link ``%s''\n", 1843 percent, choice->name); 1844 datalink_Up(choice, 1, 1); 1845 mp_StopAutoloadTimer(&bundle->ncp.mp); 1846 } else if (otherlinkup) { /* Only bring the second-last link down */ 1847 log_Printf(LogPHASE, "%d%% saturation -> Closing link ``%s''\n", 1848 percent, choice->name); 1849 datalink_Close(choice, CLOSE_STAYDOWN); 1850 mp_StopAutoloadTimer(&bundle->ncp.mp); 1851 } 1852 } 1853} 1854 1855int 1856bundle_WantAutoloadTimer(struct bundle *bundle) 1857{ 1858 struct datalink *dl; 1859 int autolink, opened; 1860 1861 if (bundle->phase == PHASE_NETWORK) { 1862 for (autolink = opened = 0, dl = bundle->links; dl; dl = dl->next) 1863 if (dl->physical->type == PHYS_AUTO) { 1864 if (++autolink == 2 || (autolink == 1 && opened)) 1865 /* Two auto links or one auto and one open in NETWORK phase */ 1866 return 1; 1867 } else if (dl->state == DATALINK_OPEN) { 1868 opened++; 1869 if (autolink) 1870 /* One auto and one open link in NETWORK phase */ 1871 return 1; 1872 } 1873 } 1874 1875 return 0; 1876} 1877