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
 61
 62
 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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
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
578
579
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
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
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
/*
 *  ReactOS Win32 Applications
 *  Copyright (C) 2005 ReactOS Team
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

/*
 * COPYRIGHT:   See COPYING in the top level directory
 * PROJECT:     ReactOS arp utility
 * FILE:        base/applications/network/arp/arp.c
 * PURPOSE:     view and manipulate the ARP cache
 * PROGRAMMERS: Ged Murphy (gedmurphy@gmail.com)
 * REVISIONS:
 *   GM 27/06/05 Created
 *
 */

#define WIN32_NO_STATUS
#include <stdarg.h>
#include <windef.h>
#include <winbase.h>
#include <stdio.h>
#include <stdlib.h>
#include <tchar.h>
#define _INC_WINDOWS
#include <winsock2.h>
#include <iphlpapi.h>

/*
 * Globals
 */
const char SEPARATOR = '-';
int _CRT_glob = 0; // stop * from listing dir files in arp -d *

/*
 * function declarations
 */
DWORD DoFormatMessage(VOID);
DWORD PrintEntries(PMIB_IPNETROW pIpAddRow);
DWORD DisplayArpEntries(PTCHAR pszInetAddr, PTCHAR pszIfAddr);
DWORD Addhost(PTCHAR pszInetAddr, PTCHAR pszEthAddr, PTCHAR pszIfAddr);
DWORD Deletehost(PTCHAR pszInetAddr, PTCHAR pszIfAddr);
VOID Usage(VOID);

/*
 * convert error code into meaningful message
 */
DWORD DoFormatMessage(VOID)
{
    LPTSTR lpMsgBuf;
    DWORD RetVal;

    DWORD ErrorCode = GetLastError();

    if (ErrorCode != ERROR_SUCCESS)
    {
        RetVal = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
                               FORMAT_MESSAGE_FROM_SYSTEM |
                               FORMAT_MESSAGE_IGNORE_INSERTS,
                               NULL,
                               ErrorCode,
                               MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */
                               (LPTSTR) &lpMsgBuf,
                               0,
                               NULL );

        if (RetVal != 0)
        {
            _tprintf(_T("%s"), lpMsgBuf);
            LocalFree(lpMsgBuf);
            /* return number of TCHAR's stored in output buffer
             * excluding '\0' - as FormatMessage does*/
            return RetVal;
        }
    }
    return 0;
}

VOID
PrintMessage(
    DWORD dwMessage)
{
    LPTSTR lpMsgBuf;
    DWORD RetVal;

    RetVal = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
                           FORMAT_MESSAGE_FROM_HMODULE |
                           FORMAT_MESSAGE_IGNORE_INSERTS,
                           GetModuleHandleW(NULL),
                           dwMessage,
                           LANG_USER_DEFAULT,
                           (LPTSTR)&lpMsgBuf,
                           0,
                           NULL);
    if (RetVal != 0)
    {
        _tprintf(_T("%s"), lpMsgBuf);
        LocalFree(lpMsgBuf);
    }
}

VOID
PrintMessageV(
    DWORD dwMessage,
    ...)
{
    LPTSTR lpMsgBuf;
    va_list args = NULL;<--- va_list 'args' used before va_start() was called.
    DWORD RetVal;

    va_start(args, dwMessage);

    RetVal = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_HMODULE,
                           GetModuleHandleW(NULL),
                           dwMessage,
                           LANG_USER_DEFAULT,
                           (LPTSTR)&lpMsgBuf,
                           0,
                           &args);
    va_end(args);

    if (RetVal != 0)
    {
        _tprintf(_T("%s"), lpMsgBuf);
        LocalFree(lpMsgBuf);
    }
}

/*
 *
 * Takes an ARP entry and prints the IP address,
 * the MAC address and the entry type to screen
 *
 */
DWORD PrintEntries(PMIB_IPNETROW pIpAddRow)
{
    IN_ADDR inaddr;
    TCHAR cMacAddr[20];

    /* print IP addresses */
    inaddr.S_un.S_addr = pIpAddRow->dwAddr;
    _tprintf(_T("  %-22s"), inet_ntoa(inaddr));

    /* print MAC address */
    _stprintf(cMacAddr, _T("%02x-%02x-%02x-%02x-%02x-%02x"),
        pIpAddRow->bPhysAddr[0],
        pIpAddRow->bPhysAddr[1],
        pIpAddRow->bPhysAddr[2],
        pIpAddRow->bPhysAddr[3],
        pIpAddRow->bPhysAddr[4],
        pIpAddRow->bPhysAddr[5]);
    _tprintf(_T("%-22s"), cMacAddr);

    /* print cache type */
    switch (pIpAddRow->dwType)
    {
        case MIB_IPNET_TYPE_DYNAMIC:
            PrintMessage(10007);
            break;

        case MIB_IPNET_TYPE_STATIC:
            PrintMessage(10008);
            break;

        case MIB_IPNET_TYPE_INVALID:
            PrintMessage(10006);
            break;

        case MIB_IPNET_TYPE_OTHER:
            PrintMessage(10005);
            break;
    }
    _putts(_T(""));
    return NO_ERROR;
}

/*
 *
 * Takes optional parameters of an internet address and interface address.
 * Retrieve all entries in the ARP cache. If an internet address is
 * specified, display the ARP entry relating to that address. If an
 * interface address is specified, display all entries relating to
 * that interface.
 *
 */
/* FIXME: allow user to specify an interface address, via pszIfAddr */
DWORD DisplayArpEntries(PTCHAR pszInetAddr, PTCHAR pszIfAddr)
{
    DWORD i, k, dwCount;
    PMIB_IPNETTABLE pIpNetTable = NULL;
    PMIB_IPADDRTABLE pIpAddrTable = NULL;
    ULONG Size = 0;
    struct in_addr inaddr, inaddr2;
    PTCHAR pszIpAddr;
    TCHAR szIntIpAddr[20];
    DWORD dwError = NO_ERROR;

    /* retrieve the IP-to-physical address mapping table */

    /* get table size */
    GetIpNetTable(pIpNetTable, &Size, 0);

    /* allocate memory for ARP address table */
    pIpNetTable = (PMIB_IPNETTABLE)HeapAlloc(GetProcessHeap(), 0, Size);
    if (pIpNetTable == NULL)
    {
        PrintMessage(10004);
        dwError = ERROR_NOT_ENOUGH_MEMORY;
        goto cleanup;
    }

    ZeroMemory(pIpNetTable, sizeof(*pIpNetTable));

    dwError = GetIpNetTable(pIpNetTable, &Size, TRUE);
    if (dwError != NO_ERROR)
    {
        _tprintf(_T("GetIpNetTable failed: %lu\n"), dwError);
        DoFormatMessage();
        goto cleanup;
    }

    /* check there are entries in the table */
    if (pIpNetTable->dwNumEntries == 0)
    {
        PrintMessage(10018);
        goto cleanup;
    }

    /* Retrieve the interface-to-ip address mapping
     * table to get the IP address for adapter */

    /* get table size */
    Size = 0;
    GetIpAddrTable(pIpAddrTable, &Size, 0);

    pIpAddrTable = (PMIB_IPADDRTABLE)HeapAlloc(GetProcessHeap(), 0, Size);
    if (pIpAddrTable == NULL)
    {
        PrintMessage(10004);
        dwError = ERROR_NOT_ENOUGH_MEMORY;
        goto cleanup;
    }

    ZeroMemory(pIpAddrTable, sizeof(*pIpAddrTable));

    dwError = GetIpAddrTable(pIpAddrTable, &Size, TRUE);
    if (dwError != NO_ERROR)
    {
        _tprintf(_T("GetIpAddrTable failed: %lu\n"), dwError);
        DoFormatMessage();
        goto cleanup;
    }

    for (k = 0; k < pIpAddrTable->dwNumEntries; k++)
    {
        if (pIpNetTable->table[0].dwIndex == pIpAddrTable->table[k].dwIndex)
        {
            //printf("debug print: pIpAddrTable->table[?].dwIndex = %lx\n", pIpNetTable->table[k].dwIndex);
            inaddr2.s_addr = pIpAddrTable->table[k].dwAddr;
            pszIpAddr = inet_ntoa(inaddr2);
            strcpy(szIntIpAddr, pszIpAddr);
        }
    }

    /* Count relevant ARP entries */
    dwCount = 0;
    for (i = 0; i < pIpNetTable->dwNumEntries; i++)
    {
        /* if the user has supplied their own internet address *
         * only count the arp entry which matches that */
        if (pszInetAddr)
        {
            inaddr.S_un.S_addr = pIpNetTable->table[i].dwAddr;
            pszIpAddr = inet_ntoa(inaddr);

            /* check if it matches, count it */
            if (strcmp(pszIpAddr, pszInetAddr) == 0)
                dwCount++;
        }
        else
        {
            /* if an address is not supplied, count all entries */
            dwCount++;
        }
    }

    /* Print message and leave if there are no relevant ARP entries */
    if (dwCount == 0)
    {
        PrintMessage(10018);
        goto cleanup;
    }

    /* print header, including interface IP address and index number */
    PrintMessageV(10003, szIntIpAddr, pIpNetTable->table[0].dwIndex);

    /* go through all ARP entries */
    for (i = 0; i < pIpNetTable->dwNumEntries; i++)
    {

        /* if the user has supplied their own internet address *
         * only print the arp entry which matches that */
        if (pszInetAddr)
        {
            inaddr.S_un.S_addr = pIpNetTable->table[i].dwAddr;
            pszIpAddr = inet_ntoa(inaddr);

            /* check if it matches, print it */
            if (strcmp(pszIpAddr, pszInetAddr) == 0)
                PrintEntries(&pIpNetTable->table[i]);
        }
        else
            /* if an address is not supplied, print all entries */
            PrintEntries(&pIpNetTable->table[i]);
    }

cleanup:
    if (pIpNetTable != NULL)
        HeapFree(GetProcessHeap(), 0, pIpNetTable);
    if (pIpAddrTable != NULL)
        HeapFree(GetProcessHeap(), 0, pIpAddrTable);

    return dwError;
}

/*
 *
 * Takes an internet address, a MAC address and an optional interface
 * address as arguments and checks their validity.
 * Fill out an MIB_IPNETROW structure and insert the data into the
 * ARP cache as a static entry.
 *
 */
DWORD Addhost(PTCHAR pszInetAddr, PTCHAR pszEthAddr, PTCHAR pszIfAddr)
{
    PMIB_IPNETROW pAddHost = NULL;
    PMIB_IPNETTABLE pIpNetTable = NULL;
    DWORD dwIpAddr = 0;
    ULONG Size = 0;
    INT i, val, c;
    DWORD dwError = NO_ERROR;

    /* error checking */

    /* check IP address */
    if (pszInetAddr == NULL)
    {
        Usage();
        return ERROR_INVALID_PARAMETER;
    }

    dwIpAddr = inet_addr(pszInetAddr);
    if (dwIpAddr == INADDR_NONE)
    {
        PrintMessageV(10001, pszInetAddr);
        return ERROR_INVALID_PARAMETER;
    }

    /* check MAC address */
    if (strlen(pszEthAddr) != 17)
    {
        PrintMessageV(10002, pszEthAddr);
        return ERROR_INVALID_PARAMETER;
    }

    for (i = 0; i < 17; i++)
    {
        if (pszEthAddr[i] == SEPARATOR)
            continue;

        if (!isxdigit(pszEthAddr[i]))
        {
            PrintMessageV(10002, pszEthAddr);
            return ERROR_INVALID_PARAMETER;
        }
    }

    /* We need the IpNetTable to get the adapter index */
    /* Return required buffer size */
    GetIpNetTable(pIpNetTable, &Size, 0);

    /* allocate memory for ARP address table */
    pIpNetTable = (PMIB_IPNETTABLE)HeapAlloc(GetProcessHeap(), 0, Size);
    if (pIpNetTable == NULL)
    {
        PrintMessage(10004);
        dwError = ERROR_NOT_ENOUGH_MEMORY;
        goto cleanup;
    }

    ZeroMemory(pIpNetTable, sizeof(*pIpNetTable));

    dwError = GetIpNetTable(pIpNetTable, &Size, TRUE);
    if (dwError != NO_ERROR)
    {
        _tprintf(_T("GetIpNetTable failed: %lu\n"), dwError);
        DoFormatMessage();
        goto cleanup;
    }

    /* reserve memory on heap and zero */
    pAddHost = (PMIB_IPNETROW)HeapAlloc(GetProcessHeap(), 0, sizeof(MIB_IPNETROW));
    if (pAddHost == NULL)
    {
        PrintMessage(10004);
        dwError = ERROR_NOT_ENOUGH_MEMORY;
        goto cleanup;
    }

    ZeroMemory(pAddHost, sizeof(MIB_IPNETROW));

    /* set dwIndex field to the index of a local IP address to
     * indicate the network on which the ARP entry applies */
    if (pszIfAddr)
    {
        if (sscanf(pszIfAddr, "%lx", &pAddHost->dwIndex) == EOF)
        {
            goto cleanup;
        }
    }
    else
    {
        //printf("debug print: pIpNetTable->table[0].dwIndex = %lx\n", pIpNetTable->table[0].dwIndex);
        /* needs testing. I get the correct index on my machine, but need others
         * to test their card index.  Any problems and we can use GetAdaptersInfo instead */
        pAddHost->dwIndex = pIpNetTable->table[0].dwIndex;
    }

    /* Set MAC address to 6 bytes (typical) */
    pAddHost->dwPhysAddrLen = 6;


    /* Encode bPhysAddr into correct byte array */
    for (i = 0; i < 6; i++)
    {
        val = 0;
        c = toupper(pszEthAddr[i * 3]);
        c = c - (isdigit(c) ? '0' : ('A' - 10));
        val += c;
        val = (val << 4);
        c = toupper(pszEthAddr[i * 3 + 1]);
        c = c - (isdigit(c) ? '0' : ('A' - 10));
        val += c;
        pAddHost->bPhysAddr[i] = (BYTE)val;
    }

    /* copy converted IP address */
    pAddHost->dwAddr = dwIpAddr;


    /* set type to static */
    pAddHost->dwType = MIB_IPNET_TYPE_STATIC;


    /* Add the ARP entry */
    dwError = SetIpNetEntry(pAddHost);
    if (dwError != NO_ERROR)
    {
        DoFormatMessage();
        goto cleanup;
    }

cleanup:
    if (pIpNetTable != NULL)
        HeapFree(GetProcessHeap(), 0, pIpNetTable);
    if (pAddHost != NULL)
        HeapFree(GetProcessHeap(), 0, pAddHost);

    return dwError;
}

/*
 *
 * Takes an internet address and an optional interface address as
 * arguments and checks their validity.
 * Add the interface number and IP to an MIB_IPNETROW structure
 * and remove the entry from the ARP cache.
 *
 */
DWORD Deletehost(PTCHAR pszInetAddr, PTCHAR pszIfAddr)
{
    PMIB_IPNETROW pDelHost = NULL;
    PMIB_IPNETTABLE pIpNetTable = NULL;
    ULONG Size = 0;
    DWORD dwIpAddr = 0;
    BOOL bFlushTable = FALSE;
    DWORD dwError = NO_ERROR;

    /* error checking */

    /* check IP address */
    if (pszInetAddr == NULL)
    {
        Usage();
        return ERROR_INVALID_PARAMETER;
    }

    /* if wildcard is given, set flag to delete all hosts */
    if (strncmp(pszInetAddr, "*", 1) == 0)
    {
        bFlushTable = TRUE;
    }
    else
    {
        dwIpAddr = inet_addr(pszInetAddr);
        if (dwIpAddr == INADDR_NONE)
        {
            PrintMessageV(10001, pszInetAddr);
            return ERROR_INVALID_PARAMETER;
        }
    }

    /* We need the IpNetTable to get the adapter index */
    /* Return required buffer size */
    GetIpNetTable(NULL, &Size, 0);

    /* allocate memory for ARP address table */
    pIpNetTable = (PMIB_IPNETTABLE) HeapAlloc(GetProcessHeap(), 0, Size);
    if (pIpNetTable == NULL)
    {
        PrintMessage(10004);
        dwError = ERROR_NOT_ENOUGH_MEMORY;
        goto cleanup;
    }

    ZeroMemory(pIpNetTable, sizeof(*pIpNetTable));

    dwError = GetIpNetTable(pIpNetTable, &Size, TRUE);
    if (dwError != NO_ERROR)
    {
        _tprintf(_T("GetIpNetTable failed: %lu\n"), dwError);
        DoFormatMessage();
        goto cleanup;
    }

    /* reserve memory on heap and zero */
    pDelHost = (MIB_IPNETROW *)HeapAlloc(GetProcessHeap(), 0, sizeof(MIB_IPNETROW));
    if (pDelHost == NULL)
    {
        PrintMessage(10004);
        dwError = ERROR_NOT_ENOUGH_MEMORY;
        goto cleanup;
    }

    ZeroMemory(pDelHost, sizeof(MIB_IPNETROW));

    /* set dwIndex field to the index of a local IP address to
     * indicate the network on which the ARP entry applies */
    if (pszIfAddr)
    {
        if (sscanf(pszIfAddr, "%lx", &pDelHost->dwIndex) == EOF)
        {
            goto cleanup;
        }
    }
    else
    {
        /* needs testing. I get the correct index on my machine, but need others
         * to test their card index. Any problems and we can use GetAdaptersInfo instead */
        pDelHost->dwIndex = pIpNetTable->table[0].dwIndex;
    }

    if (bFlushTable != FALSE)
    {
        /* delete arp cache */
        dwError = FlushIpNetTable(pDelHost->dwIndex);
        if (dwError != NO_ERROR)
        {
            DoFormatMessage();
            goto cleanup;
        }
    }
    else
    {
        /* copy converted IP address */
        pDelHost->dwAddr = dwIpAddr;

        /* Delete the ARP entry */
        dwError = DeleteIpNetEntry(pDelHost);
        if (dwError != NO_ERROR)
        {
            DoFormatMessage();
            goto cleanup;
        }
    }

cleanup:
    if (pIpNetTable != NULL)
        HeapFree(GetProcessHeap(), 0, pIpNetTable);
    if (pDelHost != NULL)
        HeapFree(GetProcessHeap(), 0, pDelHost);

    return dwError;
}

/*
 *
 * print program usage to screen
 *
 */
VOID Usage(VOID)
{
    PrintMessage(10000);
}

/*
 *
 * Program entry.
 * Parse command line and call the required function
 *
 */
INT main(int argc, char* argv[])
{
    DWORD dwError = NO_ERROR;

    if ((argc < 2) || (argc > 5))
    {
       Usage();
       return EXIT_FAILURE;
    }

    if (argv[1][0] != '-')
    {
        Usage();
        return EXIT_SUCCESS;
    }

    switch (argv[1][1])
    {
        case 'a': /* fall through */
        case 'g':
            if (argc == 2)
                dwError = DisplayArpEntries(NULL, NULL);
            else if (argc == 3)
                dwError = DisplayArpEntries(argv[2], NULL);
            else if ((argc == 4) && ((strcmp(argv[2], "-N")) == 0))
                dwError = DisplayArpEntries(NULL, argv[3]);
            else if ((argc == 5) && ((strcmp(argv[3], "-N")) == 0))
                dwError = DisplayArpEntries(argv[2], argv[4]);
            else
            {
                Usage();
                dwError = ERROR_INVALID_PARAMETER;
            }
            break;

        case 'd':
            if (argc == 3)
                dwError = Deletehost(argv[2], NULL);
            else if (argc == 4)
                dwError = Deletehost(argv[2], argv[3]);
            else
            {
                Usage();
                dwError = ERROR_INVALID_PARAMETER;
            }
            break;

        case 's':
            if (argc == 4)
                dwError = Addhost(argv[2], argv[3], NULL);
            else if (argc == 5)
                dwError = Addhost(argv[2], argv[3], argv[4]);
            else
            {
                Usage();
                dwError = ERROR_INVALID_PARAMETER;
            }
            break;

        default:
            Usage();
            dwError = ERROR_INVALID_PARAMETER;
            break;
    }

    return (dwError == NO_ERROR) ? EXIT_SUCCESS : EXIT_FAILURE;
}