NBIP 50.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
/* Copyright 1998 Acorn Computers Ltd
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/*
*
*  NBIP.C  -- NetBIOS-over-IP implementation
*
*  13-12-95 INH  Original
*  30-12-96 INH  Completed
*
*
*  This file is an implementation of the name service and session
*  service functions for a B (broadcast) node, as defined in
*  RFC1001-1002. It does the following things:
*
*   - locates remote NetBIOS names (i.e. finds IP addresses for them)
*   - maintains & defends local NetBIOS names
*   - establishes sessions with remote hosts & sends & receives data
*      using these sessions.
*
*  We also do a few M-node functions, if a name server is specified
*   by giving its IP address in LanMan$NameServer. This consists
*   largely of sending name registrations, releases, find requests
*   and status requests to the name server as well as to broadcast.
*/

/* Standard includes */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include "kernel.h"
#include "os.h"
#include "swis.h"

/* Our includes */

#include "stdtypes.h"
#include "lanman.h"
#include "buflib.h"
#include "tcpip.h"

#include "netbios.h"
#include "xlate.h"    /* For string functions */
#include "stats.h"
#include "lmvars.h"
#include "nbip.h"

Stewart Brodie's avatar
Stewart Brodie committed
61 62
#include "LanMan_MH.h"

63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150
#define EXPORT static


/* Our definitions ------------------ */

#define EventV         0x10

#define INVALID_SOCKET (-1)

#define MAX_NAMES     (MAX_DRIVES+4)
#define MAX_SESSIONS  (MAX_DRIVES+4)

#define RECV_TIMEOUT  3000 /* Wait time for general receives, in .01s */

/* Time to live values */
#define FIND_TTL     300000
#define REGISTER_TTL 300000


/* Definitions for status field */

#define NAME_FREE       0
#define LCL_AWAIT_ADD   1  /* Local name awaiting registration */
#define LCL_NAME_OK     2  /* Valid local name */
#define LCL_IN_CONFLICT 3  /* Local name in conflict */
#define LCL_AWAIT_RLSE  4  /* Local name about to be released */
#define RMT_AWAIT_FIND  5  /* Remote name currently being searched for */
#define RMT_FOUND       6  /* Remote name, found OK */
#define RMT_CACHED      7  /* Remote name which may be dropped from table */
#define RMT_STATUS_Q    8  /* Remote name doing a status query */

/* ---------------- */

struct status_resp  /* Structure used to process STATUS_RESPOMSE */
{
  int    nt_search;           /* Name-type to respond to */
  struct FindName_res *pRes;  /* Pointer to result buf */
  int    spaces_left;         /* Space left in result buf */
};

/* ----------- */

/* We keep both our own names and some remote names in the table,
   to act as a name-to-IP-address cache. Remote names can (and will)
   be chucked out without warning.
*/

typedef struct
{
  int status;

  NETNAME nn;    /* 16-byte NetBIOS name */
  int nbflags;  /* Group status & node type */

  uint TTL_StartTime;  /* Time at which a valid 'time to live' was
       		       	    received */
  uint TTL_Interval;   /* Time to live, in centiseconds */

  struct in_addr IPaddress; /* IP address of this name */
  struct status_resp *pStatResp;  /* Pointer to result buf */
}
  NAME_ENTRY;

/* ----------- */


/* Globals ============================================================= */

static NAME_ENTRY NB_NameTable[MAX_NAMES];
static int        NB_FirstFreeName;
static struct in_addr NB_IPAddress;

#define SCOPE_ID_MAX 80
static BYTE   NB_ScopeID[SCOPE_ID_MAX];
                          /* NetBIOS Scope ID, in compressed format */
static int    NB_ScopeIDlen; /* Length, including terminating zero */

static BYTE   DatagramBuf[576];
static int    NBNS_Socket = INVALID_SOCKET;
                      /* Socket for NBNS server on this machine */
static int    NBNS_RequestCount;

static struct sockaddr *NBNS_Broadcast; /* Ready-made broadcast address */
static struct sockaddr *NBNS_NameServer = NULL; /* IP address of name server */

/* NetBIOS name basics ==================================== */

#ifdef DEBUG
151
static char *debug_name_buf ( void *pnn_v, char *buf )
152
{
153 154 155 156 157 158 159 160 161 162 163 164
  BYTE *pnn = pnn_v;
  char lbuf[16];
  memcpy(lbuf, pnn, 16);
  lbuf[15] = '\0';
  sprintf(buf, "<%s[%02X]>", lbuf, pnn[15]);
  return buf;
}

static char *debug_name ( void *pnn )
{
  static char lclbuf[32];
  return debug_name_buf(pnn, lclbuf);
165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241
}

static void debug_scope ( BYTE *src )
{
  int i;

  if ( *src == 0 )
    return;

  while ( *src != 0 )
  {
    i = *src;
    if ( i >= 0xC0 )
    {
      printf("->pointer");
      break;
    }
    if ( i >= 0x40 )
    {
      printf("->invalid");
      break;
    }
    printf(".");
    src++;
    while ( i-- > 0 ) printf("%c", *src++);
  }
}
#else
#define debug_name(a)
#define debug_scope(a)
#endif

static void show_scope ( BYTE *src )
{
  int i;

  if ( *src == 0 )
  {
    printf("  No NetBIOS scope ID set\n");
    return;
  }

  printf("  NetBIOS scope ID is '");
  while ( *src != 0 )
  {
    i = *src;
    if ( i >= 0x40 )
    {
      printf("(oops)");
      break;
    }
    src++;
    while ( i-- > 0 ) printf("%c", *src++);
    if ( *src != 0 ) printf(".");
  }
  printf("'\n");
}

/* NETNAME management ==================================== */

EXPORT bool _NB_MatchName ( NETNAME *nn1, NETNAME *nn2 )
{
  return (bool) ( nn1->c4[0] == nn2->c4[0] &&
           nn1->c4[1] == nn2->c4[1] &&
           nn1->c4[2] == nn2->c4[2] &&
           nn1->c4[3] == nn2->c4[3] );
}

/* --------------------- */

EXPORT err_t _NB_FormatName ( nametype_t nt, char *name, NETNAME *res )
{
  int i;

  for ( i=0; i<15; i++)
  {
    if ( name[i] <= 0x20 ) break;
Stewart Brodie's avatar
Stewart Brodie committed
242 243
    if (name[i] == '\xA0') res->b[i] = ' ';
    else res->b[i] = toupper(name[i]);
244 245 246 247 248 249 250 251 252 253 254 255 256 257
  }

  while (i<15)
    res->b[i++] = 0x20;

  res->b[15] = nt;
  return OK;
}

/* --------------------- */

EXPORT nametype_t _NB_DecodeName ( NETNAME *pnn, char *buf )
{
  BYTE *p = pnn->b;
Stewart Brodie's avatar
Stewart Brodie committed
258 259
  char *last_nonsp = buf;
  int i;
260

Stewart Brodie's avatar
Stewart Brodie committed
261
  for (i=0; i<15 && *p >= 0x20; ++i)
262 263 264 265
    *buf++ = *p++;

  *buf = 0;

Stewart Brodie's avatar
Stewart Brodie committed
266 267 268 269
  while (--buf > last_nonsp) {
    if (*buf == ' ') *buf = 0;
  }

270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
  return (nametype_t) (pnn->b[15]);
}

/* -------------------- */

static uint NB_GetTime (void)
{
  /* This is well-defined for RISCOS */
  return * (uint *)0x10C;
}


/* NAME_ENTRY management ============================= */

static void FreeNameEntry ( NAME_ENTRY *p )
{
  int n;
  p->status = NAME_FREE;
  n = p - NB_NameTable;

  if (NB_FirstFreeName > n)
    NB_FirstFreeName = n;
}

/* ------------------ */

static void CheckExpiredNames ( void )
{
  int i;
  NAME_ENTRY *pNE;

  pNE = NB_NameTable;
  for ( i=0; i < MAX_NAMES; i++ )
  {
    if ( pNE->status == RMT_CACHED              &&
         (NB_GetTime() - pNE->TTL_StartTime) > pNE->TTL_Interval )
    {
      FreeNameEntry(pNE);
    }
  }
}

/* ------------------ */

static NAME_ENTRY *AllocNameEntry (int stat)
{
  int i;

  CheckExpiredNames(); /* Make some space if possible */

  for ( i=NB_FirstFreeName; i < MAX_NAMES; i++)
    if ( NB_NameTable[i].status == NAME_FREE )
    {
      NB_NameTable[i].status = stat;
      NB_FirstFreeName = i+1;
      return &NB_NameTable[i];
    }

  /* No more space. Chuck out the first cached remote name we find */

  for ( i=0; i < MAX_NAMES; i++ )
    if ( NB_NameTable[i].status == RMT_CACHED )
    {
      NB_FirstFreeName = i+1;
      NB_NameTable[i].status = stat;
      return &NB_NameTable[i];
    }

  return NULL;
}

/* --------------- */

static NAME_ENTRY *FindNameEntry ( NETNAME *pNN )
{
  int i;
  NAME_ENTRY *pNE;
  pNE = NB_NameTable;

  for ( i=0; i < MAX_NAMES; i++ )
  {
    if ( pNE->status != NAME_FREE )
    {
      if ( _NB_MatchName ( pNN, &(pNE->nn) ) )
        return pNE;
    }
    pNE++;
  }

  return NULL;
}

/* NBNS Subroutines ================================= */

/* Struct in_addr's always contain addresses in network byte order, so
   the integer value of the s_addr field, as perceived by C, will vary
   between big-endian and little-endian implementations. Hence, we have
   to phrase our routines in such a way that they are independent of
   the endian-ness (preferably by not treating struct in_addr as an
   integer value at all). The union below helps */

union in_addr_byte
{
  struct in_addr ina;
  BYTE   nb[4];
};

/* ------------------- */

static struct sockaddr_in NameServer_sin;

static void SetupNameServer ( void )
{
  if (NBNS_NameServer == NULL)
  {
    char *ns_addr = getenv("LanMan$NameServer");
    union in_addr_byte iab;
    int b0, b1, b2, b3;

    if ((ns_addr == NULL) || (sscanf(ns_addr, "%d.%d.%d.%d",&b0, &b1, &b2, &b3) != 4))
    {
      b0 = RdCMOS(NBNSIPCMOS0);
      b1 = RdCMOS(NBNSIPCMOS1);
      b2 = RdCMOS(NBNSIPCMOS2);
      b3 = RdCMOS(NBNSIPCMOS3);
    }
    if ( ((b0 != 0) && (b0 != 127) && (b0 <= 223))  &&  ((b3 != 0) && (b3 != 255)) )
    {
      iab.nb[0]=b0, iab.nb[1] = b1, iab.nb[2] = b2, iab.nb[3] = b3;
      NameServer_sin.sin_family = AF_INET;
      NameServer_sin.sin_port   = htons(NBNS_PORT);
      NameServer_sin.sin_addr   = iab.ina;
      NBNS_NameServer = (struct sockaddr *) &NameServer_sin;
    }
  }
}

/* ----------------- */


/* Given a scope ID (e.g. "netbios.ibm.com"), converts this to the
   NBNS compacted format.
*/

static void SetScopeID ( char *src )
{
  int i, l;
  char *p;

  if ( src==NULL) src = "";

  NB_ScopeIDlen=0;

  /* Get number of characters to next dot, or if no more dots, to end
     of string. If it's too long, it gets rudely truncated! */

  do
  {
    p = strchr(src, '.');  /* Find '.' */
    if (p == NULL)         /* Last bit */
      l = strlen(src);
    else
      l = p-src;           /* Length to dot */

    if ( l == 0  /* No more */ ||
         l >= 64 /* Illegal */ ||
         NB_ScopeIDlen+l+1 >= SCOPE_ID_MAX )
      break;

    NB_ScopeID [NB_ScopeIDlen++] = l;
    for ( i=0; i<l; i++ )
      NB_ScopeID [NB_ScopeIDlen++] = toupper(*src++);
    src++; /* Skip 'dot' if present */
  }
    while ( p != NULL );

  NB_ScopeID [NB_ScopeIDlen] = 0;
  NB_ScopeIDlen++;
}

/* ---------------------------------------- */

static uint GetLong( BYTE *p)
{
  return (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
}

/* ---------- */

static BYTE *PutLong ( BYTE *ptr, uint v )
{
  *ptr++ = (v >> 24);
  *ptr++ = (v >> 16);
  *ptr++ = (v >> 8);
  *ptr++ = v;
  return ptr;
}

/* ---------- */


static struct in_addr GetIPAddr( BYTE *p)
{
  union in_addr_byte ib;
  ib.nb[0] = p[0];
  ib.nb[1] = p[1];
  ib.nb[2] = p[2];
  ib.nb[3] = p[3];
  return ib.ina;
}

/* ---------- */

static BYTE *PutIPAddr ( BYTE *ptr, struct in_addr ia )
{
  union in_addr_byte ib;
  ib.ina = ia;
  *ptr++ = ib.nb[0];
  *ptr++ = ib.nb[1];
  *ptr++ = ib.nb[2];
  *ptr++ = ib.nb[3];
  return ptr;
}

/* ------------- */

static uint GetShort( BYTE *p)
{
  return (p[0] << 8) | p[1];
}

/* ------------- */

static BYTE *PutShort ( BYTE *ptr, uint v )
{
  *ptr++ = (v >> 8);
  *ptr++ = v;
  return ptr;
}

/* --------------- */

static BYTE *PutNetname ( BYTE *ptr, NETNAME *pNN )
{
  /* Put NetBIOS name in a compressed ASCII-coded representation */
  int i,c;
  BYTE *p;

  p = pNN->b; /* Pointer to first part of name */

  *ptr++ = 32;   /* This is always 32 characters */

  for (i=0; i<16; i++)
  {
    c = *p++;
    *ptr++ = 'A' + ((c >> 4) & 0xF);
    *ptr++ = 'A' + (c & 0xF);
  }

  memcpy ( ptr, NB_ScopeID, NB_ScopeIDlen );
  return ptr + NB_ScopeIDlen;
}

/* --------------- */

static BYTE *PutNetnameIndirect ( BYTE *ptr, BYTE *name,
				BYTE *buf_start )
{
  int c = name-buf_start;

  if ( c > 0 && c <= 0x3FFF )
    ptr=PutShort(ptr, c|0xC000 );
  else
  {
    STAT(STA_SERIOUS_BARF);
    *ptr++ = 0;
  }

  return ptr;
}

/* -------------- */

static BYTE *PutResourceInfo ( BYTE *p, NAME_ENTRY *pNE, uint ttl )
{
  p = PutLong ( p, ttl );
  p = PutShort ( p, 0x0006 );  /* 6 extra data bytes */
  p = PutShort ( p, pNE->nbflags );
  return PutIPAddr ( p, pNE->IPaddress );
}

/* -------------- */

static BYTE *CreateNBNSheader(BYTE *ptr, int opcode, int trn_ID )
{
  /* Creates an NBNS header */
  ptr = PutShort(ptr, trn_ID);  /* Create new request ID */
  ptr = PutShort(ptr, opcode & 0xFFFF);
  ptr = PutShort(ptr, (opcode & HAS_QUERY) ? 1 : 0);
  ptr = PutShort(ptr, (opcode & HAS_ANSWER) ? 1 : 0);
  ptr = PutShort(ptr, (opcode & HAS_AUTHORITY) ? 1 : 0);
  return PutShort(ptr, (opcode & HAS_ADDITIONAL) ? 1 : 0);
}

/* Transmit routines ============================================ */

static void SendDatagram ( struct sockaddr *pDst, BYTE *start, BYTE *end )
{
578 579
  dprintf((__FILE__, "SendDatagram ID:&%04x to %s\n", GetShort(start),
    inet_ntoa(((struct sockaddr_in *) pDst)->sin_addr)));
580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629
  sendto ( NBNS_Socket, start, end-start, 0, pDst,
               sizeof(struct sockaddr_in) );
}

/* --------------------- */

static void SendRegisterRequest ( struct sockaddr *pDst, NAME_ENTRY *pNE )
{
  BYTE *p, *name_p;

  p = CreateNBNSheader(DatagramBuf, NAME_REG_REQUEST, ++NBNS_RequestCount);
  name_p = p;
  p = PutNetname( p, &(pNE->nn) );  /* Query section */
  p = PutLong (p, INET_NAME_TAG );
  /* Resource section, using a name pointer */
  p = PutNetnameIndirect ( p, name_p, DatagramBuf );
  p = PutLong (p, INET_NAME_TAG );
  p = PutResourceInfo (p, pNE, REGISTER_TTL );

  SendDatagram ( pDst, DatagramBuf, p );
}

/* --------------------- */

static void SendReleaseRequest ( struct sockaddr *pDst, NAME_ENTRY *pNE )
{
  BYTE *p, *name_p;

  p = CreateNBNSheader(DatagramBuf, NAME_RLSE_REQUEST, ++NBNS_RequestCount);
  name_p = p;
  p = PutNetname( p, &(pNE->nn) );  /* Query section */
  p = PutLong (p, INET_NAME_TAG );
  /* Resource section, using a name pointer */
  p = PutNetnameIndirect ( p, name_p, DatagramBuf );
  p = PutLong (p, INET_NAME_TAG );
  p = PutResourceInfo (p, pNE, 0 );

  SendDatagram ( pDst, DatagramBuf, p );
}

/* --------------------- */

static void SendFindRequest ( struct sockaddr *pDst, NAME_ENTRY *pNE )
{
  BYTE *p;

  p = CreateNBNSheader(DatagramBuf, NAME_FIND_REQUEST, ++NBNS_RequestCount);
  p = PutNetname( p, &(pNE->nn) );  /* Query section */
  p = PutLong (p, INET_NAME_TAG );

Stewart Brodie's avatar
Stewart Brodie committed
630 631 632 633

#ifdef DEBUG
  {
          struct sockaddr_in *sin = (void *) pDst;
634 635 636
          debug2("SendFindRequest (%s)-> [%s]\n",
            debug_name(&(pNE->nn)),
            inet_ntoa(sin->sin_addr));
Stewart Brodie's avatar
Stewart Brodie committed
637 638
  }
#endif
639 640 641 642 643 644 645 646 647 648 649 650 651
  SendDatagram ( pDst, DatagramBuf, p );
}

/* --------------------- */

static void SendStatusRequest ( struct sockaddr *pDst, NAME_ENTRY *pNE )
{
  BYTE *p;

  p = CreateNBNSheader(DatagramBuf,NAME_STATUS_REQUEST,++NBNS_RequestCount);
  p = PutNetname( p, &(pNE->nn) );  /* Query section */
  p = PutLong (p, INET_STATUS_TAG );

652 653
  dprintf((__FILE__, "SendStatusRequest (%s)\n", debug_name(&(pNE->nn))));

654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758
  SendDatagram ( pDst, DatagramBuf, p );
}

/* Name Decoding subroutines ==================================== */

/* Read RFC-1001 for more info on the bizarre network name
   representation scheme.
*/

static bool ValidateName( BYTE *src, BYTE *buf_start, BYTE *buf_end )
{
  int c, loopy_count;

  loopy_count = 0;

  while( src >= buf_start && src < buf_end && loopy_count++ < 100 )
  {
    c = *src;

    if ( c == 0 )    /* Reached the end without incident */
      return true;
    else if ( c < 0x40 )  /* Ordinary name length segment */
      src += (c+1);
    else if ( c >= 0xC0 ) /* Name pointer */
    {
      if ( src+2 > buf_end ) return false;
      src = buf_start + (GetShort(src) & 0x3FFF);
    }
    else                  /* Invalid */
    {
      debug1("Invalid byte %Xh in name\n", c );
      return false;
    }
  }

  /* Get here if we go wrong somewhere e.g. name is truncated */
  debug0("Invalid name - exceeded length\n");
  return false;
}

/* -------------- */

static BYTE *FindNameEnd ( BYTE *src )
{
  int c;
  while ( c=src[0], c != 0 )
  {
    if ( c >= 0xC0 ) /* Pointer */
      return src+2;
    src += (c+1);
  }
  return src+1;
}

/* --------------------- */


/* ChasePointer is a subroutine for FindNBNSName.
   It keeps following a pointer in an encoded representation to find
   out where it starts.
*/

static BYTE *ChasePointer( BYTE *src, BYTE *buf_start )
{
  while( src[0] >= 0xC0 )
    src = buf_start + (GetShort(src) & 0x3FFF);

  return src;
}


/* FindNBNSName decodes the encoded name representation in NBNS
   packets (dear Anne, why oh why...?) and searches the name table
   for a match. All names of interest are kept in the table, so
   this is the only place that name decoding needs to be done.

   It returns NULL if the name is badly-formed, not found in the
   table, or exceeds the end of the buffer as given by buf_end.

   It should be called only with names which have passed ValidateName(),
   otherwise all sorts may happen.
*/

static NAME_ENTRY *FindNBNSName ( BYTE *src, BYTE *buf_start)
{
  NETNAME netname;
  BYTE *id;
  int i;

  /* Find first bit of name */

  src=ChasePointer(src, buf_start);

  if ( src[0] != 32 )  /* Encoded NetBIOS name is always 32 characters */
    return NULL;

  /* src points to the encoded NetBIOS name - decode it now */

  src++;
  for (i=0; i<16; i++)
  {
    netname.b[i] = ( (src[0] -'A') << 4 ) + src[1] - 'A';
    src+=2;
  }

759
  debug1("Name=%s", debug_name(&netname)); debug_scope (src); debug0("\n");
760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959

  /* Now check NetBIOS scope ID */

  id = NB_ScopeID;

  while (1)
  {
    src = ChasePointer(src, buf_start);
    i = src[0];      /* Length of this segment */
    if ( i != id[0] ) /* Length mismatch */
      return NULL;
    if ( i == 0 )      /* The end */
      break;
    if ( memcmp (src+1, id+1, i) != 0 )
      return NULL;
    src += i+1;
    id  += i+1;
  }

  /* Now check name table */
  return FindNameEntry ( &netname );
}


/* ---------------- */

struct NBNS_packet
{
  struct sockaddr from;
  int   trn_id;     /* Transaction ID */
  int   opcode;     /* Opcode */
  int   n_query;    /* No. of query records */
  int   n_answer;   /* No. of answer records */
  int   n_auth;     /* No. of authority records */
  int   n_add;      /* No. of additional records */
  BYTE *buf_start;  /* Start of raw data */
  BYTE *buf_end;    /* Last byte of raw data plus one */
  BYTE *record_ptr; /* Current record pointer, for GetNextRecord */
};

struct NBNS_resource_record
{
  NAME_ENTRY *pName;
  int  name_tag;
  int  time_to_live;
  int  data_length;
  BYTE *data_ptr;
};

/* ------------------------------- */

#define GET_QUERY    0
#define GET_RESOURCE 1

static bool GetNBNSRecord ( struct NBNS_packet *pNBP,
                          struct NBNS_resource_record *pDst, int flg )
{
  BYTE *src = pNBP->record_ptr;

  /* Name truncated or garbage? */
  if ( !ValidateName(src, pNBP->buf_start, pNBP->buf_end) )
  {
    debug0("Name truncated\n");
    return false;
  }

  /* Is name known to us? */
  pDst->pName = FindNBNSName ( src, pNBP->buf_start );
  if ( pDst->pName == NULL ) debug0("Name unknown to us\n");

  src = FindNameEnd ( src );

  if ( flg & GET_RESOURCE )
  {
    if ( src + 10 > pNBP->buf_end )
    {
      debug0("Resource truncated\n");
      return false;
    }

    pDst->name_tag = GetLong(src);
    pDst->time_to_live = GetLong(src+4);
    pDst->data_length = GetShort(src+8);

    src += 10;
    pDst->data_ptr = src;

    if ( src + pDst->data_length > pNBP->buf_end )
    {
      /* Benign truncation - we give all the data that's available */
      pDst->data_length = pNBP->buf_end - src;
    }

    src += pDst->data_length;
  }
  else
  {
    if ( src + 4 > pNBP->buf_end )
    {
      debug0("Query truncated\n");
      return false;
    }

    pDst->name_tag = GetLong(src);
    pDst->time_to_live = 0;
    pDst->data_length = 0;

    src += 4;
  }

  pNBP->record_ptr = src;
  return true;
}

/* Receive processing routines ======================================= */

static void NameFindRequest ( struct NBNS_packet *pNBP,
                              struct NBNS_resource_record *pNBRR )
{
  NAME_ENTRY *pNE = pNBRR->pName;
  BYTE *p;

  if ( pNE->status == LCL_NAME_OK )
  {
    p = CreateNBNSheader ( DatagramBuf, NAME_FIND_REPLY, pNBP->trn_id );
    p = PutNetname ( p, &(pNE->nn) );
    p = PutLong (p, INET_NAME_TAG );
    p = PutResourceInfo(p, pNE, FIND_TTL);

    sendto ( NBNS_Socket, DatagramBuf, p-DatagramBuf, 0,
               &(pNBP->from), sizeof(pNBP->from) );
  }
}

/* ---------------- */

static void NameRegisterRequest ( struct NBNS_packet *pNBP,
                              struct NBNS_resource_record *pNBRR_query )
{
  NAME_ENTRY *pNE;
  struct NBNS_resource_record NBR_add;
  BYTE *p;

  pNE = pNBRR_query->pName;

  /* Get additional record, containing group status & IP address */

  if ( /* Are all the parameters OK */
       pNE->status != LCL_NAME_OK    ||
       pNBP->n_add < 1              ||
       !GetNBNSRecord( pNBP, &NBR_add, GET_RESOURCE ) ||
       NBR_add.data_length < 6
     )
  {
    return;
  }

  /* Are they both group names? If so, don't worry */

  if ( (GetShort (NBR_add.data_ptr) & NBFLG_GROUP) != 0  &&
       (pNE->nbflags & NBFLG_GROUP)  != 0
     )
  {
    return;
  }

  /* If the IP addresses match, panic not */
  if ( GetIPAddr(NBR_add.data_ptr+2).s_addr == pNE->IPaddress.s_addr )
  {
    return;
  }

  /* Send a negative name registration response with our details */

  p = CreateNBNSheader ( DatagramBuf, NAME_REG_REPLY | ST_ACT_ERR,
                           pNBP->trn_id );
  p = PutNetname ( p, &(pNE->nn) );
  p = PutLong (p, INET_NAME_TAG );
  p = PutResourceInfo(p, pNE, REGISTER_TTL);

  sendto ( NBNS_Socket, DatagramBuf, p-DatagramBuf, 0,
             &(pNBP->from), sizeof(pNBP->from) );

}

/* ---------------------------- */

static void NameFindReply ( struct NBNS_packet *pNBP,
                            struct NBNS_resource_record *pNBRR )
{
  NAME_ENTRY *pNE = pNBRR->pName;
  BYTE *dp = pNBRR->data_ptr;

  /* Are we waiting for a reply? Is this the one? */

  if ( (pNBP->opcode & OPC_STATUS_MASK) == ST_OK &&
       pNE->status == RMT_AWAIT_FIND             &&
       pNBRR->data_length >= 6  /* At least one entry in reply */
     )
  {
Stewart Brodie's avatar
Stewart Brodie committed
960
    debug0("NameFindReply - found\n");
961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007
    pNE->status = RMT_FOUND;
    pNE->nbflags = GetShort(dp);
    pNE->IPaddress = GetIPAddr(dp+2);

    /* Process time-to-live in milliseconds */
    pNE->TTL_StartTime = NB_GetTime();

    if ( pNBRR->time_to_live > 0 )
      pNE->TTL_Interval = pNBRR->time_to_live/10;
    else
      pNE->TTL_Interval = FIND_TTL/10;
  }
}

/* ---------------------------- */

static void NameStatusReply ( struct NBNS_packet *pNBP,
                            struct NBNS_resource_record *pNBRR )
{
  struct status_resp *pSR;
  BYTE *dp;
  int n, flg;

  (void) pNBP; /* Don't use it for now */

  /* Are we waiting for a status reply? */
  dp = pNBRR->data_ptr;
  pSR = pNBRR->pName->pStatResp;

  if ( pSR == NULL ||
       pNBRR->pName->status != RMT_STATUS_Q  ||
       pNBRR->data_length < 1  /* At least one byte for name */
     )
  {
    debug0("Puzzling status response\n");
    return;
  }

  n = *dp++; /* Number of names returned */
  if (n*18 >= pNBRR->data_length)
  {
    n =  (pNBRR->data_length-1) / 18;
  }

  debug3("Status: %d names, type %Xh, %d spc\n", n, pSR->nt_search,
                   pSR->spaces_left);

1008 1009 1010
  ddumpbuf(__FILE__, dp, n*18, 0);


1011 1012
  while( pSR->spaces_left > 0  && n-- > 0 )
  {
1013 1014
    char namebuf[32];
    dprintf((__FILE__, "Found %s\n", debug_name_buf(dp, namebuf)));
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027
    /* dp points to a network name */
    if ( pSR->nt_search == ANY_NAME_TYPE ||
         pSR->nt_search == dp[15] )
    {
      memcpy ( &(pSR->pRes->name), dp, 16 );
      pSR->pRes->type = (nametype_t) (dp[15]);
      flg = GetShort(dp+16);
      pSR->pRes->flags = (flg & NBFLG_GROUP) ? FN_GROUPNAME : 0;
      pSR->spaces_left--;
      pSR->pRes++;
    }
    dp+=18;
  }
1028 1029 1030 1031 1032 1033

  while (n-- > 0)
  {
    debug1("Found but ignoring %s\n", debug_name( dp ));
    dp+=18;
  }
1034 1035 1036
}

/* ---------------------------- */
1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066
#ifdef DEBUG
static void debug_opc(struct NBNS_packet *p)
{
  static const char *statuses[16] = {
    "OK", "FMT_ERR", "SRV_ERR", "NAM_ERR", "IMP_ERR", "RFS_ERR", "ACT_ERR", "CFT_ERR"
  };
  static const char *opcodes[16] = {
    "FIND", "1", "2", "3", "4", "REGISTER", "RELEASE", "WACK", "REFRESH", "9", "10"
  };
  static char flags[256];
  const char *opcode, *status, *reply;

  reply = (p->opcode & OPC_REPLY) ? "Reply" : "Query";
  *flags = '\0';

  if (p->opcode & OPC_AUTHORITY) strcat(flags, "AUTH ");
  if (p->opcode & OPC_TRUNCATED) strcat(flags, "TRUNC ");
  if (p->opcode & OPC_REC_DESIRED) strcat(flags, "REC_DESIRED ");
  if (p->opcode & OPC_REC_AVAIL) strcat(flags, "REC_AVAIL ");
  if (p->opcode & OPC_BROADCAST) strcat(flags, "BROADCAST ");

  opcode = opcodes[(p->opcode & OPC_OPCODE_MASK) >> 11];
  status = (p->opcode & OPC_REPLY) ? statuses[(p->opcode & OPC_STATUS_MASK)] : "";

  dprintf((__FILE__, "* %s ID:&%04x %s %s\n", reply, p->trn_id,
    opcode?opcode:"<UNKNOWN>", status?status:"<UNKNOWN>"));
  dprintf((__FILE__, "n_query: %d, n_answer: %d, n_auth: %d, n_add: %d\n",
    p->n_query, p->n_answer, p->n_auth, p->n_add));
}
#endif
1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096

static void NBNS_ProcessDatagram (
                 struct sockaddr *pFrom, BYTE *buf, int len )
{
  struct NBNS_packet NBP;
  struct NBNS_resource_record NBRR;

#ifdef DEBUG
  {
    struct sockaddr_in *from2 = (struct sockaddr_in *)pFrom;
    debug3("Datagram from inaddr %s, port %d, len %d\n",
            inet_ntoa(from2->sin_addr), ntohs(from2->sin_port), len );
  }
#endif

  if ( len < 12 ) /* Too short for header */
    return;

  NBP.from   = *pFrom;
  NBP.trn_id = GetShort(buf+0);    /* Transaction ID */
  NBP.opcode = GetShort(buf+2);    /* Opcode, status & flags */
  NBP.n_query = GetShort(buf+4);
  NBP.n_answer = GetShort(buf+6);
  NBP.n_auth = GetShort(buf+8);
  NBP.n_add = GetShort(buf+10);

  NBP.buf_start = buf;
  NBP.buf_end = buf+len;
  NBP.record_ptr = buf+12;

1097 1098 1099 1100
#ifdef DEBUG
  debug_opc(&NBP);
#endif

1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198
  if ( NBP.opcode & OPC_REPLY )
  {
    /* Response to one of our questions, either a name registration request,
       or a name query request */

    if ( NBP.n_answer >=1 &&
         GetNBNSRecord( &NBP, &NBRR, GET_RESOURCE ) &&
         NBRR.pName != NULL )
    {
      if ( NBRR.name_tag == INET_NAME_TAG )
      {
        switch ( NBP.opcode & OPC_OPCODE_MASK )
        {
          case OPC_FIND: /* Name find reply */
            NameFindReply ( &NBP, &NBRR );
            break;

          case OPC_REGISTER: /* Name registration reply */
              /* If this is a negative reply, & it's a local name,
                mark it as in-conflict */

            if ((NBP.opcode & OPC_STATUS_MASK) != ST_OK)
            {
              if ( NBRR.pName->status == LCL_AWAIT_ADD ||
                   NBRR.pName->status == LCL_NAME_OK
                 )
              {
                NBRR.pName->status = LCL_IN_CONFLICT;
              }
            }
            break;

          default:
            debug0("Unknown reply\n");
            break;
        }
      }
      else if ( NBRR.name_tag == INET_STATUS_TAG )
      {
        if ( (NBP.opcode & OPC_OPCODE_MASK) == OPC_FIND  &&
             (NBP.opcode & OPC_STATUS_MASK) == ST_OK)
        {
          NameStatusReply ( &NBP, &NBRR );
        }
      }
    }
  }
  else
  {
    /* Request to us from someone else  */

    if ( NBP.n_query >=1 &&
         GetNBNSRecord( &NBP, &NBRR, GET_QUERY ) &&
         NBRR.pName != NULL )
    {
      if ( NBRR.name_tag == INET_NAME_TAG )
        switch ( NBP.opcode & OPC_OPCODE_MASK )
        {
          case OPC_FIND: /* Name find request */
            NameFindRequest ( &NBP, &NBRR );
            break;

          case OPC_REGISTER: /* Name registration request */
            NameRegisterRequest ( &NBP, &NBRR );
            break;

          case OPC_RELEASE: /* Name release request */
            if ( NBRR.pName->status == RMT_CACHED )
              FreeNameEntry ( NBRR.pName );
            break;

          default:
            break;

        }
    }
  }
}


/* Event and callback functions ==================================== */

/* Under RISCOS, background processing is done by having a system
   event - the Internet event - which gets called every time a socket
   receives something (amongst other things). This lets us schedule
   a callback to pick up the data and process it.
*/

extern void EventFn (void);   /* Provided by CMHG */
extern void NBIP_CallbackFn(void);

/* EventFn() ------------------------------------------ */

static bool EventsClaimed=false;
static bool CallbackSet = false;

/* ---------------- */

Stewart Brodie's avatar
Stewart Brodie committed
1199
int EventFn_handler ( _kernel_swi_regs *R, void *pw )
1200 1201 1202 1203 1204 1205 1206 1207 1208
{
  (void) pw;

  if ( R->r[0] == Internet_Event &&
       R->r[2] == NBNS_Socket &&
       !CallbackSet )
  {
    STAT(STA_IP_EVENTS);
    CallbackSet = true;
Stewart Brodie's avatar
Stewart Brodie committed
1209
    _swi(OS_AddCallBack, _INR(0,1), NBIP_CallbackFn, LM_pw);
1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223
  }

  return 1; /* Don't claim, others may wish to know */
}

/* -------------------------------- */

int NBIP_CallbackFn_handler(void)
{
  fd_set read_set;
  struct timeval tv;
  int    len, flen;
  struct sockaddr sa;

Stewart Brodie's avatar
Stewart Brodie committed
1224

1225 1226 1227 1228 1229 1230 1231 1232 1233 1234
  CallbackSet = false;

  while (1) /* Do as many packets as we can */
  {
    tv.tv_sec=0;
    tv.tv_usec=0;

    FD_ZERO(&read_set);
    FD_SET( NBNS_Socket, &read_set );

1235
    if ( select ( NBNS_Socket + 1, &read_set, NULL, NULL, &tv ) == 0 )
1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
      break;

    flen = sizeof(sa);
    len = recvfrom ( NBNS_Socket, DatagramBuf, sizeof(DatagramBuf),
                     0, &sa, &flen );
    if ( len > 0 )
    {
      STAT(STA_IP_RXDGRAM);
      NBNS_ProcessDatagram ( &sa, DatagramBuf, len );
    }
  }

  return 1;
}

Stewart Brodie's avatar
Stewart Brodie committed
1251 1252 1253 1254 1255 1256 1257 1258
int NBIP_CallbackFn_handler_ctrl(_kernel_swi_regs *r, void *pw)
{
  (void) r;
  (void) pw;
  return NBIP_CallbackFn_handler();
}


1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277
/* Exported routines: name service & general =========================== */

/* -------------------- */

/* This function will return a pointer to a NAME_ENTRY structure
   if the name can be found. The status field will be set to RMT_FOUND
   to ensure that the name entry is not disposed of before it can be
   used. After it has been used, it should be set to RMT_CACHED, to
   allow it to be dropped from the table after a while.
*/

static NAME_ENTRY *FindRemoteName ( NETNAME *pnn )
{
  int i;
  uint tstart;
  char plain_name[NAME_LIMIT];
  NAME_ENTRY *pNE;
  struct hostent *pHE;

1278
  debug1("Find remote name %s\n", debug_name(pnn));
1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369

  /* Check name cache */

  CheckExpiredNames();

  pNE = FindNameEntry ( pnn );

  if ( pNE != NULL )  /* Found it */
  {
    if ( pNE->status == RMT_FOUND || pNE->status == RMT_CACHED )
    {
      pNE->status = RMT_FOUND;
      return pNE;
    }
    return NULL;     /* Local name - can't be found */
  }

  /* Try to find it by broadcast, then ask name server */

  pNE = AllocNameEntry(RMT_AWAIT_FIND);
  if ( pNE==NULL )        /* No spaces left */
    return NULL;

  pNE->nn    = *pnn;   /* Copy name */
  pNE->pStatResp = NULL; /* for safety */

  for ( i=3; i>=0; i-- )
  {
    if ( i > 0 )  /* Send 3 broadcasts */
    {
      debug0("Broadcast find request\n");
      SendFindRequest ( NBNS_Broadcast, pNE );
    }
    else          /* Ask name server */
    {
      SetupNameServer();
      if ( NBNS_NameServer == NULL )
        break;
      debug0("Send find request to nameserver\n");
      SendFindRequest ( NBNS_NameServer, pNE );
    }

    tstart = NB_GetTime();
    do
    {
      CollectCallbacks();
      NBIP_CallbackFn_handler();
      if (pNE->status == RMT_FOUND)
      {
        debug1("Name found at %lX\n", pNE->IPaddress.s_addr);
        return pNE;
      }
    }
      while ( (NB_GetTime() - tstart) < 50 );
  }

  /* Still no joy - can we look it up in hosts file? */

  _NB_DecodeName ( pnn, plain_name );
  strcpyn_lower ( plain_name, plain_name, NAME_LIMIT );

  debug0("Looking up name in hosts file\n");

  pHE = gethostbyname ( plain_name );
  if ( pHE != NULL &&
       pHE->h_addr_list != NULL &&
       pHE->h_addr_list[0] != NULL )
  {
    pNE->status = RMT_FOUND;
    pNE->nbflags = NBFLG_UNIQUE | NBFLG_BNODE; /* Don't know - make it up */
    pNE->TTL_StartTime = NB_GetTime();
    pNE->TTL_Interval = 1; /* Doesn't last for long */
    pNE->IPaddress = GetIPAddr ( (BYTE *) (pHE->h_addr_list[0]) );
    debug1("Name found in hosts at %lX\n", pNE->IPaddress.s_addr);
    return pNE;
  }

  FreeNameEntry(pNE);
  return NULL;
}


/* ----------------------- */



static NAME_ENTRY *ValidatehName( hNAME hName )
{
  NAME_ENTRY *pN = (NAME_ENTRY *)hName;
  if ( pN != NULL )
  {
Stewart Brodie's avatar
Stewart Brodie committed
1370
          debug1("Status => %d\n", pN->status);
1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492
    if ( (pN->status == LCL_NAME_OK) || (pN->status == LCL_IN_CONFLICT) )
      return pN;
  }

  return NULL;
}

/* ----------------- */

EXPORT err_t _NB_AddLocalName ( nametype_t nt, char *name, hNAME *phName )
{
  NAME_ENTRY *pNE;
  NETNAME netname;
  int i;
  uint tstart;

  debug1("Add name '%s'\n", name );

  _NB_FormatName ( nt, name, &netname );

  pNE = FindNameEntry ( &netname );
  if ( pNE != NULL )  /* Either local or remote */
    return ENAMEEXISTS;

  pNE = AllocNameEntry(LCL_AWAIT_ADD);
  if ( pNE == NULL )
    return ENOHANDLES;

  pNE->IPaddress = NB_IPAddress;
  pNE->nbflags   = NBFLG_UNIQUE | NBFLG_BNODE;
  pNE->nn = netname;
  pNE->pStatResp = NULL;

  for ( i=3; i >= 0; i-- )  /* 3 opportunities to complain */
  {
    if ( i > 0 ) /* Broadcast 3 times */
    {
      SendRegisterRequest ( NBNS_Broadcast, pNE );
    }
    else /* Then check with the nameserver if present */
    {
      SetupNameServer();
      if ( NBNS_NameServer == NULL )
        break;
      SendRegisterRequest ( NBNS_NameServer, pNE );
    }

    tstart = NB_GetTime();
    do
    {
      CollectCallbacks();
      NBIP_CallbackFn_handler();
      if ( pNE->status == LCL_IN_CONFLICT )  /* Failed */
      {
        FreeNameEntry(pNE);
        return ENAMEEXISTS;
      }
    }
      while ( (NB_GetTime() - tstart) < 50 );
  }

  /* No-one complained */

  pNE->status = LCL_NAME_OK;
  *phName = (hNAME) pNE;
  return OK;
}


/* ----------------------- */

EXPORT err_t _NB_RemoveLocalName ( hNAME hName )
{
  NAME_ENTRY *pNE;
  int i;
  uint tstart;

  pNE = ValidatehName(hName);
  if ( pNE == NULL )
    return EBADPARAM;

  /* Should vape all connections to this name */

  if ( pNE->status != LCL_IN_CONFLICT )
  {
    for ( i=0; i<3; i++ )
    {
      SendReleaseRequest ( NBNS_Broadcast, pNE );
      tstart = NB_GetTime();
      do
      {
        CollectCallbacks();
        NBIP_CallbackFn_handler();
      }
        while ( (NB_GetTime() - tstart) < 50 );
    }

    /* Tell name server if we have one */
    if ( NBNS_NameServer != NULL )
      SendReleaseRequest ( NBNS_NameServer, pNE );
  }

  FreeNameEntry(pNE);
  return OK;
}

/* ----------------------- */

EXPORT int _NB_FindNames ( NETNAME *pnnFind,
                   nametype_t ntFind,
                   struct FindName_res *pResults,
                   int results_max,
                   int timeout )
{
  NAME_ENTRY   *pNE;
  struct status_resp SR;
  uint tstart;

  pNE = AllocNameEntry(RMT_STATUS_Q);
  if ( pNE == NULL )
    return 0;

1493
  debug2("Find name %s type %Xh\n", debug_name(pnnFind), ntFind);
1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583

  SR.nt_search = ntFind;
  SR.pRes = pResults;
  SR.spaces_left = results_max;

  pNE->nn = *pnnFind;
  pNE->pStatResp = &SR;

  /* Try broadcast to start with */
  SendStatusRequest( NBNS_Broadcast, pNE);

  tstart = NB_GetTime();
  do
  {
    CollectCallbacks();
    NBIP_CallbackFn_handler();
  }
    while ( SR.spaces_left > 0 && (NB_GetTime() - tstart) < timeout );

  /* If more to do, ask the name server */

  if ( SR.spaces_left == 0 ) goto search_done;

  SetupNameServer();
  if ( NBNS_NameServer == NULL ) goto search_done;

  SendStatusRequest ( NBNS_NameServer, pNE);

  tstart = NB_GetTime();
  do
  {
    CollectCallbacks();
    NBIP_CallbackFn_handler();
  }
    while ( SR.spaces_left > 0 && (NB_GetTime() - tstart) < timeout );

search_done:
  FreeNameEntry(pNE);
  return results_max - SR.spaces_left;
}


/* Session service *************************************************** */

#define SESS_FREE      0
#define SESS_CONNECTED 1

typedef struct
{
  int status;
  int sid;    /* Socket ID */
  bool LinkOK;
  NAME_ENTRY *lcl_name;
  struct sockaddr_in rmt_addr;
}
  NBIP_SESSION;

static NBIP_SESSION NB_Sessions[MAX_SESSIONS];

/* ------------------------ */

static NBIP_SESSION *AllocSession ( void )
{
  int i;
  for (i=0; i < MAX_SESSIONS; i++)
    if ( NB_Sessions[i].status == SESS_FREE )
      return &NB_Sessions[i];
  return NULL;
}

/* ------------------------ */

static void FreeSession (NBIP_SESSION *pNS)
{
  pNS->status = SESS_FREE;
}

/* ----------------- */

static NBIP_SESSION *ValidatehSession( hSESSION hSess )
{
  NBIP_SESSION *pN = (NBIP_SESSION *)hSess;
  if ( pN != NULL && pN->status == SESS_CONNECTED )
    return pN;

  return NULL;
}

/* ------------------- */

Stewart Brodie's avatar
Stewart Brodie committed
1584
static bool ReadData ( int sid, BYTE *where, int len, uint timeout, int flags )
1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602
{
  uint tstart;
  fd_set read_set;
  struct timeval tv;
  int rdlen;

  tstart = NB_GetTime();

  while ( len > 0 )
  {
    CollectCallbacks();   /* Let IP do its thing */
    NBIP_CallbackFn_handler(); /* Process any datagrams */

    tv.tv_sec=0;
    tv.tv_usec=0;

    FD_ZERO(&read_set);
    FD_SET( sid, &read_set );
Stewart Brodie's avatar
Stewart Brodie committed
1603 1604 1605
    /* SNB: Changed first param to sid+1 - is more efficient as Internet module
     * no longer has to search entire array for set bits */
    if ( select ( sid + 1, &read_set, NULL, NULL, &tv ) != 0 )
1606
    {
Stewart Brodie's avatar
Stewart Brodie committed
1607
      rdlen = recv ( sid, where, len, flags );
1608 1609
      if ( rdlen > 0 )
      {
Stewart Brodie's avatar
Stewart Brodie committed
1610
        if (flags & MSG_PEEK) break;
1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675
        len -= rdlen;
        where += rdlen;
        tstart = NB_GetTime();
        continue;
      }
    }

    if ( NB_GetTime() - tstart > timeout )
    {
      debug0("Timeout\n");
      return false;
    }
  }

  return true;
}

/* --------------- */

static err_t ConnectAttempt ( NBIP_SESSION *pNS, NETNAME *pnnFarEnd )
{
  struct sockaddr_in sa;
  BYTE *p;   uint len;

  debug2("Attempting to connect - addr=%lXh, port %d\n",
     pNS->rmt_addr.sin_addr.s_addr, ntohs(pNS->rmt_addr.sin_port) );

  /* Entered with pNS->sid = a socket descriptor, and pNS->rmt_addr is
     a starting IP address & port number. This should
     attempt to bind(), connect(), then establish a session with
     the far end. Can return ERETARGET with pNS->rmt_addr set to a
     new address, in which case it will get called again with a
     new socket */

  sa.sin_family = AF_INET;
  sa.sin_port   = 0;       /* Alloc a port */
  sa.sin_addr.s_addr = INADDR_ANY;

  if ( bind ( pNS->sid, (struct sockaddr *)&sa, sizeof(sa) ) != 0 )
    return ECREATESOCKET;

  /* Try to connect to remote end */

  if ( connect ( pNS->sid, (struct sockaddr *)(&pNS->rmt_addr),
                     sizeof(pNS->rmt_addr) ) != 0 )
    return ECONNECTSOCKET;

  /* OK, we're connected - try a 'session request' */

  p = DatagramBuf;
  *p++ = NBIP_SESS_REQUEST;
  *p++ = 0; /* Flags */
  p+=2;     /* Skip length for now */
  p = DatagramBuf+4;
  p = PutNetname ( p, pnnFarEnd );  /* Called name */
  p = PutNetname ( p, &(pNS->lcl_name->nn) ); /* Calling name */
  len = p-DatagramBuf;
  PutShort(DatagramBuf+2, len-4);

  if ( send ( pNS->sid, DatagramBuf, len, 0 ) != len )
    return ECONNECTSOCKET;
  debug0("Sent session request: ");

  /* Now get reply */

Stewart Brodie's avatar
Stewart Brodie committed
1676
  if ( !ReadData(pNS->sid, DatagramBuf, 4, RECV_TIMEOUT, 0) )
1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687
    return ETIMEOUT;

  switch ( DatagramBuf[0] )
  {
    case NBIP_SESS_OK: /* Well and good */
      return OK;

    case NBIP_SESS_REJECT:
      return ECONNREJECT;

    case NBIP_SESS_RETARGET:
Stewart Brodie's avatar
Stewart Brodie committed
1688
      if ( !ReadData( pNS->sid, DatagramBuf, 6, RECV_TIMEOUT, 0) )
1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710
        return EDATALEN;
      pNS->rmt_addr.sin_addr = GetIPAddr( DatagramBuf );
      pNS->rmt_addr.sin_port = htons(GetShort( DatagramBuf+4 ));
      debug2("Retargeted to %lXh, port %d\n",
        pNS->rmt_addr.sin_addr.s_addr, ntohs(pNS->rmt_addr.sin_port) );
      return ERETARGET;
  }

  return ECONNECTSOCKET;
}

/* ------------------------ */

EXPORT err_t _NB_OpenSession ( hNAME hLocalName, NETNAME *pnnFarEnd,
                              hSESSION *phSession )
{
  NBIP_SESSION *pNS;
  NAME_ENTRY   *lcl_end, *far_end;
  err_t res;
  int retargets=0;

  /* Check parameters */
Stewart Brodie's avatar
Stewart Brodie committed
1711
  debug0("ValidatehName..\n");
1712 1713 1714 1715 1716
  lcl_end = ValidatehName(hLocalName);
  if ( lcl_end == NULL || lcl_end->status != LCL_NAME_OK )
    return EBADPARAM;

  /* Try to find remote end */
Stewart Brodie's avatar
Stewart Brodie committed
1717
  debug0("FindRemoteName..\n");
1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759
  far_end = FindRemoteName ( pnnFarEnd );
  if ( far_end == NULL )
    return ECANTFINDNAME;

  /* Alloc session details */

  pNS = AllocSession();
  if ( pNS == NULL )
    return ENOHANDLES;

  pNS->lcl_name = lcl_end;
  pNS->rmt_addr.sin_family = AF_INET;
  pNS->rmt_addr.sin_addr   = far_end->IPaddress;
  pNS->rmt_addr.sin_port   = htons(NBIP_SESSION_PORT);
  far_end->status = RMT_CACHED;  /* No longer needed */

  /* Create socket for connection, with retries */
  do
  {
    pNS->sid = socket ( PF_INET, SOCK_STREAM, 0 );
    if ( pNS->sid == INVALID_SOCKET )
    {
      res = ECREATESOCKET;
      break;
    }
    res = ConnectAttempt ( pNS, pnnFarEnd );
    /* May return 'ERETARGET' - this isn't really an error */
    if ( res == OK )
    {
      pNS->status = SESS_CONNECTED;
      pNS->LinkOK = true;
      *phSession = (hSESSION) pNS;
      return OK;
    }
    debug1("ConnectAttempt, error %d\n", res);
    socketclose ( pNS->sid );
  }
    while ( res == ERETARGET && ++retargets < 10 );

  /* Failed - don't even keep the remote name's IP address in cache */
  FreeSession(pNS);
  FreeNameEntry ( far_end );
Stewart Brodie's avatar
Stewart Brodie committed
1760
  debug1("NB_OpenSession(IP) returning (res=%d)\n", res);
1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867
  return res;
}


/* ----------------------- */

#define IOV_MAX 4

EXPORT err_t _NB_SendData ( hSESSION hS, BUFCHAIN Data )
{
  NBIP_SESSION *pNS;
  BYTE hdr[4];
  int  i, len;
  struct GBP_in_out GBP;
  struct iovec iov[IOV_MAX];

  len = ChainLen(Data);
  if ( len >= 0x20000 )
  {
    FreeChain(Data);
    return EDATALEN;
  }

  pNS = ValidatehSession(hS);
  if ( pNS == NULL )
  {
    FreeChain(Data);
    return EBADPARAM;
  }

  PutLong( hdr, len | (NBIP_SESS_DATA << 24) );

  /* We could just send the header. Instead, adding it to the chain
     gives better performance */

  GBP.pChain = Data = AddChain(Data, hdr, 4);
  if (Data == NULL)
    return ENOBUFS;

  do
  {
    i=len=0;
    while (i<IOV_MAX && GetBlockPointer(&GBP) )
    {
      iov[i].iov_base = (char *)GBP.pBlock;
      iov[i].iov_len = GBP.BlockLen;
      len+=GBP.BlockLen;
      i++;
    }

    if ( socketwritev(pNS->sid, iov, i) != len )
    {
      FreeChain(Data);
      pNS->LinkOK = false;
      return ELINKFAILED;
    }
  }
    while ( i==IOV_MAX );

  CollectCallbacks();
  FreeChain(Data);
  return OK;
}

/* ----------------------- */

EXPORT err_t _NB_SendBlockData ( hSESSION hS, BYTE *where, int datalen )
{
  NBIP_SESSION *pNS;
  BYTE hdr[4];
  err_t res;
  struct iovec iov[2];

  while ( datalen > 0x10000 ) /* Max 64K in one go */
  {
    res = _NB_SendBlockData ( hS, where, 0x10000 );
    if ( res != OK )
      return res;
    where += 0x10000;
    datalen -= 0x10000;
  }

  pNS = ValidatehSession(hS);
  if ( pNS == NULL )
    return EBADPARAM;

  /* Send header */
  PutLong( hdr, datalen | (NBIP_SESS_DATA << 24) );
  iov[0].iov_base = (char *)hdr;
  iov[0].iov_len  = 4;
  iov[1].iov_base = (char *) where;
  iov[1].iov_len  = datalen;

  if ( socketwritev ( pNS->sid, iov, 2 ) != (datalen+4) )
  {
    pNS->LinkOK = false;
    return ELINKFAILED;
  }

  CollectCallbacks();
  return OK;
}

/* ----------------------- */

EXPORT err_t _NB_ClearRxQueue ( hSESSION hS )
{
Stewart Brodie's avatar
Stewart Brodie committed
1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880
#ifdef LONGNAMES
  NBIP_SESSION *pNS;
  BYTE buf[4];

  pNS = ValidatehSession(hS);
  if ( pNS == NULL )
    return EBADPARAM;
  if ( !ReadData(pNS->sid, buf, 4, 0, MSG_PEEK) )
  {
    return OK;
  }
  return ERXNOTREADY;
#endif
1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903
  (void) hS;
  /* ClearRxQueue - not needed? !! */
  return OK;
}

/* ----------------------- */

EXPORT err_t _NB_GetData ( hSESSION hS, BUFCHAIN *pOutData, int timeout )
{
  BUFCHAIN Chain;
  struct GBP_in_out GBP;
  NBIP_SESSION *pNS;
  BYTE hdr[4];
  uint  len;

  debug0(" Rd");

  pNS = ValidatehSession(hS);
  if ( pNS == NULL )
    return EBADPARAM;

  /* Get header */
retry:
Stewart Brodie's avatar
Stewart Brodie committed
1904
  if ( !ReadData(pNS->sid, hdr, 4, timeout, 0) )
1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925
  {
    pNS->LinkOK = false;
    return ETIMEOUT;
  }

  len = GetLong(hdr);
  if ( (len >> 24) != NBIP_SESS_DATA ) /* Keepalive packet? */
  {
    debug1("  Packet header %Xh", len);
    goto retry;
  }

  len &= 0x1FFFF; /* Max 128K of data */
  Chain = AllocBlankChain(len);
  if ( Chain == NULL )
    return ENOBUFS;

  GBP.pChain = Chain;

  while ( GetBlockPointer(&GBP) )
  {
Stewart Brodie's avatar
Stewart Brodie committed
1926
    if ( !ReadData(pNS->sid, GBP.pBlock, GBP.BlockLen, timeout, 0) )
1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956
    {
      pNS->LinkOK = false;
      FreeChain(Chain);
      return ETIMEOUT;
    }
  }

  debug1("=%d\n", len);

  *pOutData = Chain;
  return OK;
}

/* ----------------------- */

EXPORT err_t _NB_GetBlockData ( hSESSION hS, BYTE *where, int *len_in_out,
                                                  int timeout )
{
  NBIP_SESSION *pNS;
  BYTE hdr[4];
  uint  len;

  debug0(" RdB");

  pNS = ValidatehSession(hS);
  if ( pNS == NULL )
    return EBADPARAM;

  /* Get header */
retry:
Stewart Brodie's avatar
Stewart Brodie committed
1957
  if ( !ReadData(pNS->sid, hdr, 4, timeout, 0) )
1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970
  {
    pNS->LinkOK = false;
    return ETIMEOUT;
  }

  len = GetLong(hdr);
  if ( (len >> 24) != NBIP_SESS_DATA ) /* Keepalive packet? */
  {
    debug1("Packet header %Xh", len);
    goto retry;
  }

  len &= 0x1FFFF; /* Max 128K of data */