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