move network tools

svn path=/trunk/; revision=21020
This commit is contained in:
Ged Murphy
2006-02-16 23:25:46 +00:00
parent a5c746a592
commit c64c0eda5f
126 changed files with 27767 additions and 0 deletions
+621
View File
@@ -0,0 +1,621 @@
/*
* 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS arp utility
* FILE: apps/utils/net/arp/arp.c
* PURPOSE: view and manipulate the ARP cache
* PROGRAMMERS: Ged Murphy ([email protected])
* REVISIONS:
* GM 27/06/05 Created
*
*/
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <tchar.h>
#include <string.h>
#include <ctype.h>
#include <winsock2.h>
#include <iphlpapi.h>
#define UNICODE
#define _UNICODE
/*
* Globals
*/
const char SEPERATOR = '-';
int _CRT_glob = 0; // stop * from listing dir files in arp -d *
/*
* function declerations
*/
DWORD DoFormatMessage(VOID);
INT PrintEntries(PMIB_IPNETROW pIpAddRow);
INT DisplayArpEntries(PTCHAR pszInetAddr, PTCHAR pszIfAddr);
INT Addhost(PTCHAR pszInetAddr, PTCHAR pszEthAddr, PTCHAR pszIfAddr);
INT Deletehost(PTCHAR pszInetAddr, PTCHAR pszIfAddr);
VOID Usage(VOID);
/*
* convert error code into meaningful message
*/
DWORD DoFormatMessage(VOID)
{
LPVOID 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"), (LPTSTR)lpMsgBuf);
LocalFree(lpMsgBuf);
/* return number of TCHAR's stored in output buffer
* excluding '\0' - as FormatMessage does*/
return RetVal;
}
}
return 0;
}
/*
*
* Takes an ARP entry and prints the IP address,
* the MAC address and the entry type to screen
*
*/
INT 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 : _tprintf(_T("dynamic\n"));
break;
case MIB_IPNET_TYPE_STATIC : _tprintf(_T("static\n"));
break;
case MIB_IPNET_TYPE_INVALID : _tprintf(_T("invalid\n"));
break;
case MIB_IPNET_TYPE_OTHER : _tprintf(_T("other\n"));
break;
}
return EXIT_SUCCESS;
}
/*
*
* 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 */
INT DisplayArpEntries(PTCHAR pszInetAddr, PTCHAR pszIfAddr)
{
INT iRet;
UINT i, k;
PMIB_IPNETTABLE pIpNetTable = NULL;
PMIB_IPADDRTABLE pIpAddrTable = NULL;
DWORD Size = 0;
struct in_addr inaddr, inaddr2;
PTCHAR pszIpAddr;
TCHAR szIntIpAddr[20];
/* 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)
goto cleanup;
ZeroMemory(pIpNetTable, sizeof(*pIpNetTable));
iRet = GetIpNetTable(pIpNetTable, &Size, TRUE);
if (iRet != NO_ERROR)
{
_tprintf(_T("failed to allocate memory for GetIpNetTable\n"));
DoFormatMessage();
goto cleanup;
}
/* check there are entries in the table */
if (pIpNetTable->dwNumEntries == 0)
{
_tprintf(_T("No ARP entires found\n"));
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 = (MIB_IPADDRTABLE *) HeapAlloc(GetProcessHeap(), 0, Size);
if (pIpAddrTable == NULL)
goto cleanup;
ZeroMemory(pIpAddrTable, sizeof(*pIpAddrTable));
iRet = GetIpAddrTable(pIpAddrTable, &Size, TRUE);
if (iRet != NO_ERROR)
{
_tprintf(_T("GetIpAddrTable failed: %d\n"), iRet);
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);
}
}
/* print header, including interface IP address and index number */
_tprintf(_T("\nInterface: %s --- 0x%lx \n"), szIntIpAddr, pIpNetTable->table[0].dwIndex);
_tprintf(_T(" Internet Address Physical Address Type\n"));
/* go through all ARP entries */
for (i=0; i < pIpNetTable->dwNumEntries; i++)
{
/* if the user has supplied their own internet addesss *
* 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]);
}
return EXIT_SUCCESS;
cleanup:
if (pIpNetTable != NULL)
HeapFree(GetProcessHeap(), 0, pIpNetTable);
if (pIpAddrTable != NULL)
HeapFree(GetProcessHeap(), 0, pIpAddrTable);
return EXIT_FAILURE;
}
/*
*
* 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.
*
*/
INT Addhost(PTCHAR pszInetAddr, PTCHAR pszEthAddr, PTCHAR pszIfAddr)
{
PMIB_IPNETROW pAddHost = NULL;
PMIB_IPNETTABLE pIpNetTable = NULL;
DWORD dwIpAddr = 0;
ULONG Size = 0;
INT iRet, i, val, c;
/* error checking */
/* check IP address */
if (pszInetAddr != NULL)
{
if ((dwIpAddr = inet_addr(pszInetAddr)) == INADDR_NONE)
{
_tprintf(_T("ARP: bad IP address: %s\n"), pszInetAddr);
return EXIT_FAILURE;
}
}
else
{
Usage();
return EXIT_FAILURE;
}
/* check MAC address */
if (strlen(pszEthAddr) != 17)
{
_tprintf(_T("ARP: bad argument: %s\n"), pszEthAddr);
return EXIT_FAILURE;
}
for (i=0; i<17; i++)
{
if (pszEthAddr[i] == SEPERATOR)
continue;
if (!isxdigit(pszEthAddr[i]))
{
_tprintf(_T("ARP: bad argument: %s\n"), pszEthAddr);
return EXIT_FAILURE;
}
}
/* 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)
goto cleanup;
ZeroMemory(pIpNetTable, sizeof(*pIpNetTable));
iRet = GetIpNetTable(pIpNetTable, &Size, TRUE);
if (iRet != NO_ERROR)
{
_tprintf(_T("failed to allocate memory for GetIpNetTable\n"));
DoFormatMessage();
goto cleanup;
}
/* reserve memory on heap and zero */
pAddHost = (MIB_IPNETROW *) HeapAlloc(GetProcessHeap(), 0, sizeof(MIB_IPNETROW));
if (pAddHost == NULL)
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 */
if ((iRet = SetIpNetEntry(pAddHost)) != NO_ERROR)
{
DoFormatMessage();
goto cleanup;
}
HeapFree(GetProcessHeap(), 0, pAddHost);
return EXIT_SUCCESS;
cleanup:
if (pIpNetTable != NULL)
HeapFree(GetProcessHeap(), 0, pIpNetTable);
if (pAddHost != NULL)
HeapFree(GetProcessHeap(), 0, pAddHost);
return EXIT_FAILURE;
}
/*
*
* 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.
*
*/
INT Deletehost(PTCHAR pszInetAddr, PTCHAR pszIfAddr)
{
PMIB_IPNETROW pDelHost = NULL;
PMIB_IPNETTABLE pIpNetTable = NULL;
DWORD Size = 0;
DWORD dwIpAddr = 0;
INT iRet;
BOOL bFlushTable = FALSE;
/* error checking */
/* check IP address */
if (pszInetAddr != NULL)
{
/* if wildcard is given, set flag to delete all hosts */
if (strncmp(pszInetAddr, "*", 1) == 0)
bFlushTable = TRUE;
else if ((dwIpAddr = inet_addr(pszInetAddr)) == INADDR_NONE)
{
_tprintf(_T("ARP: bad IP address: %s\n"), pszInetAddr);
exit(EXIT_FAILURE);
}
}
else
{
Usage();
exit(EXIT_FAILURE);
}
/* 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)
goto cleanup;
ZeroMemory(pIpNetTable, sizeof(*pIpNetTable));
iRet = GetIpNetTable(pIpNetTable, &Size, TRUE);
if (iRet != NO_ERROR)
{
_tprintf(_T("failed to allocate memory for GetIpNetTable\n"));
DoFormatMessage();
goto cleanup;
}
/* reserve memory on heap and zero */
pDelHost = (MIB_IPNETROW *) HeapAlloc(GetProcessHeap(), 0, sizeof(MIB_IPNETROW));
if (pDelHost == NULL)
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 == TRUE)
{
/* delete arp cache */
if ((iRet = FlushIpNetTable(pDelHost->dwIndex)) != NO_ERROR)
{
DoFormatMessage();
goto cleanup;
}
else
{
HeapFree(GetProcessHeap(), 0, pDelHost);
return EXIT_SUCCESS;
}
}
else
/* copy converted IP address */
pDelHost->dwAddr = dwIpAddr;
/* Add the ARP entry */
if ((iRet = DeleteIpNetEntry(pDelHost)) != NO_ERROR)
{
DoFormatMessage();
goto cleanup;
}
HeapFree(GetProcessHeap(), 0, pDelHost);
return EXIT_SUCCESS;
cleanup:
if (pIpNetTable != NULL)
HeapFree(GetProcessHeap(), 0, pIpNetTable);
if (pDelHost != NULL)
HeapFree(GetProcessHeap(), 0, pDelHost);
return EXIT_FAILURE;
}
/*
*
* print program usage to screen
*
*/
VOID Usage(VOID)
{
_tprintf(_T("\nDisplays and modifies the IP-to-Physical address translation tables used by\n"
"address resolution protocol (ARP).\n"
"\n"
"ARP -s inet_addr eth_addr [if_addr]\n"
"ARP -d inet_addr [if_addr]\n"
"ARP -a [inet_addr] [-N if_addr]\n"
"\n"
" -a Displays current ARP entries by interrogating the current\n"
" protocol data. If inet_addr is specified, the IP and Physical\n"
" addresses for only the specified computer are displayed. If\n"
" more than one network interface uses ARP, entries for each ARP\n"
" table are displayed.\n"
" -g Same as -a.\n"
" inet_addr Specifies an internet address.\n"
" -N if_addr Displays the ARP entries for the network interface specified\n"
" by if_addr.\n"
" -d Deletes the host specified by inet_addr. inet_addr may be\n"
" wildcarded with * to delete all hosts.\n"
" -s Adds the host and associates the Internet address inet_addr\n"
" with the Physical address eth_addr. The Physical address is\n"
" given as 6 hexadecimal bytes separated by hyphens. The entry\n"
" is permanent.\n"
" eth_addr Specifies a physical address.\n"
" if_addr If present, this specifies the Internet address of the\n"
" interface whose address translation table should be modified.\n"
" If not present, the first applicable interface will be used.\n"
"Example:\n"
" > arp -s 157.55.85.212 00-aa-00-62-c6-09 .... Adds a static entry.\n"
" > arp -a .... Displays the arp table.\n\n"));
}
/*
*
* Program entry.
* Parse command line and call the required function
*
*/
INT main(int argc, char* argv[])
{
if ((argc < 2) || (argc > 5))
{
Usage();
return EXIT_FAILURE;
}
if (argv[1][0] == '-')
{
switch (argv[1][1])
{
case 'a': /* fall through */
case 'g':
if (argc == 2)
DisplayArpEntries(NULL, NULL);
else if (argc == 3)
DisplayArpEntries(argv[2], NULL);
else if ((argc == 4) && ((strcmp(argv[2], "-N")) == 0))
DisplayArpEntries(NULL, argv[3]);
else if ((argc == 5) && ((strcmp(argv[3], "-N")) == 0))
DisplayArpEntries(argv[2], argv[4]);
else
Usage();
return EXIT_FAILURE;
break;
case 'd': if (argc == 3)
Deletehost(argv[2], NULL);
else if (argc == 4)
Deletehost(argv[2], argv[3]);
else
Usage();
return EXIT_FAILURE;
break;
case 's': if (argc == 4)
Addhost(argv[2], argv[3], NULL);
else if (argc == 5)
Addhost(argv[2], argv[3], argv[4]);
else
Usage();
return EXIT_FAILURE;
break;
default:
Usage();
return EXIT_FAILURE;
}
}
else
Usage();
return EXIT_SUCCESS;
}
+5
View File
@@ -0,0 +1,5 @@
#define REACTOS_STR_FILE_DESCRIPTION "ReactOS TCP/IPv4 Win32 arp\0"
#define REACTOS_STR_INTERNAL_NAME "arp\0"
#define REACTOS_STR_ORIGINAL_FILENAME "arp.exe\0"
#define REACTOS_STR_ORIGINAL_COPYRIGHT "Ged Murphy ([email protected])\0"
#include <reactos/version.rc>
+11
View File
@@ -0,0 +1,11 @@
<module name="arp" type="win32cui" installbase="system32" installname="arp.exe">
<include base="arp">.</include>
<define name="__USE_W32API" />
<library>kernel32</library>
<library>iphlpapi</library>
<library>ws2_32</library>
<library>shlwapi</library>
<file>arp.c</file>
<file>arp.rc</file>
</module>
@@ -0,0 +1,30 @@
<directory name="arp">
<xi:include href="arp/arp.xml" />
</directory>
<directory name="finger">
<xi:include href="finger/finger.xml" />
</directory>
<directory name="ftp">
<xi:include href="ftp/ftp.xml" />
</directory>
<directory name="ipconfig">
<xi:include href="ipconfig/ipconfig.xml" />
</directory>
<directory name="netstat">
<xi:include href="netstat/netstat.xml" />
</directory>
<directory name="ping">
<xi:include href="ping/ping.xml" />
</directory>
<directory name="route">
<xi:include href="route/route.xml" />
</directory>
<directory name="telnet">
<xi:include href="telnet/telnet.xml" />
</directory>
<directory name="tracert">
<xi:include href="tracert/tracert.xml" />
</directory>
<directory name="whois">
<xi:include href="whois/whois.xml" />
</directory>
@@ -0,0 +1,23 @@
July 22, 1999
To All Licensees, Distributors of Any Version of BSD:
As you know, certain of the Berkeley Software Distribution ("BSD") source code files
require that further distributions of products containing all or portions of the
software, acknowledge within their advertising materials that such products contain
software developed by UC Berkeley and its contributors.
Specifically, the provision reads:
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
Effective immediately, licensees and distributors are no longer required to include
the acknowledgement within advertising materials. Accordingly, the foregoing paragraph
of those BSD Unix files containing it is hereby deleted in its entirety.
William Hoskins
Director, Office of Technology Licensing
University of California, Berkeley "
+138
View File
@@ -0,0 +1,138 @@
/*-
* Copyright (c) 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#if defined(LIBC_SCCS) && !defined(lint)
static char sccsid[] = "@(#)err.c 8.1 (Berkeley) 6/4/93";
#endif /* LIBC_SCCS and not lint */
#include "err.h"
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef __STDC__
#include <stdarg.h>
#else
#include <varargs.h>
#endif
extern char *__progname; /* Program name, from crt0. */
void
err(int eval, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
verr(eval, fmt, ap);
va_end(ap);
}
void
verr(int eval, const char *fmt, va_list ap)
{
int sverrno;
sverrno = errno;
(void)fprintf(stderr, "%s: ", __progname);
if (fmt != NULL) {
(void)vfprintf(stderr, fmt, ap);
(void)fprintf(stderr, ": ");
}
(void)fprintf(stderr, "%s\n", strerror(sverrno));
exit(eval);
}
void
errx(int eval, const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
verrx(eval, fmt, ap);
va_end(ap);
}
void
verrx(int eval, const char *fmt, va_list ap)
{
(void)fprintf(stderr, "%s: ", __progname);
if (fmt != NULL)
(void)vfprintf(stderr, fmt, ap);
(void)fprintf(stderr, "\n");
exit(eval);
}
void
warn(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vwarn(fmt, ap);
va_end(ap);
}
void
vwarn(fmt, ap)
const char *fmt;
va_list ap;
{
int sverrno;
sverrno = errno;
(void)fprintf(stderr, "%s: ", __progname);
if (fmt != NULL) {
(void)vfprintf(stderr, fmt, ap);
(void)fprintf(stderr, ": ");
}
(void)fprintf(stderr, "%s\n", strerror(sverrno));
}
void
warnx(const char *fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vwarnx(fmt, ap);
va_end(ap);
}
void
vwarnx(fmt, ap)
const char *fmt;
va_list ap;
{
(void)fprintf(stderr, "%s: ", __progname);
if (fmt != NULL)
(void)vfprintf(stderr, fmt, ap);
(void)fprintf(stderr, "\n");
}
@@ -0,0 +1,60 @@
/*-
* Copyright (c) 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* @(#)err.h 8.1 (Berkeley) 6/2/93
*/
#ifndef _ERR_H_
#define _ERR_H_
/*
* Don't use va_list in the err/warn prototypes. Va_list is typedef'd in two
* places (<machine/varargs.h> and <machine/stdarg.h>), so if we include one
* of them here we may collide with the utility's includes. It's unreasonable
* for utilities to have to include one of them to include err.h, so we get
* _BSD_VA_LIST_ from <machine/ansi.h> and use it.
*/
/*#include <machine/ansi.h>*/
/*#include <sys/cdefs.h>*/
#include "various.h"
#include <stdarg.h>
void err __P((int, const char *, ...));
void verr __P((int, const char *, va_list));
void errx __P((int, const char *, ...));
void verrx __P((int, const char *, va_list));
void warn __P((const char *, ...));
void vwarn __P((const char *, va_list));
void warnx __P((const char *, ...));
void vwarnx __P((const char *, va_list));
#endif /* !_ERR_H_ */
@@ -0,0 +1,178 @@
/*
* Copyright (c) 1989, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Tony Nardo of the Johns Hopkins University/Applied Physics Lab.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* 8/2/97 - Ted Felix <[email protected]>
* Ported to Win32 from 4.4BSD-LITE2 at wcarchive.
* NT Workstation already has finger, and it runs fine under
* Win95. Thought I'd do this anyways since not everyone has
* access to NT.
* Had to remove local handling. Otherwise, same as whois.
*/
/*
* Finger prints out information about users. It is not portable since
* certain fields (e.g. the full user name, office, and phone numbers) are
* extracted from the gecos field of the passwd file which other UNIXes
* may not have or may use for other things.
*
* There are currently two output formats; the short format is one line
* per user and displays login name, tty, login time, real name, idle time,
* and office location/phone number. The long format gives the same
* information (in a more legible format) as well as home directory, shell,
* mail info, and .plan/.project files.
*/
#include <winsock2.h>
#include "err.h"
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "various.h"
#include "getopt.h"
char *__progname;
time_t now;
int lflag, mflag, pplan, sflag;
static void userlist(int, char **);
void usage();
int
main(int argc, char **argv)
{
int ch;
while ((ch = getopt(argc, argv, "lmps")) != EOF)
switch(ch) {
case 'l':
lflag = 1; /* long format */
break;
case 'm':
mflag = 1; /* force exact match of names */
break;
case 'p':
pplan = 1; /* don't show .plan/.project */
break;
case 's':
sflag = 1; /* short format */
break;
case '?':
default:
(void)fprintf(stderr,
"usage: finger [-lmps] login [...]\n");
exit(1);
}
argc -= optind;
argv += optind;
(void)time(&now);
if (!*argv) {
usage();
} else {
userlist(argc, argv);
/*
* Assign explicit "large" format if names given and -s not
* explicitly stated. Force the -l AFTER we get names so any
* remote finger attempts specified won't be mishandled.
*/
if (!sflag)
lflag = 1; /* if -s not explicit, force -l */
}
return 0;
}
static void
userlist(int argc, char **argv)
{
int *used;
char **ap, **nargv, **np, **p;
WORD wVersionRequested;
WSADATA wsaData;
int iErr;
if ((nargv = malloc((argc+1) * sizeof(char *))) == NULL ||
(used = calloc(argc, sizeof(int))) == NULL)
err(1, NULL);
/* Pull out all network requests into nargv. */
for (ap = p = argv, np = nargv; *p; ++p)
if (index(*p, '@'))
*np++ = *p;
else
*ap++ = *p;
*np++ = NULL;
*ap++ = NULL;
/* If there are local requests */
if (*argv)
{
fprintf(stderr, "Warning: Can't do local finger\n");
}
/* Start winsock */
wVersionRequested = MAKEWORD( 1, 1 );
iErr = WSAStartup( wVersionRequested, &wsaData );
if ( iErr != 0 )
{
/* Tell the user that we couldn't find a usable */
/* WinSock DLL. */
fprintf(stderr, "WSAStartup failed\n");
return;
}
/* Handle network requests. */
for (p = nargv; *p;)
netfinger(*p++);
/* Bring down winsock */
WSACleanup();
exit(0);
}
void usage()
{
(void)fprintf(stderr,
"usage: finger [-lmps] login [...]\n");
exit(1);
}
@@ -0,0 +1,6 @@
/* $Id$ */
#define REACTOS_STR_FILE_DESCRIPTION "ReactOS TCP/IPv4 Win32 finger\0"
#define REACTOS_STR_INTERNAL_NAME "finger\0"
#define REACTOS_STR_ORIGINAL_FILENAME "finger.exe\0"
#include <reactos/version.rc>
@@ -0,0 +1,12 @@
<module name="finger" type="win32cui" installbase="system32" installname="finger.exe">
<include base="finger">.</include>
<define name="__USE_W32API" />
<define name="__USE_W32_SOCKETS" />
<library>kernel32</library>
<library>ws2_32</library>
<file>finger.c</file>
<file>err.c</file>
<file>getopt.c</file>
<file>net.c</file>
<file>finger.rc</file>
</module>
@@ -0,0 +1,122 @@
/*
* Copyright (c) 1987 Regents of the University of California.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* Fri Jun 13 10:39:00 1997, [email protected]:
* Ported to Win32, changed index/rindex to strchr/strrchr
*/
#if defined(LIBC_SCCS) && !defined(lint)
static char sccsid[] = "@(#)getopt.c 4.13 (Berkeley) 2/23/91";
#endif /* LIBC_SCCS and not lint */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "getopt.h"
/*
* get option letter from argument vector
*/
int opterr = 1, /* if error message should be printed */
optind = 1, /* index into parent argv vector */
optopt; /* character checked for validity */
const char *optarg; /* argument associated with option */
#define BADCH (int)'?'
#define EMSG ""
int
getopt(int nargc, char * const *nargv, const char *ostr)
{
static const char *place = EMSG; /* option letter processing */
register char *oli; /* option letter list index */
char *p;
if (!*place) { /* update scanning pointer */
if (optind >= nargc || *(place = nargv[optind]) != '-') {
place = EMSG;
return(EOF);
}
if (place[1] && *++place == '-') { /* found "--" */
++optind;
place = EMSG;
return(EOF);
}
} /* option letter okay? */
if ((optopt = (int)*place++) == (int)':' ||
!(oli = strchr(ostr, optopt))) {
/*
* if the user didn't specify '-' as an option,
* assume it means EOF.
*/
if (optopt == (int)'-')
return(EOF);
if (!*place)
++optind;
if (opterr) {
if (!(p = strrchr(*nargv, '/')))
p = *nargv;
else
++p;
(void)fprintf(stderr, "%s: illegal option -- %c\n",
p, optopt);
}
return(BADCH);
}
if (*++oli != ':') { /* don't need argument */
optarg = NULL;
if (!*place)
++optind;
}
else { /* need an argument */
if (*place) /* no white space */
optarg = place;
else if (nargc <= ++optind) { /* no arg */
place = EMSG;
if (!(p = strrchr(*nargv, '/')))
p = *nargv;
else
++p;
if (opterr)
(void)fprintf(stderr,
"%s: option requires an argument -- %c\n",
p, optopt);
return(BADCH);
}
else /* white space */
optarg = nargv[optind];
place = EMSG;
++optind;
}
return(optopt); /* dump back option letter */
}
@@ -0,0 +1,7 @@
/* getopt.h */
extern const char *optarg;
extern int optind;
int
getopt(int nargc, char * const *nargv, const char *ostr);
+139
View File
@@ -0,0 +1,139 @@
/*
* Copyright (c) 1989, 1993
* The Regents of the University of California. All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Tony Nardo of the Johns Hopkins University/Applied Physics Lab.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <sys/types.h>
#include <winsock2.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include "various.h"
int close(int);
void
netfinger(char *name)
{
extern int lflag;
char c, lastc;
struct in_addr defaddr;
struct hostent *hp, def;
struct servent *sp;
struct sockaddr_in sin;
SOCKET s;
char *alist[1], *host;
/* If this is a local request */
if (!(host = rindex(name, '@')))
return;
*host++ = '\0';
if (isdigit(*host) && (defaddr.s_addr = inet_addr(host)) != (unsigned long)-1) {
def.h_name = host;
def.h_addr_list = alist;
def.h_addr = (char *)&defaddr;
def.h_length = sizeof(struct in_addr);
def.h_addrtype = AF_INET;
def.h_aliases = 0;
hp = &def;
} else if (!(hp = gethostbyname(host))) {
(void)fprintf(stderr,
"finger: unknown host: %s\n", host);
return;
}
if (!(sp = getservbyname("finger", "tcp"))) {
(void)fprintf(stderr, "finger: tcp/finger: unknown service\n");
return;
}
sin.sin_family = hp->h_addrtype;
bcopy(hp->h_addr, (char *)&sin.sin_addr, hp->h_length);
sin.sin_port = sp->s_port;
if ((s = socket(hp->h_addrtype, SOCK_STREAM, 0)) == INVALID_SOCKET) {
perror("finger: socket");
return;
}
/* have network connection; identify the host connected with */
(void)printf("[%s]\n", hp->h_name);
if (connect(s, (struct sockaddr *)&sin, sizeof(sin)) < 0) {
fprintf(stderr, "finger: connect rc = %d", WSAGetLastError());
(void)close(s);
return;
}
/* -l flag for remote fingerd */
if (lflag)
send(s, "/W ", 3, 0);
/* send the name followed by <CR><LF> */
send(s, name, strlen(name), 0);
send(s, "\r\n", 2, 0);
/*
* Read from the remote system; once we're connected, we assume some
* data. If none arrives, we hang until the user interrupts.
*
* If we see a <CR> or a <CR> with the high bit set, treat it as
* a newline; if followed by a newline character, only output one
* newline.
*
* Otherwise, all high bits are stripped; if it isn't printable and
* it isn't a space, we can simply set the 7th bit. Every ASCII
* character with bit 7 set is printable.
*/
lastc = 0;
while (recv(s, &c, 1, 0) == 1) {
c &= 0x7f;
if (c == 0x0d) {
if (lastc == '\r') /* ^M^M - skip dupes */
continue;
c = '\n';
lastc = '\r';
} else {
if (!isprint(c) && !isspace(c))
c |= 0x40;
if (lastc != '\r' || c != '\n')
lastc = c;
else {
lastc = '\n';
continue;
}
}
putchar(c);
}
if (lastc != '\n')
putchar('\n');
putchar('\n');
}
@@ -0,0 +1,36 @@
// Various things you need when porting BSD and GNU utilities to
// Win32.
#ifndef VARIOUS_H
#define VARIOUS_H
typedef float f4byte_t;
typedef double f8byte_t;
typedef long uid_t; // SunOS 5.5
#define __P(x) x
/* utmp.h */
#define UT_LINESIZE 8
#define UT_HOSTSIZE 16
/* stat.h */
#define S_ISREG(mode) (((mode)&0xF000) == 0x8000)
#define S_ISDIR(mode) (((mode)&0xF000) == 0x4000)
#undef MIN //take care of windows default
#undef MAX //take care of windows default
#define MIN(a, b) ((a) <= (b) ? (a) : (b))
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#define bcopy(s1, s2, n) memmove(s2, s1, n)
#define bcmp(s1, s2, n) (memcmp(s1, s2, n) != 0)
#define bzero(s, n) memset(s, 0, n)
#define index(s, c) strchr(s, c)
#define rindex(s, c) strrchr(s, c)
void netfinger(char *);
#endif
File diff suppressed because it is too large Load Diff
+171
View File
@@ -0,0 +1,171 @@
/*
* Copyright (c) 1985, 1989 Regents of the University of California.
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that the above copyright notice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by the University of California, Berkeley. The name of the
* University may not be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#ifndef lint
static char sccsid[] = "@(#)cmdtab.c 5.9 (Berkeley) 3/21/89";
#endif /* not lint */
#include "ftp_var.h"
/*
* User FTP -- Command Tables.
*/
char accounthelp[] = "send account command to remote server";
char appendhelp[] = "append to a file";
char asciihelp[] = "set ascii transfer type";
char beephelp[] = "beep when command completed";
char binaryhelp[] = "set binary transfer type";
char casehelp[] = "toggle mget upper/lower case id mapping";
char cdhelp[] = "change remote working directory";
char cduphelp[] = "change remote working directory to parent directory";
char chmodhelp[] = "change file permissions of remote file";
char connecthelp[] = "connect to remote tftp";
char crhelp[] = "toggle carriage return stripping on ascii gets";
char deletehelp[] = "delete remote file";
char debughelp[] = "toggle/set debugging mode";
char dirhelp[] = "list contents of remote directory";
char disconhelp[] = "terminate ftp session";
char domachelp[] = "execute macro";
char formhelp[] = "set file transfer format";
char globhelp[] = "toggle metacharacter expansion of local file names";
char hashhelp[] = "toggle printing `#' for each buffer transferred";
char helphelp[] = "print local help information";
char idlehelp[] = "get (set) idle timer on remote side";
char lcdhelp[] = "change local working directory";
char lshelp[] = "list contents of remote directory";
char macdefhelp[] = "define a macro";
char mdeletehelp[] = "delete multiple files";
char mdirhelp[] = "list contents of multiple remote directories";
char mgethelp[] = "get multiple files";
char mkdirhelp[] = "make directory on the remote machine";
char mlshelp[] = "list contents of multiple remote directories";
char modtimehelp[] = "show last modification time of remote file";
char modehelp[] = "set file transfer mode";
char mputhelp[] = "send multiple files";
char newerhelp[] = "get file if remote file is newer than local file ";
char nlisthelp[] = "nlist contents of remote directory";
char nmaphelp[] = "set templates for default file name mapping";
char ntranshelp[] = "set translation table for default file name mapping";
char porthelp[] = "toggle use of PORT cmd for each data connection";
char prompthelp[] = "force interactive prompting on multiple commands";
char proxyhelp[] = "issue command on alternate connection";
char pwdhelp[] = "print working directory on remote machine";
char quithelp[] = "terminate ftp session and exit";
char quotehelp[] = "send arbitrary ftp command";
char receivehelp[] = "receive file";
char regethelp[] = "get file restarting at end of local file";
char remotehelp[] = "get help from remote server";
char renamehelp[] = "rename file";
char restarthelp[]= "restart file transfer at bytecount";
char rmdirhelp[] = "remove directory on the remote machine";
char rmtstatushelp[]="show status of remote machine";
char runiquehelp[] = "toggle store unique for local files";
char resethelp[] = "clear queued command replies";
char sendhelp[] = "send one file";
char passivehelp[] = "enter passive transfer mode";
char sitehelp[] = "send site specific command to remote server\n\t\tTry \"rhelp site\" or \"site help\" for more information";
char shellhelp[] = "escape to the shell";
char sizecmdhelp[] = "show size of remote file";
char statushelp[] = "show current status";
char structhelp[] = "set file transfer structure";
char suniquehelp[] = "toggle store unique on remote machine";
char systemhelp[] = "show remote system type";
char tenexhelp[] = "set tenex file transfer type";
char tracehelp[] = "toggle packet tracing";
char typehelp[] = "set file transfer type";
char umaskhelp[] = "get (set) umask on remote side";
char userhelp[] = "send new user information";
char verbosehelp[] = "toggle verbose mode";
struct cmd cmdtab[] = {
{ "!", shellhelp, 0, 0, 0, shell },
{ "$", domachelp, 1, 0, 0, domacro },
{ "account", accounthelp, 0, 1, 1, account},
{ "append", appendhelp, 1, 1, 1, put },
{ "ascii", asciihelp, 0, 1, 1, setascii },
{ "bell", beephelp, 0, 0, 0, setbell },
{ "binary", binaryhelp, 0, 1, 1, setbinary },
{ "bye", quithelp, 0, 0, 0, quit },
{ "case", casehelp, 0, 0, 1, setcase },
{ "cd", cdhelp, 0, 1, 1, cd },
{ "cdup", cduphelp, 0, 1, 1, cdup },
{ "chmod", chmodhelp, 0, 1, 1, do_chmod },
{ "close", disconhelp, 0, 1, 1, disconnect },
{ "cr", crhelp, 0, 0, 0, setcr },
{ "delete", deletehelp, 0, 1, 1, delete },
{ "debug", debughelp, 0, 0, 0, setdebug },
{ "dir", dirhelp, 1, 1, 1, ls },
{ "disconnect", disconhelp, 0, 1, 1, disconnect },
{ "form", formhelp, 0, 1, 1, setform },
{ "get", receivehelp, 1, 1, 1, get },
{ "glob", globhelp, 0, 0, 0, setglob },
{ "hash", hashhelp, 0, 0, 0, sethash },
{ "help", helphelp, 0, 0, 1, help },
{ "idle", idlehelp, 0, 1, 1, idle },
{ "image", binaryhelp, 0, 1, 1, setbinary },
{ "lcd", lcdhelp, 0, 0, 0, lcd },
{ "ls", lshelp, 1, 1, 1, ls },
{ "macdef", macdefhelp, 0, 0, 0, macdef },
{ "mdelete", mdeletehelp, 1, 1, 1, mdelete },
{ "mdir", mdirhelp, 1, 1, 1, mls },
{ "mget", mgethelp, 1, 1, 1, mget },
{ "mkdir", mkdirhelp, 0, 1, 1, makedir },
{ "mls", mlshelp, 1, 1, 1, mls },
{ "mode", modehelp, 0, 1, 1, fsetmode },
{ "modtime", modtimehelp, 0, 1, 1, modtime },
{ "mput", mputhelp, 1, 1, 1, mput },
{ "newer", newerhelp, 1, 1, 1, newer },
{ "nmap", nmaphelp, 0, 0, 1, setnmap },
{ "nlist", nlisthelp, 1, 1, 1, ls },
{ "ntrans", ntranshelp, 0, 0, 1, setntrans },
{ "open", connecthelp, 0, 0, 1, setpeer },
{ "passive",passivehelp,0, 0, 0, setpassive },
{ "prompt", prompthelp, 0, 0, 0, setprompt },
{ "proxy", proxyhelp, 0, 0, 1, doproxy },
{ "sendport", porthelp, 0, 0, 0, setport },
{ "put", sendhelp, 1, 1, 1, put },
{ "pwd", pwdhelp, 0, 1, 1, pwd },
{ "quit", quithelp, 0, 0, 0, quit },
{ "quote", quotehelp, 1, 1, 1, quote },
{ "recv", receivehelp, 1, 1, 1, get },
{ "reget", regethelp, 1, 1, 1, reget },
{ "rstatus", rmtstatushelp, 0, 1, 1, rmtstatus },
{ "rhelp", remotehelp, 0, 1, 1, rmthelp },
{ "rename", renamehelp, 0, 1, 1, renamefile },
{ "reset", resethelp, 0, 1, 1, reset },
{ "restart", restarthelp, 1, 1, 1, restart },
{ "rmdir", rmdirhelp, 0, 1, 1, removedir },
{ "runique", runiquehelp, 0, 0, 1, setrunique },
{ "send", sendhelp, 1, 1, 1, put },
{ "site", sitehelp, 0, 1, 1, site },
{ "size", sizecmdhelp, 1, 1, 1, sizecmd },
{ "status", statushelp, 0, 0, 1, status },
{ "struct", structhelp, 0, 1, 1, setstruct },
{ "system", systemhelp, 0, 1, 1, syst },
{ "sunique", suniquehelp, 0, 0, 1, setsunique },
{ "tenex", tenexhelp, 0, 1, 1, settenex },
{ "trace", tracehelp, 0, 0, 0, settrace },
{ "type", typehelp, 0, 1, 1, settype },
{ "user", userhelp, 0, 1, 1, user },
{ "umask", umaskhelp, 0, 1, 1, do_umask },
{ "verbose", verbosehelp, 0, 0, 0, setverbose },
{ "?", helphelp, 0, 0, 1, help },
{ 0 },
};
int NCMDS = (sizeof (cmdtab) / sizeof (cmdtab[0])) - 1;
+148
View File
@@ -0,0 +1,148 @@
/*
* Copyright (c) 1985 Regents of the University of California.
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that the above copyright notice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by the University of California, Berkeley. The name of the
* University may not be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#ifndef lint
static char sccsid[] = "@(#)domacro.c 1.6 (Berkeley) 2/28/89";
#endif /* not lint */
#include "ftp_var.h"
#include "prototypes.h"
#include <signal.h>
#include <stdio.h>
//#include <errno.h>
#include <ctype.h>
//#include <sys/ttychars.h>
void domacro(argc, argv)
int argc;
const char *argv[];
{
int i, j;
const char *cp1;
char *cp2;
int count = 2, loopflg = 0;
char line2[200];
struct cmd *getcmd(), *c;
if (argc < 2) {
(void) strcat(line, " ");
printf("(macro name) ");
(void) fflush(stdout);
(void) gets(&line[strlen(line)]);
makeargv();
argc = margc;
argv = margv;
}
if (argc < 2) {
printf("Usage: %s macro_name.\n", argv[0]);
(void) fflush(stdout);
code = -1;
return;
}
for (i = 0; i < macnum; ++i) {
if (!strncmp(argv[1], macros[i].mac_name, 9)) {
break;
}
}
if (i == macnum) {
printf("'%s' macro not found.\n", argv[1]);
(void) fflush(stdout);
code = -1;
return;
}
(void) strcpy(line2, line);
TOP:
cp1 = macros[i].mac_start;
while (cp1 != macros[i].mac_end) {
while (isspace(*cp1)) {
cp1++;
}
cp2 = line;
while (*cp1 != '\0') {
switch(*cp1) {
case '\\':
*cp2++ = *++cp1;
break;
case '$':
if (isdigit(*(cp1+1))) {
j = 0;
while (isdigit(*++cp1)) {
j = 10*j + *cp1 - '0';
}
cp1--;
if (argc - 2 >= j) {
(void) strcpy(cp2, argv[j+1]);
cp2 += strlen(argv[j+1]);
}
break;
}
if (*(cp1+1) == 'i') {
loopflg = 1;
cp1++;
if (count < argc) {
(void) strcpy(cp2, argv[count]);
cp2 += strlen(argv[count]);
}
break;
}
/* intentional drop through */
default:
*cp2++ = *cp1;
break;
}
if (*cp1 != '\0') {
cp1++;
}
}
*cp2 = '\0';
makeargv();
c = getcmd(margv[0]);
if (c == (struct cmd *)-1) {
printf("?Ambiguous command\n");
code = -1;
}
else if (c == 0) {
printf("?Invalid command\n");
code = -1;
}
else if (c->c_conn && !connected) {
printf("Not connected.\n");
code = -1;
}
else {
if (verbose) {
printf("%s\n",line);
}
(*c->c_handler)(margc, margv);
if (bell && c->c_bell) {
(void) putchar('\007');
}
(void) strcpy(line, line2);
makeargv();
argc = margc;
argv = margv;
}
if (cp1 != macros[i].mac_end) {
cp1++;
}
(void) fflush(stdout);
}
if (loopflg && ++count < argc) {
goto TOP;
}
}
+341
View File
@@ -0,0 +1,341 @@
#include <stdio.h>
#include <time.h>
#include <winsock.h>
#include "fake.h"
#include "prototypes.h"
#define MAX_ASCII 100
int checkRecv(SOCKET s);
int checkRecv(SOCKET s)
{
int testVal;
fd_set sSet;
struct timeval timeout;
timeout.tv_sec = 60;
FD_ZERO(&sSet);
FD_SET(s, &sSet);
testVal = select(0, &sSet, NULL, NULL, &timeout);
if (testVal == SOCKET_ERROR)
fprintf(stderr, "Socket Error");
return testVal;
}
void blkfree(char **av0)
{
register char **av = av0;
while (*av)
free(*av++);
}
char **glob(register char *v)
{
return NULL;
}
int sleep(int time)
{
return time;
}
int herror(char *string)
{
return 0;
}
#if 0
int gettimeofday(struct timeval *timenow,
struct timezone *zone)
{
time_t t;
t = clock();
timenow->tv_usec = t;
timenow->tv_sec = t / CLK_TCK;
return 0;
}
int fgetcSocket(int s)
{
int c;
char buffer[10];
// checkRecv(s);
c = recv(s, buffer, 1, 0);
#ifdef DEBUG_IN
printf("%c", buffer[0]);
#endif
if (c == INVALID_SOCKET)
return c;
if (c == 0)
return EOF;
return buffer[0];
}
#else
int fgetcSocket(int s)
{
static int index = 0;
static int total = 0;
static char buffer[4096];
if (index == total)
{
index = 0;
total = recv(s, buffer, sizeof(buffer), 0);
if (total == SOCKET_ERROR)
{
total = 0;
return ERROR;
}
if (total == 0)
return EOF;
}
return buffer[index++];
}
#endif
const char *fprintfSocket(int s, const char *format, ...)
{
va_list argptr;
char buffer[10009];
va_start(argptr, format);
vsprintf(buffer, format, argptr);
va_end(argptr);
send(s, buffer, strlen(buffer), 0);
return NULL;
}
const char *fputsSocket(const char *format, int s)
{
send(s, format, strlen(format), 0);
return NULL;
}
int fputcSocket(int s, char putChar)
{
char buffer[2];
buffer[0] = putChar;
buffer[1] = '\0';
if(SOCKET_ERROR==send(s, buffer, 1, 0)) {
int iret=WSAGetLastError ();
fprintf(stdout,"fputcSocket: %d\n",iret);
return 0;
}
else {
return putChar;
}
}
int fputSocket(int s, char *buffer, int len)
{
int iret;
while(len) {
if(SOCKET_ERROR==(iret=send(s, buffer, len, 0)))
{
iret=WSAGetLastError ();
fprintf(stdout,"fputcSocket: %d\n",iret);
return 0;
}
else {
return len-=iret;
}
}
return 0;
}
char *fgetsSocket(int s, char *string)
{
char buffer[2] = {0};
int i, count;
for (i = 0, count = 1; count != 0 && buffer[0] != '\n'; i++)
{
checkRecv(s);
count = recv(s, buffer, 1, 0);
if (count == SOCKET_ERROR)
{
printf("Error in fgetssocket");
return NULL;
}
if (count == 1)
{
string[i] = buffer[0];
if (i == MAX_ASCII - 3)
{
count = 0;
string[++i] = '\n';
string[++i] = '\0';
}
}
else
{
if (i == 0)
return NULL;
else
{
string[i] = '\n';
string[i + 1] = '\0'; // This is risky
return string;
}
}
}
string[i] = '\0';
#ifdef DEBUG_IN
printf("%s", string);
#endif
return string;
}
#if 0
char *getpass(const char *prompt)
{
static char string[64];
printf("%s", prompt);
gets(string);
return string;
}
#endif
char *getpass (const char * prompt)
{
static char input[256];
HANDLE in;
HANDLE err;
DWORD count;
in = GetStdHandle (STD_INPUT_HANDLE);
err = GetStdHandle (STD_ERROR_HANDLE);
if (in == INVALID_HANDLE_VALUE || err == INVALID_HANDLE_VALUE)
return NULL;
if (WriteFile (err, prompt, strlen (prompt), &count, NULL))
{
int istty = (GetFileType (in) == FILE_TYPE_CHAR);
DWORD old_flags;
int rc;
if (istty)
{
if (GetConsoleMode (in, &old_flags))
SetConsoleMode (in, ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT);
else
istty = 0;
}
/* Need to read line one byte at time to avoid blocking, if not a
tty, so always do it this way. */
count = 0;
while (1)
{
DWORD dummy;
char one_char;
rc = ReadFile (in, &one_char, 1, &dummy, NULL);
if (rc == 0)
break;
if (one_char == '\r')
{
/* CR is always followed by LF if reading from tty. */
if (istty)
continue;
else
break;
}
if (one_char == '\n')
break;
/* Silently truncate password string if overly long. */
if (count < sizeof (input) - 1)
input[count++] = one_char;
}
input[count] = '\0';
WriteFile (err, "\r\n", 2, &count, NULL);
if (istty)
SetConsoleMode (in, old_flags);
if (rc)
return input;
}
return NULL;
}
#if 0
// Stubbed out here. Should be changed in Source code...
int access(const char *filename, int accessmethod)
{
return 0;
}
#endif
#ifndef __GNUC__
#define EPOCHFILETIME (116444736000000000i64)
#else
#define EPOCHFILETIME (116444736000000000LL)
#endif
int gettimeofday(struct timeval *tv, struct timezone *tz)
{
FILETIME ft;
LARGE_INTEGER li;
__int64 t;
static int tzflag;
if (tv)
{
GetSystemTimeAsFileTime(&ft);
li.LowPart = ft.dwLowDateTime;
li.HighPart = ft.dwHighDateTime;
t = li.QuadPart; /* In 100-nanosecond intervals */
t -= EPOCHFILETIME; /* Offset to the Epoch time */
t /= 10; /* In microseconds */
tv->tv_sec = (long)(t / 1000000);
tv->tv_usec = (long)(t % 1000000);
}
if (tz)
{
if (!tzflag)
{
_tzset();
tzflag++;
}
tz->tz_minuteswest = _timezone / 60;
tz->tz_dsttime = _daylight;
}
return 0;
}
+17
View File
@@ -0,0 +1,17 @@
#define bcopy(s,d,l) memcpy((d),(s),(l))
#define bzero(cp,l) memset((cp),0,(l))
#define rindex strrchr
#define index strchr
#define getwd getcwd
#define strcasecmp strcmp
#define strncasecmp strnicmp
struct timezone {
int tz_minuteswest; /* minutes W of Greenwich */
int tz_dsttime; /* type of dst correction */
};
int gettimeofday(struct timeval *tv, struct timezone *tz);
File diff suppressed because it is too large Load Diff
+372
View File
@@ -0,0 +1,372 @@
# Microsoft Developer Studio Generated NMAKE File, Based on ftp.dsp
!IF "$(CFG)" == ""
CFG=ftp - Win32 Debug
!MESSAGE No configuration specified. Defaulting to ftp - Win32 Debug.
!ENDIF
!IF "$(CFG)" != "ftp - Win32 Release" && "$(CFG)" != "ftp - Win32 Debug"
!MESSAGE Invalid configuration "$(CFG)" specified.
!MESSAGE You can specify a configuration when running NMAKE
!MESSAGE by defining the macro CFG on the command line. For example:
!MESSAGE
!MESSAGE NMAKE /f "ftp.mak" CFG="ftp - Win32 Debug"
!MESSAGE
!MESSAGE Possible choices for configuration are:
!MESSAGE
!MESSAGE "ftp - Win32 Release" (based on "Win32 (x86) Console Application")
!MESSAGE "ftp - Win32 Debug" (based on "Win32 (x86) Console Application")
!MESSAGE
!ERROR An invalid configuration is specified.
!ENDIF
!IF "$(OS)" == "Windows_NT"
NULL=
!ELSE
NULL=nul
!ENDIF
!IF "$(CFG)" == "ftp - Win32 Release"
OUTDIR=.\Release
INTDIR=.\Release
# Begin Custom Macros
OutDir=.\Release
# End Custom Macros
!IF "$(RECURSE)" == "0"
ALL : "$(OUTDIR)\ftp.exe"
!ELSE
ALL : "$(OUTDIR)\ftp.exe"
!ENDIF
CLEAN :
-@erase "$(INTDIR)\cmds.obj"
-@erase "$(INTDIR)\cmdtab.obj"
-@erase "$(INTDIR)\domacro.obj"
-@erase "$(INTDIR)\fake.obj"
-@erase "$(INTDIR)\ftp.obj"
-@erase "$(INTDIR)\main.obj"
-@erase "$(INTDIR)\ruserpass.obj"
-@erase "$(INTDIR)\vc*.idb"
-@erase "$(OUTDIR)\ftp.exe"
-@erase "$(OUTDIR)\ftp.pch"
"$(OUTDIR)" :
if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)"
CPP=cl.exe
CPP_PROJ=/nologo /ML /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" \
/D "HAVE_TIMEVAL" /Fp"$(INTDIR)\ftp.pch" /YX /Fo"$(INTDIR)\\" /Fd"$(INTDIR)\\" /FD\
/c
CPP_OBJS=.\Release/
CPP_SBRS=.
.c{$(CPP_OBJS)}.obj::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.cpp{$(CPP_OBJS)}.obj::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.cxx{$(CPP_OBJS)}.obj::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.c{$(CPP_SBRS)}.sbr::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.cpp{$(CPP_SBRS)}.sbr::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.cxx{$(CPP_SBRS)}.sbr::
$(CPP) @<<
$(CPP_PROJ) $<
<<
RSC=rc.exe
BSC32=bscmake.exe
BSC32_FLAGS=/nologo /o"$(OUTDIR)\ftp.bsc"
BSC32_SBRS= \
LINK32=link.exe
LINK32_FLAGS=kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib\
advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib\
odbccp32.lib wsock32.lib /nologo /subsystem:console /incremental:no\
/pdb:"$(OUTDIR)\ftp.pdb" /machine:I386 /out:"$(OUTDIR)\ftp.exe"
LINK32_OBJS= \
"$(INTDIR)\cmds.obj" \
"$(INTDIR)\cmdtab.obj" \
"$(INTDIR)\domacro.obj" \
"$(INTDIR)\fake.obj" \
"$(INTDIR)\ftp.obj" \
"$(INTDIR)\main.obj" \
"$(INTDIR)\ruserpass.obj"
"$(OUTDIR)\ftp.exe" : "$(OUTDIR)" $(DEF_FILE) $(LINK32_OBJS)
$(LINK32) @<<
$(LINK32_FLAGS) $(LINK32_OBJS)
<<
TargetPath=.\Release\ftp.exe
InputPath=.\Release\ftp.exe
SOURCE=$(InputPath)
!ELSEIF "$(CFG)" == "ftp - Win32 Debug"
OUTDIR=.\Debug
INTDIR=.\Debug
# Begin Custom Macros
OutDir=.\Debug
# End Custom Macros
!IF "$(RECURSE)" == "0"
ALL : "$(OUTDIR)\ftp.exe"
!ELSE
ALL : "$(OUTDIR)\ftp.exe"
!ENDIF
CLEAN :
-@erase "$(INTDIR)\cmds.obj"
-@erase "$(INTDIR)\cmdtab.obj"
-@erase "$(INTDIR)\domacro.obj"
-@erase "$(INTDIR)\fake.obj"
-@erase "$(INTDIR)\ftp.obj"
-@erase "$(INTDIR)\main.obj"
-@erase "$(INTDIR)\ruserpass.obj"
-@erase "$(INTDIR)\vc*.idb"
-@erase "$(INTDIR)\vc*.pdb"
-@erase "$(OUTDIR)\ftp.exe"
-@erase "$(OUTDIR)\ftp.ilk"
-@erase "$(OUTDIR)\ftp.pdb"
-@erase "$(OUTDIR)\ftp.pch"
"$(OUTDIR)" :
if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)"
CPP=cl.exe
CPP_PROJ=/nologo /MLd /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS"\
/Fp"$(INTDIR)\ftp.pch" /YX /Fo"$(INTDIR)\\" /Fd"$(INTDIR)\\" /FD /c
CPP_OBJS=.\Debug/
CPP_SBRS=.
.c{$(CPP_OBJS)}.obj::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.cpp{$(CPP_OBJS)}.obj::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.cxx{$(CPP_OBJS)}.obj::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.c{$(CPP_SBRS)}.sbr::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.cpp{$(CPP_SBRS)}.sbr::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.cxx{$(CPP_SBRS)}.sbr::
$(CPP) @<<
$(CPP_PROJ) $<
<<
RSC=rc.exe
BSC32=bscmake.exe
BSC32_FLAGS=/nologo /o"$(OUTDIR)\ftp.bsc"
BSC32_SBRS= \
LINK32=link.exe
LINK32_FLAGS=kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib\
advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib\
odbccp32.lib wsock32.lib /nologo /subsystem:console /incremental:yes\
/pdb:"$(OUTDIR)\ftp.pdb" /debug /machine:I386 /out:"$(OUTDIR)\ftp.exe"\
/pdbtype:sept
LINK32_OBJS= \
"$(INTDIR)\cmds.obj" \
"$(INTDIR)\cmdtab.obj" \
"$(INTDIR)\domacro.obj" \
"$(INTDIR)\fake.obj" \
"$(INTDIR)\ftp.obj" \
"$(INTDIR)\main.obj" \
"$(INTDIR)\ruserpass.obj"
"$(OUTDIR)\ftp.exe" : "$(OUTDIR)" $(DEF_FILE) $(LINK32_OBJS)
$(LINK32) @<<
$(LINK32_FLAGS) $(LINK32_OBJS)
<<
TargetPath=.\Debug\ftp.exe
InputPath=.\Debug\ftp.exe
SOURCE=$(InputPath)
!ENDIF
!IF "$(CFG)" == "ftp - Win32 Release" || "$(CFG)" == "ftp - Win32 Debug"
SOURCE=.\cmds.c
!IF "$(CFG)" == "ftp - Win32 Release"
DEP_CPP_CMDS_=\
".\fake.h"\
".\ftp_var.h"\
".\pathnames.h"\
".\prototypes.h"\
"$(INTDIR)\cmds.obj" : $(SOURCE) $(DEP_CPP_CMDS_) "$(INTDIR)"
!ELSEIF "$(CFG)" == "ftp - Win32 Debug"
DEP_CPP_CMDS_=\
".\fake.h"\
".\ftp_var.h"\
".\pathnames.h"\
".\prototypes.h"\
{$(INCLUDE)}"sys\stat.h"\
{$(INCLUDE)}"sys\types.h"\
"$(INTDIR)\cmds.obj" : $(SOURCE) $(DEP_CPP_CMDS_) "$(INTDIR)"
!ENDIF
SOURCE=.\cmdtab.c
DEP_CPP_CMDTA=\
".\fake.h"\
".\ftp_var.h"\
"$(INTDIR)\cmdtab.obj" : $(SOURCE) $(DEP_CPP_CMDTA) "$(INTDIR)"
SOURCE=.\domacro.c
DEP_CPP_DOMAC=\
".\fake.h"\
".\ftp_var.h"\
".\prototypes.h"\
"$(INTDIR)\domacro.obj" : $(SOURCE) $(DEP_CPP_DOMAC) "$(INTDIR)"
SOURCE=.\fake.c
DEP_CPP_FAKE_=\
".\prototypes.h"\
"$(INTDIR)\fake.obj" : $(SOURCE) $(DEP_CPP_FAKE_) "$(INTDIR)"
SOURCE=.\ftp.c
!IF "$(CFG)" == "ftp - Win32 Release"
DEP_CPP_FTP_C=\
".\fake.h"\
".\ftp_var.h"\
".\prototypes.h"\
"$(INTDIR)\ftp.obj" : $(SOURCE) $(DEP_CPP_FTP_C) "$(INTDIR)"
!ELSEIF "$(CFG)" == "ftp - Win32 Debug"
DEP_CPP_FTP_C=\
".\fake.h"\
".\ftp_var.h"\
".\prototypes.h"\
{$(INCLUDE)}"sys\stat.h"\
{$(INCLUDE)}"sys\types.h"\
"$(INTDIR)\ftp.obj" : $(SOURCE) $(DEP_CPP_FTP_C) "$(INTDIR)"
!ENDIF
SOURCE=.\main.c
!IF "$(CFG)" == "ftp - Win32 Release"
DEP_CPP_MAIN_=\
".\fake.h"\
".\ftp_var.h"\
".\prototypes.h"\
"$(INTDIR)\main.obj" : $(SOURCE) $(DEP_CPP_MAIN_) "$(INTDIR)"
!ELSEIF "$(CFG)" == "ftp - Win32 Debug"
DEP_CPP_MAIN_=\
".\fake.h"\
".\ftp_var.h"\
".\prototypes.h"\
{$(INCLUDE)}"sys\types.h"\
"$(INTDIR)\main.obj" : $(SOURCE) $(DEP_CPP_MAIN_) "$(INTDIR)"
!ENDIF
SOURCE=.\ruserpass.c
!IF "$(CFG)" == "ftp - Win32 Release"
DEP_CPP_RUSER=\
".\fake.h"\
".\ftp_var.h"\
".\prototypes.h"\
"$(INTDIR)\ruserpass.obj" : $(SOURCE) $(DEP_CPP_RUSER) "$(INTDIR)"
!ELSEIF "$(CFG)" == "ftp - Win32 Debug"
DEP_CPP_RUSER=\
".\fake.h"\
".\ftp_var.h"\
".\prototypes.h"\
{$(INCLUDE)}"sys\stat.h"\
{$(INCLUDE)}"sys\types.h"\
"$(INTDIR)\ruserpass.obj" : $(SOURCE) $(DEP_CPP_RUSER) "$(INTDIR)"
!ENDIF
!ENDIF
@@ -0,0 +1,400 @@
# Microsoft Developer Studio Generated NMAKE File, Based on ftp.dsp
!IF "$(CFG)" == ""
CFG=ftp - Win32 Debug
!MESSAGE No configuration specified. Defaulting to ftp - Win32 Debug.
!ENDIF
!IF "$(CFG)" != "ftp - Win32 Release" && "$(CFG)" != "ftp - Win32 Debug"
!MESSAGE Invalid configuration "$(CFG)" specified.
!MESSAGE You can specify a configuration when running NMAKE
!MESSAGE by defining the macro CFG on the command line. For example:
!MESSAGE
!MESSAGE NMAKE /f "ftp.mak" CFG="ftp - Win32 Debug"
!MESSAGE
!MESSAGE Possible choices for configuration are:
!MESSAGE
!MESSAGE "ftp - Win32 Release" (based on "Win32 (x86) Console Application")
!MESSAGE "ftp - Win32 Debug" (based on "Win32 (x86) Console Application")
!MESSAGE
!ERROR An invalid configuration is specified.
!ENDIF
!IF "$(OS)" == "Windows_NT"
NULL=
!ELSE
NULL=nul
!ENDIF
!IF "$(CFG)" == "ftp - Win32 Release"
OUTDIR=.\Release
INTDIR=.\Release
# Begin Custom Macros
OutDir=.\Release
# End Custom Macros
!IF "$(RECURSE)" == "0"
ALL : "$(OUTDIR)\ftp.exe" "\emacs-19.34\bin\ftp.exe"
!ELSE
ALL : "$(OUTDIR)\ftp.exe" "\emacs-19.34\bin\ftp.exe"
!ENDIF
CLEAN :
-@erase "$(INTDIR)\cmds.obj"
-@erase "$(INTDIR)\cmdtab.obj"
-@erase "$(INTDIR)\domacro.obj"
-@erase "$(INTDIR)\fake.obj"
-@erase "$(INTDIR)\ftp.obj"
-@erase "$(INTDIR)\main.obj"
-@erase "$(INTDIR)\ruserpass.obj"
-@erase "$(INTDIR)\vc50.idb"
-@erase "$(OUTDIR)\ftp.exe"
-@erase "\emacs-19.34\bin\ftp.exe"
"$(OUTDIR)" :
if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)"
CPP=cl.exe
CPP_PROJ=/nologo /ML /W3 /GX /O2 /I "C:\emacs-19.34\nt\inc" /I\
"C:\emacs-19.34\src" /D "WIN32" /D "NDEBUG" /D "_CONSOLE" /D "_MBCS" /D\
"HAVE_TIMEVAL" /Fp"$(INTDIR)\ftp.pch" /YX /Fo"$(INTDIR)\\" /Fd"$(INTDIR)\\" /FD\
/c
CPP_OBJS=.\Release/
CPP_SBRS=.
.c{$(CPP_OBJS)}.obj::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.cpp{$(CPP_OBJS)}.obj::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.cxx{$(CPP_OBJS)}.obj::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.c{$(CPP_SBRS)}.sbr::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.cpp{$(CPP_SBRS)}.sbr::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.cxx{$(CPP_SBRS)}.sbr::
$(CPP) @<<
$(CPP_PROJ) $<
<<
RSC=rc.exe
BSC32=bscmake.exe
BSC32_FLAGS=/nologo /o"$(OUTDIR)\ftp.bsc"
BSC32_SBRS= \
LINK32=link.exe
LINK32_FLAGS=kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib\
advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib\
odbccp32.lib /nologo /subsystem:console /incremental:no\
/pdb:"$(OUTDIR)\ftp.pdb" /machine:I386 /out:"$(OUTDIR)\ftp.exe"
LINK32_OBJS= \
"$(INTDIR)\cmds.obj" \
"$(INTDIR)\cmdtab.obj" \
"$(INTDIR)\domacro.obj" \
"$(INTDIR)\fake.obj" \
"$(INTDIR)\ftp.obj" \
"$(INTDIR)\main.obj" \
"$(INTDIR)\ruserpass.obj" \
"d:\Program Files\DevStudio\VC\lib\WSOCK32.LIB"
"$(OUTDIR)\ftp.exe" : "$(OUTDIR)" $(DEF_FILE) $(LINK32_OBJS)
$(LINK32) @<<
$(LINK32_FLAGS) $(LINK32_OBJS)
<<
TargetPath=.\Release\ftp.exe
InputPath=.\Release\ftp.exe
SOURCE=$(InputPath)
"\emacs-19.34\bin\ftp.exe" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
# copy $(TargetPath) \emacs-19.34\bin
!ELSEIF "$(CFG)" == "ftp - Win32 Debug"
OUTDIR=.\Debug
INTDIR=.\Debug
# Begin Custom Macros
OutDir=.\Debug
# End Custom Macros
!IF "$(RECURSE)" == "0"
ALL : "$(OUTDIR)\ftp.exe" "\emacs-19.34\bin\ftp.exe"
!ELSE
ALL : "$(OUTDIR)\ftp.exe" "\emacs-19.34\bin\ftp.exe"
!ENDIF
CLEAN :
-@erase "$(INTDIR)\cmds.obj"
-@erase "$(INTDIR)\cmdtab.obj"
-@erase "$(INTDIR)\domacro.obj"
-@erase "$(INTDIR)\fake.obj"
-@erase "$(INTDIR)\ftp.obj"
-@erase "$(INTDIR)\main.obj"
-@erase "$(INTDIR)\ruserpass.obj"
-@erase "$(INTDIR)\vc50.idb"
-@erase "$(INTDIR)\vc50.pdb"
-@erase "$(OUTDIR)\ftp.exe"
-@erase "$(OUTDIR)\ftp.ilk"
-@erase "$(OUTDIR)\ftp.pdb"
-@erase "\emacs-19.34\bin\ftp.exe"
"$(OUTDIR)" :
if not exist "$(OUTDIR)/$(NULL)" mkdir "$(OUTDIR)"
CPP=cl.exe
CPP_PROJ=/nologo /MLd /W3 /Gm /GX /Zi /Od /I "C:\emacs-19.34\nt\inc" /I\
"C:\emacs-19.34\src" /D "WIN32" /D "_DEBUG" /D "_CONSOLE" /D "_MBCS"\
/Fp"$(INTDIR)\ftp.pch" /YX /Fo"$(INTDIR)\\" /Fd"$(INTDIR)\\" /FD /c
CPP_OBJS=.\Debug/
CPP_SBRS=.
.c{$(CPP_OBJS)}.obj::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.cpp{$(CPP_OBJS)}.obj::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.cxx{$(CPP_OBJS)}.obj::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.c{$(CPP_SBRS)}.sbr::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.cpp{$(CPP_SBRS)}.sbr::
$(CPP) @<<
$(CPP_PROJ) $<
<<
.cxx{$(CPP_SBRS)}.sbr::
$(CPP) @<<
$(CPP_PROJ) $<
<<
RSC=rc.exe
BSC32=bscmake.exe
BSC32_FLAGS=/nologo /o"$(OUTDIR)\ftp.bsc"
BSC32_SBRS= \
LINK32=link.exe
LINK32_FLAGS=kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib\
advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib\
odbccp32.lib /nologo /subsystem:console /incremental:yes\
/pdb:"$(OUTDIR)\ftp.pdb" /debug /machine:I386 /out:"$(OUTDIR)\ftp.exe"\
/pdbtype:sept
LINK32_OBJS= \
"$(INTDIR)\cmds.obj" \
"$(INTDIR)\cmdtab.obj" \
"$(INTDIR)\domacro.obj" \
"$(INTDIR)\fake.obj" \
"$(INTDIR)\ftp.obj" \
"$(INTDIR)\main.obj" \
"$(INTDIR)\ruserpass.obj" \
"d:\Program Files\DevStudio\VC\lib\WSOCK32.LIB"
"$(OUTDIR)\ftp.exe" : "$(OUTDIR)" $(DEF_FILE) $(LINK32_OBJS)
$(LINK32) @<<
$(LINK32_FLAGS) $(LINK32_OBJS)
<<
TargetPath=.\Debug\ftp.exe
InputPath=.\Debug\ftp.exe
SOURCE=$(InputPath)
"\emacs-19.34\bin\ftp.exe" : $(SOURCE) "$(INTDIR)" "$(OUTDIR)"
# copy $(TargetPath) \emacs-19.34\bin
!ENDIF
!IF "$(CFG)" == "ftp - Win32 Release" || "$(CFG)" == "ftp - Win32 Debug"
SOURCE=.\cmds.c
!IF "$(CFG)" == "ftp - Win32 Release"
DEP_CPP_CMDS_=\
".\fake.h"\
".\ftp_var.h"\
".\pathnames.h"\
".\prototypes.h"\
"$(INTDIR)\cmds.obj" : $(SOURCE) $(DEP_CPP_CMDS_) "$(INTDIR)"
!ELSEIF "$(CFG)" == "ftp - Win32 Debug"
DEP_CPP_CMDS_=\
"..\..\..\emacs-19.34\nt\inc\netdb.h"\
"..\..\..\emacs-19.34\nt\inc\netinet\in.h"\
"..\..\..\emacs-19.34\nt\inc\sys\socket.h"\
"..\..\..\emacs-19.34\src\nt.h"\
".\fake.h"\
".\ftp_var.h"\
".\pathnames.h"\
".\prototypes.h"\
{$(INCLUDE)}"sys\stat.h"\
{$(INCLUDE)}"sys\types.h"\
"$(INTDIR)\cmds.obj" : $(SOURCE) $(DEP_CPP_CMDS_) "$(INTDIR)"
!ENDIF
SOURCE=.\cmdtab.c
DEP_CPP_CMDTA=\
".\fake.h"\
".\ftp_var.h"\
"$(INTDIR)\cmdtab.obj" : $(SOURCE) $(DEP_CPP_CMDTA) "$(INTDIR)"
SOURCE=.\domacro.c
DEP_CPP_DOMAC=\
".\fake.h"\
".\ftp_var.h"\
".\prototypes.h"\
"$(INTDIR)\domacro.obj" : $(SOURCE) $(DEP_CPP_DOMAC) "$(INTDIR)"
SOURCE=.\fake.c
DEP_CPP_FAKE_=\
".\prototypes.h"\
"$(INTDIR)\fake.obj" : $(SOURCE) $(DEP_CPP_FAKE_) "$(INTDIR)"
SOURCE=.\ftp.c
!IF "$(CFG)" == "ftp - Win32 Release"
DEP_CPP_FTP_C=\
".\fake.h"\
".\ftp_var.h"\
".\prototypes.h"\
"$(INTDIR)\ftp.obj" : $(SOURCE) $(DEP_CPP_FTP_C) "$(INTDIR)"
!ELSEIF "$(CFG)" == "ftp - Win32 Debug"
DEP_CPP_FTP_C=\
"..\..\..\emacs-19.34\nt\inc\netdb.h"\
"..\..\..\emacs-19.34\nt\inc\netinet\in.h"\
"..\..\..\emacs-19.34\nt\inc\pwd.h"\
"..\..\..\emacs-19.34\nt\inc\sys\file.h"\
"..\..\..\emacs-19.34\nt\inc\sys\ioctl.h"\
"..\..\..\emacs-19.34\nt\inc\sys\param.h"\
"..\..\..\emacs-19.34\nt\inc\sys\socket.h"\
"..\..\..\emacs-19.34\nt\inc\sys\time.h"\
"..\..\..\emacs-19.34\src\nt.h"\
".\fake.h"\
".\ftp_var.h"\
".\prototypes.h"\
{$(INCLUDE)}"sys\stat.h"\
{$(INCLUDE)}"sys\types.h"\
"$(INTDIR)\ftp.obj" : $(SOURCE) $(DEP_CPP_FTP_C) "$(INTDIR)"
!ENDIF
SOURCE=.\main.c
!IF "$(CFG)" == "ftp - Win32 Release"
DEP_CPP_MAIN_=\
".\fake.h"\
".\ftp_var.h"\
".\prototypes.h"\
"$(INTDIR)\main.obj" : $(SOURCE) $(DEP_CPP_MAIN_) "$(INTDIR)"
!ELSEIF "$(CFG)" == "ftp - Win32 Debug"
DEP_CPP_MAIN_=\
"..\..\..\emacs-19.34\nt\inc\netdb.h"\
"..\..\..\emacs-19.34\nt\inc\pwd.h"\
"..\..\..\emacs-19.34\nt\inc\sys\ioctl.h"\
"..\..\..\emacs-19.34\nt\inc\sys\socket.h"\
"..\..\..\emacs-19.34\src\nt.h"\
".\fake.h"\
".\ftp_var.h"\
".\prototypes.h"\
{$(INCLUDE)}"sys\types.h"\
"$(INTDIR)\main.obj" : $(SOURCE) $(DEP_CPP_MAIN_) "$(INTDIR)"
!ENDIF
SOURCE=.\ruserpass.c
!IF "$(CFG)" == "ftp - Win32 Release"
DEP_CPP_RUSER=\
".\fake.h"\
".\ftp_var.h"\
".\prototypes.h"\
"$(INTDIR)\ruserpass.obj" : $(SOURCE) $(DEP_CPP_RUSER) "$(INTDIR)"
!ELSEIF "$(CFG)" == "ftp - Win32 Debug"
DEP_CPP_RUSER=\
".\fake.h"\
".\ftp_var.h"\
".\prototypes.h"\
{$(INCLUDE)}"sys\stat.h"\
{$(INCLUDE)}"sys\types.h"\
"$(INTDIR)\ruserpass.obj" : $(SOURCE) $(DEP_CPP_RUSER) "$(INTDIR)"
!ENDIF
!ENDIF
+6
View File
@@ -0,0 +1,6 @@
/* $Id: route.rc 11816 2004-11-26 06:51:47Z arty $ */
#define REACTOS_STR_FILE_DESCRIPTION "ReactOS TCP/IPv4 FTP Client\0"
#define REACTOS_STR_INTERNAL_NAME "ftp\0"
#define REACTOS_STR_ORIGINAL_FILENAME "ftp.exe\0"
#include <reactos/version.rc>
+16
View File
@@ -0,0 +1,16 @@
<module name="ftp" type="win32cui" installbase="system32" installname="ftp.exe" allowwarnings="true">
<include base="ftp">.</include>
<define name="__USE_W32API" />
<define name="lint" />
<library>kernel32</library>
<library>ws2_32</library>
<library>iphlpapi</library>
<file>cmds.c</file>
<file>cmdtab.c</file>
<file>domacro.c</file>
<file>fake.c</file>
<file>ftp.c</file>
<file>main.c</file>
<file>ruserpass.c</file>
<file>ftp.rc</file>
</module>
+168
View File
@@ -0,0 +1,168 @@
#include <winsock.h>
#include "fake.h"
#include "prototypes.h"
#include <setjmp.h>
//typedef void (*Sig_t)(int);
/* The following defines are from ftp.h and telnet.h from bsd.h */
/* All relevent copyrights below apply. */
#define IAC 255
#define DONT 254
#define DO 253
#define WONT 252
#define WILL 251
#define SB 250
#define GA 249
#define EL 248
#define EC 247
#define AYT 246
#define AO 245
#define IP 244
#define BREAK 243
#define DM 242
#define NOP 241
#define SE 240
#define EOR 239
#define ABORT 238
#define SUSP 237
#define xEOF 236
#define MAXPATHLEN 255
#define TYPE_A 'A'
#define TYPE_I 'I'
#define TYPE_E 'E'
#define TYPE_L 'L'
#define PRELIM 1
#define COMPLETE 2
#define CONTINUE 3
#define TRANSIENT 4
#define MODE_S 1
#define MODE_B 2
#define MODE_C 3
#define STRU_F 1
#define STRU_R 2
#define STRU_P 3
#define SIGQUIT 1
#define SIGPIPE 2
#define SIGALRM 3
#define FORM_N 1
#define FORM_T 2
#define FORM_C 3
/*
* Copyright (c) 1985 Regents of the University of California.
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that the above copyright notice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by the University of California, Berkeley. The name of the
* University may not be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* @(#)ftp_var.h 5.5 (Berkeley) 6/29/88
*/
/*
* FTP global variables.
*/
/*
* Options and other state info.
*/
extern int trace; /* trace packets exchanged */
extern int hash; /* print # for each buffer transferred */
extern int sendport; /* use PORT cmd for each data connection */
extern int verbose; /* print messages coming back from server */
extern int connected; /* connected to server */
extern int fromatty; /* input is from a terminal */
extern int interactive; /* interactively prompt on m* cmds */
extern int debug; /* debugging level */
extern int bell; /* ring bell on cmd completion */
extern int doglob; /* glob local file names */
extern int proxy; /* proxy server connection active */
extern int proxflag; /* proxy connection exists */
extern int sunique; /* store files on server with unique name */
extern int runique; /* store local files with unique name */
extern int mcase; /* map upper to lower case for mget names */
extern int ntflag; /* use ntin ntout tables for name translation */
extern int mapflag; /* use mapin mapout templates on file names */
extern int code; /* return/reply code for ftp command */
extern int crflag; /* if 1, strip car. rets. on ascii gets */
extern char pasv[64]; /* passive port for proxy data connection */
extern int passivemode; /* passive mode enabled */
extern char *altarg; /* argv[1] with no shell-like preprocessing */
extern char ntin[17]; /* input translation table */
extern char ntout[17]; /* output translation table */
extern char mapin[MAXPATHLEN]; /* input map template */
extern char mapout[MAXPATHLEN]; /* output map template */
extern char typename[32]; /* name of file transfer type */
extern int type; /* file transfer type */
extern char structname[32]; /* name of file transfer structure */
extern int stru; /* file transfer structure */
extern char formname[32]; /* name of file transfer format */
extern int form; /* file transfer format */
extern char modename[32]; /* name of file transfer mode */
extern int mode; /* file transfer mode */
extern char bytename[32]; /* local byte size in ascii */
extern int bytesize; /* local byte size in binary */
extern jmp_buf toplevel; /* non-local goto stuff for cmd scanner */
extern char line[200]; /* input line buffer */
extern char *stringbase; /* current scan point in line buffer */
extern char argbuf[200]; /* argument storage buffer */
extern char *argbase; /* current storage point in arg buffer */
extern int margc; /* count of arguments on input line */
extern const char *margv[20]; /* args parsed from input line */
extern int cpend; /* flag: if != 0, then pending server reply */
extern int mflag; /* flag: if != 0, then active multi command */
extern int options; /* used during socket creation */
/*
* Format of command table.
*/
struct cmd {
const char *c_name; /* name of command */
const char *c_help; /* help string */
char c_bell; /* give bell when command completes */
char c_conn; /* must be connected to use command */
char c_proxy; /* proxy server may execute */
void (*c_handler)(); /* function to call */
};
struct macel {
char mac_name[9]; /* macro name */
char *mac_start; /* start of macro in macbuf */
char *mac_end; /* end of macro in macbuf */
};
int macnum; /* number of defined macros */
struct macel macros[16];
char macbuf[4096];
#if defined(__ANSI__) || defined(sparc)
typedef void sig_t;
#else
typedef int sig_t;
#endif
typedef int uid_t;
+598
View File
@@ -0,0 +1,598 @@
/*
* Copyright (c) 1985, 1989 Regents of the University of California.
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that the above copyright notice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by the University of California, Berkeley. The name of the
* University may not be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#ifndef lint
char copyright[] =
"@(#) Copyright (c) 1985, 1989 Regents of the University of California.\n\
All rights reserved.\n";
#endif /* not lint */
#ifndef lint
static char sccsid[] = "@(#)main.c based on 5.13 (Berkeley) 3/14/89";
#endif /* not lint */
/*
* FTP User Program -- Command Interface.
*/
#ifndef _WIN32
#include <netdb.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <arpa/ftp.h>
#include <errno.h>
#include <pwd.h>
#endif
#include "ftp_var.h"
#include "prototypes.h"
#include <sys/types.h>
#include <io.h>
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#if defined(sun) && !defined(FD_SET)
typedef int uid_t;
#endif
uid_t getuid();
void intr();
void lostpeer();
char *getlogin();
short portnum;
char home[128];
char *globerr;
int autologin;
/* Lot's of options... */
/*
* Options and other state info.
*/
int trace; /* trace packets exchanged */
int hash; /* print # for each buffer transferred */
int sendport; /* use PORT cmd for each data connection */
int verbose; /* print messages coming back from server */
int connected; /* connected to server */
int fromatty; /* input is from a terminal */
int interactive; /* interactively prompt on m* cmds */
int debug; /* debugging level */
int bell; /* ring bell on cmd completion */
int doglob; /* glob local file names */
int proxy; /* proxy server connection active */
int passivemode;
int proxflag; /* proxy connection exists */
int sunique; /* store files on server with unique name */
int runique; /* store local files with unique name */
int mcase; /* map upper to lower case for mget names */
int ntflag; /* use ntin ntout tables for name translation */
int mapflag; /* use mapin mapout templates on file names */
int code; /* return/reply code for ftp command */
int crflag; /* if 1, strip car. rets. on ascii gets */
char pasv[64]; /* passive port for proxy data connection */
char *altarg; /* argv[1] with no shell-like preprocessing */
char ntin[17]; /* input translation table */
char ntout[17]; /* output translation table */
// #include <sys/param.h>
char mapin[MAXPATHLEN]; /* input map template */
char mapout[MAXPATHLEN]; /* output map template */
char typename[32]; /* name of file transfer type */
int type; /* file transfer type */
char structname[32]; /* name of file transfer structure */
int stru; /* file transfer structure */
char formname[32]; /* name of file transfer format */
int form; /* file transfer format */
char modename[32]; /* name of file transfer mode */
int mode; /* file transfer mode */
char bytename[32]; /* local byte size in ascii */
int bytesize; /* local byte size in binary */
jmp_buf toplevel; /* non-local goto stuff for cmd scanner */
char line[200]; /* input line buffer */
char *stringbase; /* current scan point in line buffer */
char argbuf[200]; /* argument storage buffer */
char *argbase; /* current storage point in arg buffer */
int margc; /* count of arguments on input line */
const char *margv[20]; /* args parsed from input line */
int cpend; /* flag: if != 0, then pending server reply */
int mflag; /* flag: if != 0, then active multi command */
int options; /* used during socket creation */
static const char *slurpstring();
int main(int argc, const char *argv[])
{
const char *cp;
int top;
#if 0
char homedir[MAXPATHLEN];
#endif
int err;
WORD wVerReq;
WSADATA WSAData;
struct servent *sp; /* service spec for tcp/ftp */
/* Disable output buffering, for the benefit of Emacs. */
//setbuf(stdout, NULL);
_fmode = O_BINARY; // This causes an error somewhere.
wVerReq = MAKEWORD(1,1);
err = WSAStartup(wVerReq, &WSAData);
if (err != 0)
{
fprintf(stderr, "Could not initialize Windows socket interface.");
exit(1);
}
sp = getservbyname("ftp", "tcp");
if (sp == 0) {
fprintf(stderr, "ftp: ftp/tcp: unknown service\n");
exit(1);
}
portnum = sp->s_port;
doglob = 1;
interactive = 1;
autologin = 1;
argc--, argv++;
while (argc > 0 && **argv == '-') {
for (cp = *argv + 1; *cp; cp++)
switch (*cp) {
case 'd':
options |= SO_DEBUG;
debug++;
break;
case 'v':
verbose++;
break;
case 't':
trace++;
break;
case 'i':
interactive = 0;
break;
case 'n':
autologin = 0;
break;
case 'g':
doglob = 0;
break;
default:
fprintf(stdout,
"ftp: %c: unknown option\n", *cp);
exit(1);
}
argc--, argv++;
}
// fromatty = isatty(fileno(stdin));
fromatty = 1; // Strengthen this test
/*
* Set up defaults for FTP.
*/
(void) strcpy(typename, "ascii"), type = TYPE_A;
(void) strcpy(formname, "non-print"), form = FORM_N;
(void) strcpy(modename, "stream"), mode = MODE_S;
(void) strcpy(structname, "file"), stru = STRU_F;
(void) strcpy(bytename, "8"), bytesize = 8;
if (fromatty)
verbose++;
cpend = 0; /* no pending replies */
proxy = 0; /* proxy not active */
passivemode = 1; /* passive mode *is* active */
crflag = 1; /* strip c.r. on ascii gets */
/*
* Set up the home directory in case we're globbing.
*/
#if 0
cp = getlogin();
if (cp != NULL) {
pw = getpwnam(cp);
}
if (pw == NULL)
pw = getpwuid(getuid());
if (pw != NULL) {
home = homedir;
(void) strcpy(home, pw->pw_dir);
}
#endif
strcpy(home, "C:/");
if (argc > 0) {
if (setjmp(toplevel))
exit(0);
// (void) signal(SIGINT, intr);
// (void) signal(SIGPIPE, lostpeer);
setpeer(argc + 1, argv - 1);
}
top = setjmp(toplevel) == 0;
if (top) {
// (void) signal(SIGINT, intr);
// (void) signal(SIGPIPE, lostpeer);
}
for (;;) {
cmdscanner(top);
top = 1;
}
}
void
intr()
{
longjmp(toplevel, 1);
}
void lostpeer(void)
{
extern int cout;
extern int data;
if (connected) {
if (cout != (int) NULL) {
closesocket(cout);
cout = (int) NULL;
}
if (data >= 0) {
(void) shutdown(data, 1+1);
(void) close(data);
data = -1;
}
connected = 0;
}
pswitch(1);
if (connected) {
if (cout != (int)NULL) {
closesocket(cout);
cout = (int) NULL;
}
connected = 0;
}
proxflag = 0;
pswitch(0);
}
/*char *
tail(filename)
char *filename;
{
register char *s;
while (*filename) {
s = rindex(filename, '/');
if (s == NULL)
break;
if (s[1])
return (s + 1);
*s = '\0';
}
return (filename);
}
*/
/*
* Command parser.
*/
void cmdscanner(top)
int top;
{
register struct cmd *c;
if (!top)
(void) putchar('\n');
for (;;) {
(void) fflush(stdout);
if (fromatty) {
printf("ftp> ");
(void) fflush(stdout);
}
if (gets(line) == 0) {
if (feof(stdin) || ferror(stdin))
quit();
break;
}
if (line[0] == 0)
break;
makeargv();
if (margc == 0) {
continue;
}
c = getcmd(margv[0]);
if (c == (struct cmd *)-1) {
printf("?Ambiguous command\n");
continue;
}
if (c == 0) {
printf("?Invalid command\n");
continue;
}
if (c->c_conn && !connected) {
printf ("Not connected.\n");
continue;
}
(*c->c_handler)(margc, margv);
if (bell && c->c_bell)
(void) putchar('\007');
if (c->c_handler != help)
break;
}
(void) fflush(stdout);
// (void) signal(SIGINT, intr);
// (void) signal(SIGPIPE, lostpeer);
}
struct cmd *
getcmd(name)
const char *name;
{
extern struct cmd cmdtab[];
const char *p, *q;
struct cmd *c, *found;
int nmatches, longest;
longest = 0;
nmatches = 0;
found = 0;
for (c = cmdtab; (p = c->c_name); c++) {
for (q = name; *q == *p++; q++)
if (*q == 0) /* exact match? */
return (c);
if (!*q) { /* the name was a prefix */
if (q - name > longest) {
longest = q - name;
nmatches = 1;
found = c;
} else if (q - name == longest)
nmatches++;
}
}
if (nmatches > 1)
return ((struct cmd *)-1);
return (found);
}
/*
* Slice a string up into argc/argv.
*/
int slrflag;
void makeargv()
{
const char **argp;
margc = 0;
argp = margv;
stringbase = line; /* scan from first of buffer */
argbase = argbuf; /* store from first of buffer */
slrflag = 0;
while ((*argp++ = slurpstring()))
margc++;
}
/*
* Parse string into argbuf;
* implemented with FSM to
* handle quoting and strings
*/
static const char *
slurpstring()
{
int got_one = 0;
register char *sb = stringbase;
register char *ap = argbase;
char *tmp = argbase; /* will return this if token found */
if (*sb == '!' || *sb == '$') { /* recognize ! as a token for shell */
switch (slrflag) { /* and $ as token for macro invoke */
case 0:
slrflag++;
stringbase++;
return ((*sb == '!') ? "!" : "$");
/* NOTREACHED */
case 1:
slrflag++;
altarg = stringbase;
break;
default:
break;
}
}
S0:
switch (*sb) {
case '\0':
goto OUT1;
case ' ':
case '\t':
sb++; goto S0;
default:
switch (slrflag) {
case 0:
slrflag++;
break;
case 1:
slrflag++;
altarg = sb;
break;
default:
break;
}
goto S1;
}
S1:
switch (*sb) {
case ' ':
case '\t':
case '\0':
goto OUT1; /* end of token */
case '\\':
sb++; goto S2; /* slurp next character */
case '"':
sb++; goto S3; /* slurp quoted string */
default:
*ap++ = *sb++; /* add character to token */
got_one = 1;
goto S1;
}
S2:
switch (*sb) {
case '\0':
goto OUT1;
default:
*ap++ = *sb++;
got_one = 1;
goto S1;
}
S3:
switch (*sb) {
case '\0':
goto OUT1;
case '"':
sb++; goto S1;
default:
*ap++ = *sb++;
got_one = 1;
goto S3;
}
OUT1:
if (got_one)
*ap++ = '\0';
argbase = ap; /* update storage pointer */
stringbase = sb; /* update scan pointer */
if (got_one) {
return(tmp);
}
switch (slrflag) {
case 0:
slrflag++;
break;
case 1:
slrflag++;
altarg = (char *) 0;
break;
default:
break;
}
return((char *)0);
}
#define HELPINDENT (sizeof ("directory"))
/*
* Help command.
* Call each command handler with argc == 0 and argv[0] == name.
*/
void help(argc, argv)
int argc;
char *argv[];
{
extern struct cmd cmdtab[];
register struct cmd *c;
if (argc == 1) {
register int i, j, w, k;
int columns, width = 0, lines;
extern int NCMDS;
printf("Commands may be abbreviated. Commands are:\n\n");
for (c = cmdtab; c < &cmdtab[NCMDS]; c++) {
int len = strlen(c->c_name);
if (len > width)
width = len;
}
width = (width + 8) &~ 7;
columns = 80 / width;
if (columns == 0)
columns = 1;
lines = (NCMDS + columns - 1) / columns;
for (i = 0; i < lines; i++) {
for (j = 0; j < columns; j++) {
c = cmdtab + j * lines + i;
if (c->c_name && (!proxy || c->c_proxy)) {
printf("%s", c->c_name);
}
else if (c->c_name) {
for (k=0; k < (int) strlen(c->c_name); k++) {
(void) putchar(' ');
}
}
if (c + lines >= &cmdtab[NCMDS]) {
printf("\n");
break;
}
w = strlen(c->c_name);
while (w < width) {
w = (w + 8) &~ 7;
(void) putchar('\t');
}
}
}
(void) fflush(stdout);
return;
}
while (--argc > 0) {
register char *arg;
arg = *++argv;
c = getcmd(arg);
if (c == (struct cmd *)-1)
printf("?Ambiguous help command %s\n", arg);
else if (c == (struct cmd *)0)
printf("?Invalid help command %s\n", arg);
else
printf("%-*s\t%s\n", HELPINDENT,
c->c_name, c->c_help);
}
(void) fflush(stdout);
}
@@ -0,0 +1,21 @@
/*
* Copyright (c) 1989 The Regents of the University of California.
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that the above copyright notice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by the University of California, Berkeley. The name of the
* University may not be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* %W% (Berkeley) %G%
*/
#define _PATH_TMP "/tmp/ftpXXXXXX"
#define _PATH_BSHELL "/bin/sh"
@@ -0,0 +1,66 @@
int fgetcSocket(int s);
const char *fputsSocket(const char *format, int s);
const char *fprintfSocket(int s, const char *format, ...);
int fputcSocket(int s, char putChar);
int fputSocket(int s, char *putChar, int len);
char *fgetsSocket(int s, char *string);
char *hookup();
char **glob();
int herror(char *s);
int getreply(int expecteof);
int ruserpass(const char *host, char **aname, char **apass, char **aacct);
char *getpass(const char *prompt);
void makeargv(void);
void domacro(int argc, const char *argv[]);
void proxtrans(const char *cmd, const char *local, const char *remote);
int null(void);
int initconn(void);
void disconnect(void);
void ptransfer(const char *direction, long bytes, struct timeval *t0, struct timeval *t1);
void setascii(void);
void setbinary(void);
void setebcdic(void);
void settenex(void);
void tvsub(struct timeval *tdiff, struct timeval *t1, struct timeval *t0);
void setpassive(int argc, char *argv[]);
void setpeer(int argc, const char *argv[]);
void cmdscanner(int top);
void pswitch(int flag);
void quit(void);
int login(const char *host);
int command(const char *fmt, ...);
int globulize(const char **cpp);
void sendrequest(const char *cmd, const char *local, const char *remote, int printnames);
void recvrequest(const char *cmd, const char *local, const char *remote, const char *mode,
int printnames);
int confirm(const char *cmd, const char *file);
void blkfree(char **av0);
int getit(int argc, const char *argv[], int restartit, const char *mode);
int sleep(int time);
char *tail();
int errno;
char *mktemp();
void setbell(), setdebug();
void setglob(), sethash(), setport();
void setprompt();
void settrace(), setverbose();
void settype(), setform(), setstruct();
void restart(), syst();
void cd(), lcd(), delete(), mdelete();
void ls(), mls(), get(), mget(), help(), append(), put(), mput(), reget();
void status();
void renamefile();
void quote(), rmthelp(), site();
void pwd(), makedir(), removedir(), setcr();
void account(), doproxy(), reset(), setcase(), setntrans(), setnmap();
void setsunique(), setrunique(), cdup(), macdef();
void sizecmd(), modtime(), newer(), rmtstatus();
void do_chmod(), do_umask(), idle();
void shell(), user(), fsetmode();
struct cmd *getcmd();
@@ -0,0 +1,274 @@
/*
* Copyright (c) 1985 Regents of the University of California.
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted
* provided that the above copyright notice and this paragraph are
* duplicated in all such forms and that any documentation,
* advertising materials, and other materials related to such
* distribution and use acknowledge that the software was developed
* by the University of California, Berkeley. The name of the
* University may not be used to endorse or promote products derived
* from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
#ifndef lint
static char sccsid[] = "@(#)ruserpass.c 5.1 (Berkeley) 3/1/89";
#endif /* not lint */
#include <sys/types.h>
#include <stdio.h>
//#include <utmp.h>
#include <ctype.h>
#include <sys/stat.h>
#include <errno.h>
#include "ftp_var.h"
#include "prototypes.h"
#include <winsock.h>
char *renvlook(), *index(), *getenv(), *getpass(), *getlogin();
void *malloc();
char *strcpy();
struct utmp *getutmp();
static FILE *cfile;
#ifndef MAXHOSTNAMELEN
#define MAXHOSTNAMELEN 64
#endif
#define DEFAULT 1
#define LOGIN 2
#define PASSWD 3
#define ACCOUNT 4
#define MACDEF 5
#define ID 10
#define MACH 11
static char tokval[100];
static struct toktab {
const char *tokstr;
int tval;
} toktab[]= {
{"default", DEFAULT},
{"login", LOGIN},
{"password", PASSWD},
{"passwd", PASSWD},
{"account", ACCOUNT},
{"machine", MACH},
{"macdef", MACDEF},
{0, 0}
};
extern char *hostname;
static int token(void);
int ruserpass(const char *host, char **aname, char **apass, char **aacct)
{
const char *hdir, *mydomain;
char buf[BUFSIZ], *tmp;
char myname[MAXHOSTNAMELEN];
int t, i, c, usedefault = 0;
struct stat stb;
extern int errno;
hdir = getenv("HOME");
if (hdir == NULL)
hdir = ".";
(void) sprintf(buf, "%s/.netrc", hdir);
cfile = fopen(buf, "r");
if (cfile == NULL) {
if (errno != ENOENT)
perror(buf);
return(0);
}
if (gethostname(myname, sizeof(myname)) < 0)
myname[0] = '\0';
if ((mydomain = index(myname, '.')) == NULL)
mydomain = "";
next:
while ((t = token())) switch(t) {
case DEFAULT:
usedefault = 1;
/* FALL THROUGH */
case MACH:
if (!usedefault) {
if (token() != ID)
continue;
/*
* Allow match either for user's input host name
* or official hostname. Also allow match of
* incompletely-specified host in local domain.
*/
if (strcasecmp(host, tokval) == 0)
goto match;
if (strcasecmp(hostname, tokval) == 0)
goto match;
if ((tmp = index(hostname, '.')) != NULL &&
strcasecmp(tmp, mydomain) == 0 &&
strncasecmp(hostname, tokval, tmp - hostname) == 0 &&
tokval[tmp - hostname] == '\0')
goto match;
if ((tmp = index(host, '.')) != NULL &&
strcasecmp(tmp, mydomain) == 0 &&
strncasecmp(host, tokval, tmp - host) == 0 &&
tokval[tmp - host] == '\0')
goto match;
continue;
}
match:
while ((t = token()) && t != MACH && t != DEFAULT) switch(t) {
case LOGIN:
if (token()) {
if (*aname == 0) {
*aname = malloc((unsigned) strlen(tokval) + 1);
(void) strcpy(*aname, tokval);
} else {
if (strcmp(*aname, tokval))
goto next;
}
}
break;
case PASSWD:
if (strcmp(*aname, "anonymous") &&
fstat(fileno(cfile), &stb) >= 0 &&
(stb.st_mode & 077) != 0) {
fprintf(stderr, "Error - .netrc file not correct mode.\n");
fprintf(stderr, "Remove password or correct mode.\n");
goto bad;
}
if (token() && *apass == 0) {
*apass = malloc((unsigned) strlen(tokval) + 1);
(void) strcpy(*apass, tokval);
}
break;
case ACCOUNT:
if (fstat(fileno(cfile), &stb) >= 0
&& (stb.st_mode & 077) != 0) {
fprintf(stderr, "Error - .netrc file not correct mode.\n");
fprintf(stderr, "Remove account or correct mode.\n");
goto bad;
}
if (token() && *aacct == 0) {
*aacct = malloc((unsigned) strlen(tokval) + 1);
(void) strcpy(*aacct, tokval);
}
break;
case MACDEF:
if (proxy) {
(void) fclose(cfile);
return(0);
}
while ((c=getc(cfile)) != EOF && (c == ' ' || c == '\t'));
if (c == EOF || c == '\n') {
printf("Missing macdef name argument.\n");
goto bad;
}
if (macnum == 16) {
printf("Limit of 16 macros have already been defined\n");
goto bad;
}
tmp = macros[macnum].mac_name;
*tmp++ = c;
for (i=0; i < 8 && (c=getc(cfile)) != EOF &&
!isspace(c); ++i) {
*tmp++ = c;
}
if (c == EOF) {
printf("Macro definition missing null line terminator.\n");
goto bad;
}
*tmp = '\0';
if (c != '\n') {
while ((c=getc(cfile)) != EOF && c != '\n');
}
if (c == EOF) {
printf("Macro definition missing null line terminator.\n");
goto bad;
}
if (macnum == 0) {
macros[macnum].mac_start = macbuf;
}
else {
macros[macnum].mac_start = macros[macnum-1].mac_end + 1;
}
tmp = macros[macnum].mac_start;
while (tmp != macbuf + 4096) {
if ((c=getc(cfile)) == EOF) {
printf("Macro definition missing null line terminator.\n");
goto bad;
}
*tmp = c;
if (*tmp == '\n') {
if (*(tmp-1) == '\0') {
macros[macnum++].mac_end = tmp - 1;
break;
}
*tmp = '\0';
}
tmp++;
}
if (tmp == macbuf + 4096) {
printf("4K macro buffer exceeded\n");
goto bad;
}
break;
default:
fprintf(stderr, "Unknown .netrc keyword %s\n", tokval);
break;
}
goto done;
}
done:
(void) fclose(cfile);
return(0);
bad:
(void) fclose(cfile);
return(-1);
}
static int token(void)
{
char *cp;
int c;
struct toktab *t;
if (feof(cfile))
return (0);
while ((c = getc(cfile)) != EOF &&
(c == '\r' || c == '\n' || c == '\t' || c == ' ' || c == ','))
continue;
if (c == EOF)
return (0);
cp = tokval;
if (c == '"') {
while ((c = getc(cfile)) != EOF && c != '"') {
if (c == '\\')
c = getc(cfile);
*cp++ = c;
}
} else {
*cp++ = c;
while ((c = getc(cfile)) != EOF
&& c != '\n' && c != '\t' && c != ' ' && c != ',' && c != '\r') {
if (c == '\\')
c = getc(cfile);
*cp++ = c;
}
}
*cp = 0;
if (tokval[0] == 0)
return (0);
for (t = toktab; t->tokstr; t++)
if (!strcmp(t->tokstr, tokval))
return (t->tval);
return (ID);
}
@@ -0,0 +1,517 @@
/*
* ReactOS Win32 Applications
* Copyright (C) 2005 ReactOS Team
*
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS arp utility
* FILE: apps/utils/net/ipconfig/ipconfig.c
* PURPOSE:
* PROGRAMMERS: Ged Murphy ([email protected])
* REVISIONS:
* GM 14/09/05 Created
*
*/
/*
* TODO:
* fix renew / release
* implement flushdns, registerdns, displaydns, showclassid, setclassid
* allow globbing on adapter names
*/
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <tchar.h>
#include <string.h>
#include <ctype.h>
#include <winsock2.h>
#include <iphlpapi.h>
#define UNICODE
#define _UNICODE
LPCTSTR GetNodeTypeName(UINT NodeType)
{
switch (NodeType) {
case 1: return _T("Broadcast");
case 2: return _T("Peer To Peer");
case 4: return _T("Mixed");
case 8: return _T("Hybrid");
default : return _T("unknown");
}
}
LPCTSTR GetInterfaceTypeName(UINT InterfaceType)
{
switch (InterfaceType) {
case MIB_IF_TYPE_OTHER: return _T("Other Type Of Adapter");
case MIB_IF_TYPE_ETHERNET: return _T("Ethernet Adapter");
case MIB_IF_TYPE_TOKENRING: return _T("Token Ring Adapter");
case MIB_IF_TYPE_FDDI: return _T("FDDI Adapter");
case MIB_IF_TYPE_PPP: return _T("PPP Adapter");
case MIB_IF_TYPE_LOOPBACK: return _T("Loopback Adapter");
case MIB_IF_TYPE_SLIP: return _T("SLIP Adapter");
default: return _T("unknown");
}
}
/* print MAC address */
PTCHAR PrintMacAddr(PBYTE Mac)
{
static TCHAR MacAddr[20];
_stprintf(MacAddr, _T("%02x-%02x-%02x-%02x-%02x-%02x"),
Mac[0], Mac[1], Mac[2], Mac[3], Mac[4], Mac[5]);
return MacAddr;
}
DWORD DoFormatMessage(DWORD ErrorCode)
{
LPVOID lpMsgBuf;
DWORD RetVal;
if ((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 ))) {
_tprintf(_T("%s"), (LPTSTR)lpMsgBuf);
LocalFree(lpMsgBuf);
/* return number of TCHAR's stored in output buffer
* excluding '\0' - as FormatMessage does*/
return RetVal;
}
else
return 0;
}
INT ShowInfo(BOOL bAll)
{
PIP_ADAPTER_INFO pAdapterInfo = NULL;
PIP_ADAPTER_INFO pAdapter = NULL;
ULONG adaptOutBufLen;
PFIXED_INFO pFixedInfo;
ULONG netOutBufLen;
PIP_ADDR_STRING pIPAddr = NULL;
DWORD ErrRet = 0;
/* assign memory for call to GetNetworkParams */
pFixedInfo = (FIXED_INFO *) GlobalAlloc( GPTR, sizeof( FIXED_INFO ) );
netOutBufLen = sizeof(FIXED_INFO);
/* assign memory for call to GetAdapterInfo */
pAdapterInfo = (IP_ADAPTER_INFO *) malloc( sizeof(IP_ADAPTER_INFO) );
adaptOutBufLen = sizeof(IP_ADAPTER_INFO);
/* set required buffer size */
if(GetNetworkParams(pFixedInfo, &netOutBufLen) == ERROR_BUFFER_OVERFLOW)
{
GlobalFree(pFixedInfo);
pFixedInfo = (FIXED_INFO *) GlobalAlloc(GPTR, netOutBufLen);
}
/* set required buffer size */
if (GetAdaptersInfo( pAdapterInfo, &adaptOutBufLen) == ERROR_BUFFER_OVERFLOW)
{
free(pAdapterInfo);
pAdapterInfo = (IP_ADAPTER_INFO *) malloc (adaptOutBufLen);
}
if ((ErrRet = GetAdaptersInfo(pAdapterInfo, &adaptOutBufLen)) != NO_ERROR)
{
_tprintf(_T("GetAdaptersInfo failed : "));
DoFormatMessage(ErrRet);
return EXIT_FAILURE;
}
if ((ErrRet = GetNetworkParams(pFixedInfo, &netOutBufLen)) != NO_ERROR)
{
_tprintf(_T("GetNetworkParams failed : "));
DoFormatMessage(ErrRet);
return EXIT_FAILURE;
}
pAdapter = pAdapterInfo;
_tprintf(_T("\nReactOS IP Configuration\n\n"));
if (bAll)
{
_tprintf(_T("\tHost Name . . . . . . . . . . . . : %s\n"), pFixedInfo->HostName);
_tprintf(_T("\tPrimary DNS Suffix. . . . . . . . : \n"));
_tprintf(_T("\tNode Type . . . . . . . . . . . . : %s\n"), GetNodeTypeName(pFixedInfo->NodeType));
if (pFixedInfo->EnableRouting)
_tprintf(_T("\tIP Routing Enabled. . . . . . . . : Yes\n"));
else
_tprintf(_T("\tIP Routing Enabled. . . . . . . . : No\n"));
if (pAdapter->HaveWins)
_tprintf(_T("\tWINS Proxy enabled. . . . . . . . : Yes\n"));
else
_tprintf(_T("\tWINS Proxy enabled. . . . . . . . : No\n"));
_tprintf(_T("\tDNS Suffix Search List. . . . . . : %s\n"), pFixedInfo->DomainName);
}
while (pAdapter)
{
_tprintf(_T("\n%s ...... : \n\n"), GetInterfaceTypeName(pAdapter->Type));
/* check if the adapter is connected to the media */
if (_tcscmp(pAdapter->IpAddressList.IpAddress.String, "0.0.0.0") == 0)
{
_tprintf(_T("\tMedia State . . . . . . . . . . . : Media disconnected\n"));
pAdapter = pAdapter->Next;
continue;
}
_tprintf(_T("\tConnection-specific DNS Suffix. . : %s\n"), pFixedInfo->DomainName);
if (bAll)
{
_tprintf(_T("\tDescription . . . . . . . . . . . : %s\n"), pAdapter->Description);
_tprintf(_T("\tPhysical Address. . . . . . . . . : %s\n"), PrintMacAddr(pAdapter->Address));
if (pAdapter->DhcpEnabled)
_tprintf(_T("\tDHCP Enabled. . . . . . . . . . . : Yes\n"));
else
_tprintf(_T("\tDHCP Enabled. . . . . . . . . . . : No\n"));
_tprintf(_T("\tAutoconfiguration Enabled . . . . : \n"));
}
_tprintf(_T("\tIP Address. . . . . . . . . . . . : %s\n"), pAdapter->IpAddressList.IpAddress.String);
_tprintf(_T("\tSubnet Mask . . . . . . . . . . . : %s\n"), pAdapter->IpAddressList.IpMask.String);
_tprintf(_T("\tDefault Gateway . . . . . . . . . : %s\n"), pAdapter->GatewayList.IpAddress.String);
if (bAll)
{
if (pAdapter->DhcpEnabled)
_tprintf(_T("\tDHCP Server . . . . . . . . . . . : %s\n"), pAdapter->DhcpServer.IpAddress.String);
_tprintf(_T("\tDNS Servers . . . . . . . . . . . : "));
_tprintf(_T("%s\n"), pFixedInfo->DnsServerList.IpAddress.String);
pIPAddr = pFixedInfo -> DnsServerList.Next;
while (pIPAddr)
{
_tprintf(_T("\t\t\t\t\t %s\n"), pIPAddr ->IpAddress.String );
pIPAddr = pIPAddr ->Next;
}
if (pAdapter->HaveWins)
{
_tprintf(_T("\tPrimary WINS Server . . . . . . . : %s\n"), pAdapter->PrimaryWinsServer.IpAddress.String);
_tprintf(_T("\tSecondard WINS Server . . . . . . : %s\n"), pAdapter->SecondaryWinsServer.IpAddress.String);
}
if (pAdapter->DhcpEnabled)
{
_tprintf(_T("\tLease Obtained. . . . . . . . . . : %s"), _tasctime(localtime(&pAdapter->LeaseObtained)));
_tprintf(_T("\tLease Expires . . . . . . . . . . : %s"), _tasctime(localtime(&pAdapter->LeaseExpires)));
}
}
_tprintf(_T("\n"));
pAdapter = pAdapter->Next;
}
return 0;
}
INT Release(TCHAR Index)
{
IP_ADAPTER_INDEX_MAP AdapterInfo;
DWORD dwRetVal = 0;
/* if interface is not given, query GetInterfaceInfo */
if (Index == (TCHAR)NULL)
{
PIP_INTERFACE_INFO pInfo;
ULONG ulOutBufLen;
pInfo = (IP_INTERFACE_INFO *) malloc(sizeof(IP_INTERFACE_INFO));
ulOutBufLen = 0;
/* Make an initial call to GetInterfaceInfo to get
* the necessary size into the ulOutBufLen variable */
if ( GetInterfaceInfo(pInfo, &ulOutBufLen) == ERROR_INSUFFICIENT_BUFFER)
{
GlobalFree(pInfo);
pInfo = (IP_INTERFACE_INFO *) malloc (ulOutBufLen);
}
/* Make a second call to GetInterfaceInfo to get the actual data we want */
if ((dwRetVal = GetInterfaceInfo(pInfo, &ulOutBufLen)) == NO_ERROR )
{
AdapterInfo = pInfo->Adapter[0];
_tprintf(_T("name - %S\n"), pInfo->Adapter[0].Name);
}
else
{
_tprintf(_T("\nGetInterfaceInfo failed : "));
DoFormatMessage(dwRetVal);
}
}
else
{
;
/* we need to be able to release connections by name with support for globbing
* i.e. ipconfig /release Eth* will release all cards starting with Eth...
* ipconfig /release *con* will release all cards with 'con' in their name
*/
}
/* Call IpReleaseAddress to release the IP address on the specified adapter. */
if ((dwRetVal = IpReleaseAddress(&AdapterInfo)) != NO_ERROR)
{
_tprintf(_T("\nAn error occured while releasing interface %s : "), _T("*name*"));
DoFormatMessage(dwRetVal);
}
return 0;
}
INT Renew(TCHAR Index)
{
IP_ADAPTER_INDEX_MAP AdapterInfo;
DWORD dwRetVal = 0;
/* if interface is not given, query GetInterfaceInfo */
if (Index == (TCHAR)NULL)
{
PIP_INTERFACE_INFO pInfo;
ULONG ulOutBufLen;
pInfo = (IP_INTERFACE_INFO *) malloc(sizeof(IP_INTERFACE_INFO));
ulOutBufLen = 0;
/* Make an initial call to GetInterfaceInfo to get
* the necessary size into the ulOutBufLen variable */
if ( GetInterfaceInfo(pInfo, &ulOutBufLen) == ERROR_INSUFFICIENT_BUFFER)
{
GlobalFree(pInfo);
pInfo = (IP_INTERFACE_INFO *) malloc (ulOutBufLen);
}
/* Make a second call to GetInterfaceInfo to get the actual data we want */
if ((dwRetVal = GetInterfaceInfo(pInfo, &ulOutBufLen)) == NO_ERROR )
{
AdapterInfo = pInfo->Adapter[0];
_tprintf(_T("name - %S\n"), pInfo->Adapter[0].Name);
} else {
_tprintf(_T("\nGetInterfaceInfo failed : "));
DoFormatMessage(dwRetVal);
}
}
else
{
;
/* we need to be able to renew connections by name with support for globbing
* i.e. ipconfig /renew Eth* will renew all cards starting with Eth...
* ipconfig /renew *con* will renew all cards with 'con' in their name
*/
}
/* Call IpRenewAddress to renew the IP address on the specified adapter. */
if ((dwRetVal = IpRenewAddress(&AdapterInfo)) != NO_ERROR)
{
_tprintf(_T("\nAn error occured while renew interface %s : "), _T("*name*"));
DoFormatMessage(dwRetVal);
}
return 0;
}
/* temp func for testing purposes */
VOID Info()
{
// Declare and initialize variables
PIP_INTERFACE_INFO pInfo;
ULONG ulOutBufLen;
DWORD dwRetVal;
pInfo = (IP_INTERFACE_INFO *) malloc( sizeof(IP_INTERFACE_INFO) );
ulOutBufLen = sizeof(IP_INTERFACE_INFO);
dwRetVal = 0;
// Make an initial call to GetInterfaceInfo to get
// the necessary size in the ulOutBufLen variable
if ( GetInterfaceInfo(pInfo, &ulOutBufLen) == ERROR_INSUFFICIENT_BUFFER)
{
free(pInfo);
pInfo = (IP_INTERFACE_INFO *) malloc (ulOutBufLen);
}
// Make a second call to GetInterfaceInfo to get
// the actual data we need
if ((dwRetVal = GetInterfaceInfo(pInfo, &ulOutBufLen)) == NO_ERROR )
{
int i;
for (i=0; i<pInfo->NumAdapters; i++)
{
printf("\tAdapter Name: %S\n", pInfo->Adapter[i].Name);
printf("\tAdapter Index: %ld\n", pInfo->Adapter[i].Index);
printf("\tNum Adapters: %ld\n", pInfo->NumAdapters);
}
}
else
{
printf("GetInterfaceInfo failed.\n");
DoFormatMessage(dwRetVal);
}
}
VOID Usage(VOID)
{
_tprintf(_T("\nUSAGE:\n"
" ipconfig [/? | /all | /renew [adapter] | /release [adapter] |\n"
" /flushdns | /displaydns | /registerdns |\n"
" /showclassid adapter |\n"
" /setclassid adapter [classid] ]\n"
"\n"
"where\n"
" adapter Connection name\n"
" (wildcard characters * and ? allowed, see examples)\n"
"\n"
" Options:\n"
" /? Display this help message\n"
" /all Display full configuration information.\n"
" /release Release the IP address for the specified adapter.\n"
" /renew Renew the IP address for the specified adapter.\n"
" /flushdns Purges the DNS Resolver cache.\n"
" /registerdns Refreshes all DHCP leases and re-registers DNS names.\n"
" /displaydns Display the contents of the DNS Resolver Cache.\n"
" /showclassid Displays all the dhcp class IDs allowed for adapter.\n"
" /setclassid Modifies the dhcp class id.\n"
"\n"
"The default is to display only the IP address, subnet mask and\n"
"default gateway for each adapter bound to TCP/IP.\n"
"\n"
"For Release and Renew, if no adapter name is specified, then the IP address\n"
"leases for all adapters bound to TCP/IP will be released or renewed.\n"
"\n"
"For Setclassid, if no ClassId is specified, then the ClassId is removed.\n"
"\n"
"Examples:\n"
" > ipconfig ... Show information.\n"
" > ipconfig /all ... Show detailed information\n"
" > ipconfig /renew ... renew all adapters\n"
" > ipconfig /renew EL* ... renew any connection that has its\n"
" name starting with EL\n"
" > ipconfig /release *Con* ... release all matching connections,\n"
" eg. \"Local Area Connection 1\" or\n"
" \"Local Area Connection 2\"\n"));
}
int main(int argc, char *argv[])
{
BOOL DoUsage=FALSE;
BOOL DoAll=FALSE;
BOOL DoRelease=FALSE;
BOOL DoRenew=FALSE;
BOOL DoFlushdns=FALSE;
BOOL DoRegisterdns=FALSE;
BOOL DoDisplaydns=FALSE;
BOOL DoShowclassid=FALSE;
BOOL DoSetclassid=FALSE;
/* Parse command line for options we have been given. */
if ( (argc > 1)&&(argv[1][0]=='/') )
{
if( !_tcsicmp( &argv[1][1], _T("?") ))
{
DoUsage = TRUE;
}
else if( !_tcsnicmp( &argv[1][1], _T("ALL"), _tcslen(&argv[1][1]) ))
{
DoAll = TRUE;
}
else if( !_tcsnicmp( &argv[1][1], _T("RELEASE"), _tcslen(&argv[1][1]) ))
{
DoRelease = TRUE;
}
else if( ! _tcsnicmp( &argv[1][1], _T("RENEW"), _tcslen(&argv[1][1]) ))
{
DoRenew = TRUE;
}
else if( ! _tcsnicmp( &argv[1][1], _T("FLUSHDNS"), _tcslen(&argv[1][1]) ))
{
DoFlushdns = TRUE;
}
else if( ! _tcsnicmp( &argv[1][1], _T("FLUSHREGISTERDNS"), _tcslen(&argv[1][1]) ))
{
DoRegisterdns = TRUE;
}
else if( ! _tcsnicmp( &argv[1][1], _T("DISPLAYDNS"), _tcslen(&argv[1][1]) ))
{
DoDisplaydns = TRUE;
}
else if( ! _tcsnicmp( &argv[1][1], _T("SHOWCLASSID"), _tcslen(&argv[1][1]) ))
{
DoShowclassid = TRUE;
}
else if( ! _tcsnicmp( &argv[1][1], _T("SETCLASSID"), _tcslen(&argv[1][1]) ))
{
DoSetclassid = TRUE;
}
}
switch (argc)
{
case 1: /* Default behaviour if no options are given*/
ShowInfo(FALSE);
break;
case 2: /* Process all the options that take no paramiters */
if (DoUsage)
Usage();
else if (DoAll)
ShowInfo(TRUE);
else if (DoRelease)
Release((TCHAR)NULL);
else if (DoRenew)
Renew((TCHAR)NULL);
else if (DoFlushdns)
_tprintf(_T("\nSorry /flushdns is not implemented yet\n"));
else if (DoRegisterdns)
_tprintf(_T("\nSorry /registerdns is not implemented yet\n"));
else if (DoDisplaydns)
_tprintf(_T("\nSorry /displaydns is not implemented yet\n"));
else
Usage();
break;
case 3: /* Process all the options that can have 1 paramiters */
if (DoRelease)
_tprintf(_T("\nSorry /release [adapter] is not implemented yet\n"));
//Release(argv[2]);
else if (DoRenew)
_tprintf(_T("\nSorry /renew [adapter] is not implemented yet\n"));
else if (DoShowclassid)
_tprintf(_T("\nSorry /showclassid adapter is not implemented yet\n"));
else if (DoSetclassid)
_tprintf(_T("\nSorry /setclassid adapter is not implemented yet\n"));
else
Usage();
break;
case 4: /* Process all the options that can have 2 paramiters */
if (DoSetclassid)
_tprintf(_T("\nSorry /setclassid adapter [classid]is not implemented yet\n"));
else
Usage();
break;
default:
Usage();
}
return 0;
}
@@ -0,0 +1,5 @@
#define REACTOS_STR_FILE_DESCRIPTION "ReactOS TCP/IPv4 Win32 ipconfig\0"
#define REACTOS_STR_INTERNAL_NAME "ipconfig\0"
#define REACTOS_STR_ORIGINAL_FILENAME "ipconfig.exe\0"
#define REACTOS_STR_ORIGINAL_COPYRIGHT "Ged Murphy ([email protected])\0"
#include <reactos/version.rc>
@@ -0,0 +1,9 @@
<module name="ipconfig" type="win32cui" installbase="system32" installname="ipconfig.exe" allowwarnings="true">
<include base="ipconfig">.</include>
<define name="__USE_W32API" />
<library>kernel32</library>
<library>user32</library>
<library>iphlpapi</library>
<file>ipconfig.c</file>
<file>ipconfig.rc</file>
</module>
@@ -0,0 +1,642 @@
/*
* PROJECT: ReactOS netstat utility
* LICENSE: GPL - See COPYING in the top level directory
* FILE: apps/utils/net/netstat/netstat.c
* PURPOSE: display IP stack statistics
* COPYRIGHT: Copyright 2005 Ged Murphy <[email protected]>
*/
/*
* TODO:
* sort function return values.
* implement -b, -o and -v
* clean up GetIpHostName
* command line parser needs more work
*/
#include <windows.h>
#include <winsock.h>
#include <tchar.h>
#include <stdio.h>
#include <iphlpapi.h>
#include "netstat.h"
enum ProtoType {IP, TCP, UDP, ICMP} Protocol;
DWORD Interval; /* time to pause between printing output */
/* TCP endpoint states */
TCHAR TcpState[][32] = {
_T("???"),
_T("CLOSED"),
_T("LISTENING"),
_T("SYN_SENT"),
_T("SYN_RCVD"),
_T("ESTABLISHED"),
_T("FIN_WAIT1"),
_T("FIN_WAIT2"),
_T("CLOSE_WAIT"),
_T("CLOSING"),
_T("LAST_ACK"),
_T("TIME_WAIT"),
_T("DELETE_TCB")
};
/*
* format message string and display output
*/
DWORD DoFormatMessage(DWORD ErrorCode)
{
LPVOID lpMsgBuf;
DWORD RetVal;
if ((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 )))
{
_tprintf(_T("%s"), (LPTSTR)lpMsgBuf);
LocalFree(lpMsgBuf);
/* return number of TCHAR's stored in output buffer
* excluding '\0' - as FormatMessage does*/
return RetVal;
}
else
return 0;
}
/*
*
* Parse command line parameters and set any options
*
*/
BOOL ParseCmdline(int argc, char* argv[])
{
INT i;
TCHAR Proto[5];
if ((argc == 1) || (_istdigit(*argv[1])))
bNoOptions = TRUE;
/* Parse command line for options we have been given. */
for (i = 1; i < argc; i++)
{
if ( (argc > 1)&&(argv[i][0] == '-') )
{
TCHAR c;
while ((c = *++argv[i]) != '\0')
{
switch (tolower(c))
{
case 'a' :
bDoShowAllCons = TRUE;
break;
case 'b' :
bDoShowProcName = TRUE;
break;
case 'e' :
bDoShowEthStats = TRUE;
break;
case 'n' :
bDoShowNumbers = TRUE;
break;
case 's' :
bDoShowProtoStats = TRUE;
break;
case 'p' :
bDoShowProtoCons = TRUE;
strncpy(Proto, (++argv)[i], sizeof(Proto));
if (!_tcsicmp( "IP", Proto ))
Protocol = IP;
else if (!_tcsicmp( "ICMP", Proto ))
Protocol = ICMP;
else if (!_tcsicmp( "TCP", Proto ))
Protocol = TCP;
else if (!_tcsicmp( "UDP", Proto ))
Protocol = UDP;
else
{
Usage();
return EXIT_FAILURE;
}
(--argv)[i]; /* move pointer back down to previous argv */
break;
case 'r' :
bDoShowRouteTable = TRUE;
break;
case 'v' :
_tprintf(_T("got v\n"));
bDoDispSeqComp = TRUE;
break;
default :
Usage();
return EXIT_FAILURE;
}
}
}
else if (_istdigit(*argv[i]))
{
if (_stscanf(argv[i], "%lu", &Interval) != EOF)
bLoopOutput = TRUE;
else
return EXIT_FAILURE;
}
// else
// {
// Usage();
// EXIT_FAILURE;
// }
}
return EXIT_SUCCESS;
}
/*
* Simulate Microsofts netstat utility output
*/
BOOL DisplayOutput()
{
if (bNoOptions)
{
_tprintf(_T("\n Proto Local Address Foreign Address State\n"));
ShowTcpTable();
return EXIT_SUCCESS;
}
if (bDoShowRouteTable)
{
/* mingw doesn't have lib for _tsystem */
if (system("route print") == -1)
{
_tprintf(_T("cannot find 'route.exe'\n"));
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
if (bDoShowEthStats)
{
ShowEthernetStatistics();
return EXIT_SUCCESS;
}
if (bDoShowProtoCons)
{
switch (Protocol)
{
case IP :
if (bDoShowProtoStats)
{
ShowIpStatistics();
return EXIT_SUCCESS;
}
break;
case ICMP :
if (bDoShowProtoStats)
{
ShowIcmpStatistics();
return EXIT_SUCCESS;
}
break;
case TCP :
if (bDoShowProtoStats)
ShowTcpStatistics();
_tprintf(_T("\nActive Connections\n"));
_tprintf(_T("\n Proto Local Address Foreign Address State\n"));
ShowTcpTable();
break;
case UDP :
if (bDoShowProtoStats)
ShowUdpStatistics();
_tprintf(_T("\nActive Connections\n"));
_tprintf(_T("\n Proto Local Address Foreign Address State\n"));
ShowUdpTable();
break;
default :
break;
}
}
else if (bDoShowProtoStats)
{
ShowIpStatistics();
ShowIcmpStatistics();
ShowTcpStatistics();
ShowUdpStatistics();
return EXIT_SUCCESS;
}
else //if (bDoShowAllCons)
{
_tprintf(_T("\nActive Connections\n"));
_tprintf(_T("\n Proto Local Address Foreign Address State\n"));
ShowTcpTable();
ShowUdpTable();
}
return EXIT_SUCCESS;
}
VOID ShowIpStatistics()
{
PMIB_IPSTATS pIpStats;
DWORD dwRetVal;
pIpStats = (MIB_IPSTATS*) HeapAlloc(GetProcessHeap(), 0, sizeof(MIB_IPSTATS));
if ((dwRetVal = GetIpStatistics(pIpStats)) == NO_ERROR)
{
_tprintf(_T("\nIPv4 Statistics\n\n"));
_tprintf(_T(" %-34s = %lu\n"), _T("Packets Recieved"), pIpStats->dwInReceives);
_tprintf(_T(" %-34s = %lu\n"), _T("Received Header Errors"), pIpStats->dwInHdrErrors);
_tprintf(_T(" %-34s = %lu\n"), _T("Received Address Errors"), pIpStats->dwInAddrErrors);
_tprintf(_T(" %-34s = %lu\n"), _T("Datagrams Forwarded"), pIpStats->dwForwDatagrams);
_tprintf(_T(" %-34s = %lu\n"), _T("Unknown Protocols Recieved"), pIpStats->dwInUnknownProtos);
_tprintf(_T(" %-34s = %lu\n"), _T("Received Packets Discarded"), pIpStats->dwInDiscards);
_tprintf(_T(" %-34s = %lu\n"), _T("Recieved Packets Delivered"), pIpStats->dwInDelivers);
_tprintf(_T(" %-34s = %lu\n"), _T("Output Requests"), pIpStats->dwOutRequests);
_tprintf(_T(" %-34s = %lu\n"), _T("Routing Discards"), pIpStats->dwRoutingDiscards);
_tprintf(_T(" %-34s = %lu\n"), _T("Discarded Output Packets"), pIpStats->dwOutDiscards);
_tprintf(_T(" %-34s = %lu\n"), _T("Output Packets No Route"), pIpStats->dwOutNoRoutes);
_tprintf(_T(" %-34s = %lu\n"), _T("Reassembly Required"), pIpStats->dwReasmReqds);
_tprintf(_T(" %-34s = %lu\n"), _T("Reassembly Succesful"), pIpStats->dwReasmOks);
_tprintf(_T(" %-34s = %lu\n"), _T("Reassembly Failures"), pIpStats->dwReasmFails);
// _tprintf(_T(" %-34s = %lu\n"), _T("Datagrams succesfully fragmented"), NULL); /* FIXME: what is this one? */
_tprintf(_T(" %-34s = %lu\n"), _T("Datagrams Failing Fragmentation"), pIpStats->dwFragFails);
_tprintf(_T(" %-34s = %lu\n"), _T("Fragments Created"), pIpStats->dwFragCreates);
}
else
DoFormatMessage(dwRetVal);
HeapFree(GetProcessHeap(), 0, pIpStats);
}
VOID ShowIcmpStatistics()
{
PMIB_ICMP pIcmpStats;
DWORD dwRetVal;
pIcmpStats = (MIB_ICMP*) HeapAlloc(GetProcessHeap(), 0, sizeof(MIB_ICMP));
if ((dwRetVal = GetIcmpStatistics(pIcmpStats)) == NO_ERROR)
{
_tprintf(_T("\nICMPv4 Statistics\n\n"));
_tprintf(_T(" Received Sent\n"));
_tprintf(_T(" %-25s %-11lu %lu\n"), _T("Messages"),
pIcmpStats->stats.icmpInStats.dwMsgs, pIcmpStats->stats.icmpOutStats.dwMsgs);
_tprintf(_T(" %-25s %-11lu %lu\n"), _T("Errors"),
pIcmpStats->stats.icmpInStats.dwErrors, pIcmpStats->stats.icmpOutStats.dwErrors);
_tprintf(_T(" %-25s %-11lu %lu\n"), _T("Destination Unreachable"),
pIcmpStats->stats.icmpInStats.dwDestUnreachs, pIcmpStats->stats.icmpOutStats.dwDestUnreachs);
_tprintf(_T(" %-25s %-11lu %lu\n"), _T("Time Exceeded"),
pIcmpStats->stats.icmpInStats.dwTimeExcds, pIcmpStats->stats.icmpOutStats.dwTimeExcds);
_tprintf(_T(" %-25s %-11lu %lu\n"), _T("Parameter Problems"),
pIcmpStats->stats.icmpInStats.dwParmProbs, pIcmpStats->stats.icmpOutStats.dwParmProbs);
_tprintf(_T(" %-25s %-11lu %lu\n"), _T("Source Quenches"),
pIcmpStats->stats.icmpInStats.dwSrcQuenchs, pIcmpStats->stats.icmpOutStats.dwSrcQuenchs);
_tprintf(_T(" %-25s %-11lu %lu\n"), _T("Redirects"),
pIcmpStats->stats.icmpInStats.dwRedirects, pIcmpStats->stats.icmpOutStats.dwRedirects);
_tprintf(_T(" %-25s %-11lu %lu\n"), _T("Echos"),
pIcmpStats->stats.icmpInStats.dwEchos, pIcmpStats->stats.icmpOutStats.dwEchos);
_tprintf(_T(" %-25s %-11lu %lu\n"), _T("Echo Replies"),
pIcmpStats->stats.icmpInStats.dwEchoReps, pIcmpStats->stats.icmpOutStats.dwEchoReps);
_tprintf(_T(" %-25s %-11lu %lu\n"), _T("Timestamps"),
pIcmpStats->stats.icmpInStats.dwTimestamps, pIcmpStats->stats.icmpOutStats.dwTimestamps);
_tprintf(_T(" %-25s %-11lu %lu\n"), _T("Timestamp Replies"),
pIcmpStats->stats.icmpInStats.dwTimestampReps, pIcmpStats->stats.icmpOutStats.dwTimestampReps);
_tprintf(_T(" %-25s %-11lu %lu\n"), _T("Address Masks"),
pIcmpStats->stats.icmpInStats.dwAddrMasks, pIcmpStats->stats.icmpOutStats.dwAddrMasks);
_tprintf(_T(" %-25s %-11lu %lu\n"), _T("Address Mask Replies"),
pIcmpStats->stats.icmpInStats.dwAddrMaskReps, pIcmpStats->stats.icmpOutStats.dwAddrMaskReps);
}
else
DoFormatMessage(dwRetVal);
HeapFree(GetProcessHeap(), 0, pIcmpStats);
}
VOID ShowTcpStatistics()
{
PMIB_TCPSTATS pTcpStats;
DWORD dwRetVal;
pTcpStats = (MIB_TCPSTATS*) HeapAlloc(GetProcessHeap(), 0, sizeof(MIB_TCPSTATS));
if ((dwRetVal = GetTcpStatistics(pTcpStats)) == NO_ERROR)
{
_tprintf(_T("\nTCP Statistics for IPv4\n\n"));
_tprintf(_T(" %-35s = %lu\n"), _T("Active Opens"), pTcpStats->dwActiveOpens);
_tprintf(_T(" %-35s = %lu\n"), _T("Passive Opens"), pTcpStats->dwPassiveOpens);
_tprintf(_T(" %-35s = %lu\n"), _T("Failed Connection Attempts"), pTcpStats->dwAttemptFails);
_tprintf(_T(" %-35s = %lu\n"), _T("Reset Connections"), pTcpStats->dwEstabResets);
_tprintf(_T(" %-35s = %lu\n"), _T("Current Connections"), pTcpStats->dwCurrEstab);
_tprintf(_T(" %-35s = %lu\n"), _T("Segments Recieved"), pTcpStats->dwInSegs);
_tprintf(_T(" %-35s = %lu\n"), _T("Segments Sent"), pTcpStats->dwOutSegs);
_tprintf(_T(" %-35s = %lu\n"), _T("Segments Retransmitted"), pTcpStats->dwRetransSegs);
}
else
DoFormatMessage(dwRetVal);
HeapFree(GetProcessHeap(), 0, pTcpStats);
}
VOID ShowUdpStatistics()
{
PMIB_UDPSTATS pUdpStats;
DWORD dwRetVal;
pUdpStats = (MIB_UDPSTATS*) HeapAlloc(GetProcessHeap(), 0, sizeof(MIB_UDPSTATS));
if ((dwRetVal = GetUdpStatistics(pUdpStats)) == NO_ERROR)
{
_tprintf(_T("\nUDP Statistics for IPv4\n\n"));
_tprintf(_T(" %-21s = %lu\n"), _T("Datagrams Recieved"), pUdpStats->dwInDatagrams);
_tprintf(_T(" %-21s = %lu\n"), _T("No Ports"), pUdpStats->dwNoPorts);
_tprintf(_T(" %-21s = %lu\n"), _T("Recieve Errors"), pUdpStats->dwInErrors);
_tprintf(_T(" %-21s = %lu\n"), _T("Datagrams Sent"), pUdpStats->dwOutDatagrams);
}
else
DoFormatMessage(dwRetVal);
HeapFree(GetProcessHeap(), 0, pUdpStats);
}
VOID ShowEthernetStatistics()
{
PMIB_IFTABLE pIfTable;
DWORD dwSize = 0;
DWORD dwRetVal = 0;
pIfTable = (MIB_IFTABLE*) HeapAlloc(GetProcessHeap(), 0, sizeof(MIB_IFTABLE));
if (GetIfTable(pIfTable, &dwSize, 0) == ERROR_INSUFFICIENT_BUFFER)
{
HeapFree(GetProcessHeap(), 0, pIfTable);
pIfTable = (MIB_IFTABLE*) HeapAlloc(GetProcessHeap(), 0, dwSize);
if ((dwRetVal = GetIfTable(pIfTable, &dwSize, 0)) == NO_ERROR)
{
_tprintf(_T("Interface Statistics\n\n"));
_tprintf(_T(" Received Sent\n\n"));
_tprintf(_T("%-20s %14lu %15lu\n"), _T("Bytes"),
pIfTable->table[0].dwInOctets, pIfTable->table[0].dwOutOctets);
_tprintf(_T("%-20s %14lu %15lu\n"), _T("Unicast packets"),
pIfTable->table[0].dwInUcastPkts, pIfTable->table[0].dwOutUcastPkts);
_tprintf(_T("%-20s %14lu %15lu\n"), _T("Non-unicast packets"),
pIfTable->table[0].dwInNUcastPkts, pIfTable->table[0].dwOutNUcastPkts);
_tprintf(_T("%-20s %14lu %15lu\n"), _T("Discards"),
pIfTable->table[0].dwInDiscards, pIfTable->table[0].dwOutDiscards);
_tprintf(_T("%-20s %14lu %15lu\n"), _T("Errors"),
pIfTable->table[0].dwInErrors, pIfTable->table[0].dwOutErrors);
_tprintf(_T("%-20s %14lu\n"), _T("Unknown Protocols"),
pIfTable->table[0].dwInUnknownProtos);
}
else
DoFormatMessage(dwRetVal);
}
HeapFree(GetProcessHeap(), 0, pIfTable);
}
VOID ShowTcpTable()
{
PMIB_TCPTABLE tcpTable;
DWORD error, dwSize;
DWORD i;
CHAR HostIp[HOSTNAMELEN], HostPort[PORTNAMELEN];
CHAR RemoteIp[HOSTNAMELEN], RemotePort[PORTNAMELEN];
CHAR Host[ADDRESSLEN];
CHAR Remote[ADDRESSLEN];
/* Get the table of TCP endpoints */
dwSize = 0;
error = GetTcpTable(NULL, &dwSize, TRUE);
if (error != ERROR_INSUFFICIENT_BUFFER)
{
printf("Failed to snapshot TCP endpoints.\n");
DoFormatMessage(error);
exit(EXIT_FAILURE);
}
tcpTable = (PMIB_TCPTABLE) HeapAlloc(GetProcessHeap(), 0, dwSize);
error = GetTcpTable(tcpTable, &dwSize, TRUE );
if (error)
{
printf("Failed to snapshot TCP endpoints table.\n");
DoFormatMessage(error);
HeapFree(GetProcessHeap(), 0, tcpTable);
exit(EXIT_FAILURE);
}
/* Dump the TCP table */
for (i = 0; i < tcpTable->dwNumEntries; i++)
{
/* If we aren't showing all connections, only display established, close wait
* and time wait. This is the default output for netstat */
if (bDoShowAllCons || (tcpTable->table[i].dwState == MIB_TCP_STATE_ESTAB)
|| (tcpTable->table[i].dwState == MIB_TCP_STATE_CLOSE_WAIT)
|| (tcpTable->table[i].dwState == MIB_TCP_STATE_TIME_WAIT))
{
/* I've split this up so it's easier to follow */
GetIpHostName(TRUE, tcpTable->table[i].dwLocalAddr, HostIp, HOSTNAMELEN);
GetPortName(tcpTable->table[i].dwLocalPort, "tcp", HostPort, PORTNAMELEN);
GetIpHostName(FALSE, tcpTable->table[i].dwRemoteAddr, RemoteIp, HOSTNAMELEN);
GetPortName(tcpTable->table[i].dwRemotePort, "tcp", RemotePort, PORTNAMELEN);
sprintf(Host, "%s:%s", HostIp, HostPort);
sprintf(Remote, "%s:%s", RemoteIp, RemotePort);
_tprintf(_T(" %-6s %-22s %-22s %s\n"), _T("TCP"),
Host, Remote, TcpState[tcpTable->table[i].dwState]);
}
}
HeapFree(GetProcessHeap(), 0, tcpTable);
}
VOID ShowUdpTable()
{
PMIB_UDPTABLE udpTable;
DWORD error, dwSize;
DWORD i;
CHAR HostIp[HOSTNAMELEN], HostPort[PORTNAMELEN];
CHAR Host[ADDRESSLEN];
/* Get the table of UDP endpoints */
dwSize = 0;
error = GetUdpTable(NULL, &dwSize, TRUE);
if (error != ERROR_INSUFFICIENT_BUFFER)
{
printf("Failed to snapshot UDP endpoints.\n");
DoFormatMessage(error);
exit(EXIT_FAILURE);
}
udpTable = (PMIB_UDPTABLE) HeapAlloc(GetProcessHeap(), 0, dwSize);
error = GetUdpTable(udpTable, &dwSize, TRUE);
if (error)
{
printf("Failed to snapshot UDP endpoints table.\n");
DoFormatMessage(error);
HeapFree(GetProcessHeap(), 0, udpTable);
exit(EXIT_FAILURE);
}
/* Dump the UDP table */
for (i = 0; i < udpTable->dwNumEntries; i++)
{
/* I've split this up so it's easier to follow */
GetIpHostName(TRUE, udpTable->table[i].dwLocalAddr, HostIp, HOSTNAMELEN);
GetPortName(udpTable->table[i].dwLocalPort, "tcp", HostPort, PORTNAMELEN);
sprintf(Host, "%s:%s", HostIp, HostPort);
_tprintf(_T(" %-6s %-22s %-22s\n"), _T("UDP"), Host, _T("*:*"));
}
HeapFree(GetProcessHeap(), 0, udpTable);
}
/*
* Translate port numbers into their text equivalent if there is one
*/
PCHAR
GetPortName(UINT Port, PCSTR Proto, CHAR Name[], INT NameLen)
{
struct servent *pSrvent;
if (bDoShowNumbers)
{
sprintf(Name, "%d", htons((WORD)Port));
return Name;
}
/* Try to translate to a name */
if ((pSrvent = getservbyport(Port, Proto)))
strcpy(Name, pSrvent->s_name );
else
sprintf(Name, "%d", htons((WORD)Port));
return Name;
}
/*
* convert addresses into dotted decimal or hostname
*/
PCHAR
GetIpHostName(BOOL Local, UINT IpAddr, CHAR Name[], int NameLen)
{
// struct hostent *phostent;
UINT nIpAddr;
/* display dotted decimal */
nIpAddr = htonl(IpAddr);
if (bDoShowNumbers) {
sprintf(Name, "%d.%d.%d.%d",
(nIpAddr >> 24) & 0xFF,
(nIpAddr >> 16) & 0xFF,
(nIpAddr >> 8) & 0xFF,
(nIpAddr) & 0xFF);
return Name;
}
Name[0] = _T('\0');
/* try to resolve the name */
if (!IpAddr) {
if (!Local) {
sprintf(Name, "%d.%d.%d.%d",
(nIpAddr >> 24) & 0xFF,
(nIpAddr >> 16) & 0xFF,
(nIpAddr >> 8) & 0xFF,
(nIpAddr) & 0xFF);
} else {
if (gethostname(Name, NameLen) != 0)
DoFormatMessage(WSAGetLastError());
}
} else if (IpAddr == 0x0100007f) {
if (Local) {
if (gethostname(Name, NameLen) != 0)
DoFormatMessage(WSAGetLastError());
} else {
_tcsncpy(Name, _T("localhost"), 10);
}
// } else if (phostent = gethostbyaddr((char*)&ipaddr, sizeof(nipaddr), PF_INET)) {
// strcpy(name, phostent->h_name);
} else {
sprintf(Name, "%d.%d.%d.%d",
((nIpAddr >> 24) & 0x000000FF),
((nIpAddr >> 16) & 0x000000FF),
((nIpAddr >> 8) & 0x000000FF),
((nIpAddr) & 0x000000FF));
}
return Name;
}
VOID Usage()
{
_tprintf(_T("\nDisplays current TCP/IP protocol statistics and network connections.\n\n"
"NETSTAT [-a] [-e] [-n] [-s] [-p proto] [-r] [interval]\n\n"
" -a Displays all connections and listening ports.\n"
" -e Displays Ethernet statistics. May be combined with -s\n"
" option\n"
" -n Displays address and port numbers in numeric form.\n"
" -p proto Shows connections for protocol 'proto' TCP or UDP.\n"
" If used with the -s option to display\n"
" per-protocol statistics, 'proto' may be TCP, UDP, or IP.\n"
" -r Displays the current routing table.\n"
" -s Displays per-protocol statistics. By default, Statistics are\n"
" shown for IP, ICMP, TCP and UDP;\n"
" the -p option may be used to specify a subset of the default.\n"
" interval Redisplays selected statistics every 'interval' seconds.\n"
" Press CTRL+C to stop redisplaying. By default netstat will\n"
" print the current information only once.\n"));
}
/*
*
* Parse command line parameters and set any options
* Run display output, looping over set intervals if a number is given
*
*/
int main(int argc, char *argv[])
{
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0)
{
_tprintf(_T("WSAStartup() failed : %d\n"), WSAGetLastError());
return -1;
}
if (ParseCmdline(argc, argv))
return -1;
if (bLoopOutput)
{
while (1)
{
if (DisplayOutput())
return -1;
Sleep(Interval*1000);
}
}
if (DisplayOutput())
return -1;
else
return 0;
}
@@ -0,0 +1,61 @@
/* Maximum string lengths for ASCII ip address and port names */
#define HOSTNAMELEN 256
#define PORTNAMELEN 256
#define ADDRESSLEN HOSTNAMELEN+PORTNAMELEN
/* command line options */
BOOL bNoOptions = FALSE; // print default
BOOL bDoShowAllCons = FALSE; // -a
BOOL bDoShowProcName = FALSE; // -b
BOOL bDoShowEthStats = FALSE; // -e
BOOL bDoShowNumbers = FALSE; // -n
BOOL bDoShowProtoCons = FALSE; // -p
BOOL bDoShowRouteTable = FALSE; // -r
BOOL bDoShowProtoStats = FALSE; // -s
BOOL bDoDispSeqComp = FALSE; // -v
BOOL bLoopOutput = FALSE; // interval
/* Undocumented extended information structures available only on XP and higher */
typedef struct {
DWORD dwState; // state of the connection
DWORD dwLocalAddr; // address on local computer
DWORD dwLocalPort; // port number on local computer
DWORD dwRemoteAddr; // address on remote computer
DWORD dwRemotePort; // port number on remote computer
DWORD dwProcessId;
} MIB_TCPEXROW, *PMIB_TCPEXROW;
typedef struct {
DWORD dwNumEntries;
MIB_TCPEXROW table;
} MIB_TCPEXTABLE, *PMIB_TCPEXTABLE;
typedef struct {
DWORD dwLocalAddr; // address on local computer
DWORD dwLocalPort; // port number on local computer
DWORD dwProcessId;
} MIB_UDPEXROW, *PMIB_UDPEXROW;
typedef struct {
DWORD dwNumEntries;
MIB_UDPEXROW table;
} MIB_UDPEXTABLE, *PMIB_UDPEXTABLE;
/* function declerations */
BOOL ParseCmdline(int argc, char* argv[]);
BOOL DisplayOutput(VOID);
DWORD DoFormatMessage(DWORD ErrorCode);
VOID ShowIpStatistics(VOID);
VOID ShowIcmpStatistics(VOID);
VOID ShowTcpStatistics(VOID);
VOID ShowUdpStatistics(VOID);
VOID ShowEthernetStatistics(VOID);
VOID ShowTcpTable(VOID);
VOID ShowUdpTable(VOID);
PCHAR GetPortName(UINT Port, PCSTR Proto, CHAR Name[PORTNAMELEN], INT NameLen);
PCHAR GetIpHostName(BOOL local, UINT ipaddr, CHAR name[HOSTNAMELEN], int namelen);
VOID Usage(VOID);
@@ -0,0 +1,7 @@
#define REACTOS_STR_FILE_DESCRIPTION "ReactOS TCP/IPv4 Win32 netstat\0"
#define REACTOS_STR_INTERNAL_NAME "netstat\0"
#define REACTOS_STR_ORIGINAL_FILENAME "netstat.exe\0"
#define REACTOS_STR_ORIGINAL_COPYRIGHT "Ged Murphy ([email protected])\0"
#include <reactos/version.rc>
@@ -0,0 +1,13 @@
<module name="netstat" type="win32cui" installbase="system32" installname="netstat.exe" allowwarnings="true">
<include base="netstat">.</include>
<define name="__USE_W32API" />
<define name="_WIN32_IE">0x600</define>
<define name="_WIN32_WINNT">0x501</define>
<library>kernel32</library>
<library>user32</library>
<library>ws2_32</library>
<library>snmpapi</library>
<library>iphlpapi</library>
<file>netstat.c</file>
<file>netstat.rc</file>
</module>
+633
View File
@@ -0,0 +1,633 @@
/*
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS ping utility
* FILE: apps/net/ping/ping.c
* PURPOSE: Network test utility
* PROGRAMMERS: Casper S. Hornstrup ([email protected])
* REVISIONS:
* CSH 01/09/2000 Created
*/
#include <winsock2.h>
#include <tchar.h>
#include <stdarg.h>
#include <string.h>
#include <stdio.h>
#ifndef _MSC_VER
/* FIXME: Where should this be? */
#ifdef CopyMemory
#undef CopyMemory
#endif
#define CopyMemory(Destination, Source, Length) memcpy(Destination, Source, Length);
/* Should be in the header files somewhere (exported by ntdll.dll) */
long atol(const char *str);
#ifndef __int64
typedef long long __int64;
#endif
char * _i64toa(__int64 value, char *string, int radix);
#endif /* _MSC_VER */
#ifdef DBG
#undef DBG
#endif
/* General ICMP constants */
#define ICMP_MINSIZE 8 /* Minimum ICMP packet size */
#define ICMP_MAXSIZE 65535 /* Maximum ICMP packet size */
/* ICMP message types */
#define ICMPMSG_ECHOREQUEST 8 /* ICMP ECHO request message */
#define ICMPMSG_ECHOREPLY 0 /* ICMP ECHO reply message */
#pragma pack(4)
/* IPv4 header structure */
typedef struct _IPv4_HEADER {
unsigned char IHL:4;
unsigned char Version:4;
unsigned char TOS;
unsigned short Length;
unsigned short Id;
unsigned short FragFlags;
unsigned char TTL;
unsigned char Protocol;
unsigned short Checksum;
unsigned int SrcAddress;
unsigned int DstAddress;
} IPv4_HEADER, *PIPv4_HEADER;
/* ICMP echo request/reply header structure */
typedef struct _ICMP_HEADER {
unsigned char Type;
unsigned char Code;
unsigned short Checksum;
unsigned short Id;
unsigned short SeqNum;
} ICMP_HEADER, *PICMP_HEADER;
typedef struct _ICMP_ECHO_PACKET {
ICMP_HEADER Icmp;
LARGE_INTEGER Timestamp;
} ICMP_ECHO_PACKET, *PICMP_ECHO_PACKET;
#pragma pack(1)
BOOL InvalidOption;
BOOL NeverStop;
BOOL ResolveAddresses;
UINT PingCount;
UINT DataSize; /* ICMP echo request data size */
BOOL DontFragment;
ULONG TTLValue;
ULONG TOSValue;
ULONG Timeout;
CHAR TargetName[256];
SOCKET IcmpSock;
SOCKADDR_IN Target;
LPSTR TargetIP;
FD_SET Fds;
TIMEVAL Timeval;
UINT CurrentSeqNum;
UINT SentCount;
UINT LostCount;
BOOL MinRTTSet;
LARGE_INTEGER MinRTT; /* Minimum round trip time in microseconds */
LARGE_INTEGER MaxRTT;
LARGE_INTEGER SumRTT;
LARGE_INTEGER AvgRTT;
LARGE_INTEGER TicksPerMs; /* Ticks per millisecond */
LARGE_INTEGER TicksPerUs; /* Ticks per microsecond */
BOOL UsePerformanceCounter;
#ifdef DBG
/* Display the contents of a buffer */
static VOID DisplayBuffer(
PVOID Buffer,
DWORD Size)
{
UINT i;
PCHAR p;
printf("Buffer (0x%p) Size (0x%lX).\n", Buffer, Size);
p = (PCHAR)Buffer;
for (i = 0; i < Size; i++) {
if (i % 16 == 0) {
printf("\n");
}
printf("%02X ", (p[i]) & 0xFF);
}
}
#endif /* DBG */
/* Display usage information on screen */
static VOID Usage(VOID)
{
printf("\nUsage: ping [-t] [-n count] [-l size] [-w timeout] destination-host\n\n");
printf("Options:\n");
printf(" -t Ping the specified host until stopped.\n");
printf(" To stop - type Control-C.\n");
printf(" -n count Number of echo requests to send.\n");
printf(" -l size Send buffer size.\n");
printf(" -w timeout Timeout in milliseconds to wait for each reply.\n\n");
}
/* Reset configuration to default values */
static VOID Reset(VOID)
{
LARGE_INTEGER PerformanceCounterFrequency;
NeverStop = FALSE;
ResolveAddresses = FALSE;
PingCount = 4;
DataSize = 32;
DontFragment = FALSE;
TTLValue = 128;
TOSValue = 0;
Timeout = 1000;
UsePerformanceCounter = QueryPerformanceFrequency(&PerformanceCounterFrequency);
if (UsePerformanceCounter) {
/* Performance counters may return incorrect results on some multiprocessor
platforms so we restrict execution on the first processor. This may fail
on Windows NT so we fall back to GetCurrentTick() for timing */
if (SetThreadAffinityMask (GetCurrentThread(), 1) == 0) {
UsePerformanceCounter = FALSE;
}
/* Convert frequency to ticks per millisecond */
TicksPerMs.QuadPart = PerformanceCounterFrequency.QuadPart / 1000;
/* And to ticks per microsecond */
TicksPerUs.QuadPart = PerformanceCounterFrequency.QuadPart / 1000000;
}
if (!UsePerformanceCounter) {
/* 1 tick per millisecond for GetCurrentTick() */
TicksPerMs.QuadPart = 1;
/* GetCurrentTick() cannot handle microseconds */
TicksPerUs.QuadPart = 1;
}
}
/* Return ULONG in a string */
static ULONG GetULONG(LPSTR String)
{
UINT i, Length;
ULONG Value;
i = 0;
Length = (UINT)_tcslen(String);
while ((i < Length) && ((String[i] < '0') || (String[i] > '9'))) i++;
if ((i >= Length) || ((String[i] < '0') || (String[i] > '9'))) {
InvalidOption = TRUE;
return 0;
}
Value = (ULONG)atol(&String[i]);
return Value;
}
/* Return ULONG in a string. Try next paramter if not successful */
static ULONG GetULONG2(LPSTR String1, LPSTR String2, PINT i)
{
ULONG Value;
Value = GetULONG(String1);
if (InvalidOption) {
InvalidOption = FALSE;
if (String2[0] != '-') {
Value = GetULONG(String2);
if (!InvalidOption)
*i += 1;
}
}
return Value;
}
/* Parse command line parameters */
static BOOL ParseCmdline(int argc, char* argv[])
{
INT i;
BOOL ShowUsage;
BOOL FoundTarget;
//#if 1
// lstrcpy(TargetName, "127.0.0.1");
// PingCount = 1;
// return TRUE;
//#endif
if (argc < 2) {
ShowUsage = TRUE;
} else {
ShowUsage = FALSE;
}
FoundTarget = FALSE;
InvalidOption = FALSE;
for (i = 1; i < argc; i++) {
if (argv[i][0] == '-') {
switch (argv[i][1]) {
case 't': NeverStop = TRUE; break;
case 'a': ResolveAddresses = TRUE; break;
case 'n': PingCount = GetULONG2(&argv[i][2], argv[i + 1], &i); break;
case 'l':
DataSize = GetULONG2(&argv[i][2], argv[i + 1], &i);
if ((DataSize < 0) || (DataSize > ICMP_MAXSIZE - sizeof(ICMP_ECHO_PACKET))) {
printf("Bad value for option -l, valid range is from 0 to %d.\n",
ICMP_MAXSIZE - sizeof(ICMP_ECHO_PACKET));
return FALSE;
}
break;
case 'f': DontFragment = TRUE; break;
case 'i': TTLValue = GetULONG2(&argv[i][2], argv[i + 1], &i); break;
case 'v': TOSValue = GetULONG2(&argv[i][2], argv[i + 1], &i); break;
case 'w': Timeout = GetULONG2(&argv[i][2], argv[i + 1], &i); break;
default:
printf("Bad option %s.\n", argv[i]);
Usage();
return FALSE;
}
if (InvalidOption) {
printf("Bad option format %s.\n", argv[i]);
return FALSE;
}
} else {
if (FoundTarget) {
printf("Bad parameter %s.\n", argv[i]);
return FALSE;
} else {
lstrcpy(TargetName, argv[i]);
FoundTarget = TRUE;
}
}
}
if ((!ShowUsage) && (!FoundTarget)) {
printf("Name or IP address of destination host must be specified.\n");
return FALSE;
}
if (ShowUsage) {
Usage();
return FALSE;
}
return TRUE;
}
/* Calculate checksum of data */
static WORD Checksum(PUSHORT data, UINT size)
{
ULONG sum = 0;
while (size > 1) {
sum += *data++;
size -= sizeof(USHORT);
}
if (size)
sum += *(UCHAR*)data;
sum = (sum >> 16) + (sum & 0xFFFF);
sum += (sum >> 16);
return (USHORT)(~sum);
}
/* Prepare to ping target */
static BOOL Setup(VOID)
{
WORD wVersionRequested;
WSADATA WsaData;
INT Status;
ULONG Addr;
PHOSTENT phe;
wVersionRequested = MAKEWORD(2, 2);
Status = WSAStartup(wVersionRequested, &WsaData);
if (Status != 0) {
printf("Could not initialize winsock dll.\n");
return FALSE;
}
IcmpSock = WSASocket(AF_INET, SOCK_RAW, IPPROTO_ICMP, NULL, 0, 0);
if (IcmpSock == INVALID_SOCKET) {
printf("Could not create socket (#%d).\n", WSAGetLastError());
return FALSE;
}
ZeroMemory(&Target, sizeof(Target));
phe = NULL;
Addr = inet_addr(TargetName);
if (Addr == INADDR_NONE) {
phe = gethostbyname(TargetName);
if (phe == NULL) {
printf("Unknown host %s.\n", TargetName);
return FALSE;
}
}
if (phe != NULL) {
CopyMemory(&Target.sin_addr, phe->h_addr, phe->h_length);
} else {
Target.sin_addr.s_addr = Addr;
}
if (phe != NULL) {
Target.sin_family = phe->h_addrtype;
} else {
Target.sin_family = AF_INET;
}
TargetIP = inet_ntoa(Target.sin_addr);
CurrentSeqNum = 0;
SentCount = 0;
LostCount = 0;
MinRTT.QuadPart = 0;
MaxRTT.QuadPart = 0;
SumRTT.QuadPart = 0;
MinRTTSet = FALSE;
return TRUE;
}
/* Close socket */
static VOID Cleanup(VOID)
{
if (IcmpSock != INVALID_SOCKET)
closesocket(IcmpSock);
WSACleanup();
}
static VOID QueryTime(PLARGE_INTEGER Time)
{
if (UsePerformanceCounter) {
if (QueryPerformanceCounter(Time) == 0) {
/* This should not happen, but we fall
back to GetCurrentTick() if it does */
Time->u.LowPart = (ULONG)GetTickCount();
Time->u.HighPart = 0;
/* 1 tick per millisecond for GetCurrentTick() */
TicksPerMs.QuadPart = 1;
/* GetCurrentTick() cannot handle microseconds */
TicksPerUs.QuadPart = 1;
UsePerformanceCounter = FALSE;
}
} else {
Time->u.LowPart = (ULONG)GetTickCount();
Time->u.HighPart = 0;
}
}
static VOID TimeToMsString(LPSTR String, LARGE_INTEGER Time)
{
CHAR Convstr[40];
LARGE_INTEGER LargeTime;
LargeTime.QuadPart = Time.QuadPart / TicksPerMs.QuadPart;
_i64toa(LargeTime.QuadPart, Convstr, 10);
strcpy(String, Convstr);
strcat(String, "ms");
}
/* Locate the ICMP data and print it. Returns TRUE if the packet was good,
FALSE if not */
static BOOL DecodeResponse(PCHAR buffer, UINT size, PSOCKADDR_IN from)
{
PIPv4_HEADER IpHeader;
PICMP_ECHO_PACKET Icmp;
UINT IphLength;
CHAR Time[100];
LARGE_INTEGER RelativeTime;
LARGE_INTEGER LargeTime;
CHAR Sign[2];
IpHeader = (PIPv4_HEADER)buffer;
IphLength = IpHeader->IHL * 4;
if (size < IphLength + ICMP_MINSIZE) {
#ifdef DBG
printf("Bad size (0x%X < 0x%X)\n", size, IphLength + ICMP_MINSIZE);
#endif /* DBG */
return FALSE;
}
Icmp = (PICMP_ECHO_PACKET)(buffer + IphLength);
if (Icmp->Icmp.Type != ICMPMSG_ECHOREPLY) {
#ifdef DBG
printf("Bad ICMP type (0x%X should be 0x%X)\n", Icmp->Icmp.Type, ICMPMSG_ECHOREPLY);
#endif /* DBG */
return FALSE;
}
if (Icmp->Icmp.Id != (USHORT)GetCurrentProcessId()) {
#ifdef DBG
printf("Bad ICMP id (0x%X should be 0x%X)\n", Icmp->Icmp.Id, (USHORT)GetCurrentProcessId());
#endif /* DBG */
return FALSE;
}
QueryTime(&LargeTime);
RelativeTime.QuadPart = (LargeTime.QuadPart - Icmp->Timestamp.QuadPart);
if ((RelativeTime.QuadPart / TicksPerMs.QuadPart) < 1) {
strcpy(Sign, "<");
strcpy(Time, "1ms");
} else {
strcpy(Sign, "=");
TimeToMsString(Time, RelativeTime);
}
printf("Reply from %s: bytes=%d time%s%s TTL=%d\n", inet_ntoa(from->sin_addr),
size - IphLength - sizeof(ICMP_ECHO_PACKET), Sign, Time, IpHeader->TTL);
if (RelativeTime.QuadPart < MinRTT.QuadPart || !MinRTTSet) {
MinRTT.QuadPart = RelativeTime.QuadPart;
MinRTTSet = TRUE;
}
if (RelativeTime.QuadPart > MaxRTT.QuadPart)
MaxRTT.QuadPart = RelativeTime.QuadPart;
SumRTT.QuadPart += RelativeTime.QuadPart;
return TRUE;
}
/* Send and receive one ping */
static BOOL Ping(VOID)
{
INT Status;
SOCKADDR From;
INT Length;
PVOID Buffer;
UINT Size;
PICMP_ECHO_PACKET Packet;
/* Account for extra space for IP header when packet is received */
Size = DataSize + 128;
Buffer = GlobalAlloc(0, Size);
if (!Buffer) {
printf("Not enough free resources available.\n");
return FALSE;
}
ZeroMemory(Buffer, Size);
Packet = (PICMP_ECHO_PACKET)Buffer;
/* Assemble ICMP echo request packet */
Packet->Icmp.Type = ICMPMSG_ECHOREQUEST;
Packet->Icmp.Code = 0;
Packet->Icmp.Id = (USHORT)GetCurrentProcessId();
Packet->Icmp.SeqNum = (USHORT)CurrentSeqNum;
Packet->Icmp.Checksum = 0;
/* Timestamp is part of data area */
QueryTime(&Packet->Timestamp);
CopyMemory(Buffer, &Packet->Icmp, sizeof(ICMP_ECHO_PACKET) + DataSize);
/* Calculate checksum for ICMP header and data area */
Packet->Icmp.Checksum = Checksum((PUSHORT)&Packet->Icmp, sizeof(ICMP_ECHO_PACKET) + DataSize);
CurrentSeqNum++;
/* Send ICMP echo request */
FD_ZERO(&Fds);
FD_SET(IcmpSock, &Fds);
Timeval.tv_sec = Timeout / 1000;
Timeval.tv_usec = Timeout % 1000;
Status = select(0, NULL, &Fds, NULL, &Timeval);
if ((Status != SOCKET_ERROR) && (Status != 0)) {
#ifdef DBG
printf("Sending packet\n");
DisplayBuffer(Buffer, sizeof(ICMP_ECHO_PACKET) + DataSize);
printf("\n");
#endif /* DBG */
Status = sendto(IcmpSock, Buffer, sizeof(ICMP_ECHO_PACKET) + DataSize,
0, (SOCKADDR*)&Target, sizeof(Target));
SentCount++;
}
if (Status == SOCKET_ERROR) {
if (WSAGetLastError() == WSAEHOSTUNREACH) {
printf("Destination host unreachable.\n");
} else {
printf("Could not transmit data (%d).\n", WSAGetLastError());
}
GlobalFree(Buffer);
return FALSE;
}
/* Expect to receive ICMP echo reply */
FD_ZERO(&Fds);
FD_SET(IcmpSock, &Fds);
Timeval.tv_sec = Timeout / 1000;
Timeval.tv_usec = Timeout % 1000;
Status = select(0, &Fds, NULL, NULL, &Timeval);
if ((Status != SOCKET_ERROR) && (Status != 0)) {
Length = sizeof(From);
Status = recvfrom(IcmpSock, Buffer, Size, 0, &From, &Length);
#ifdef DBG
printf("Received packet\n");
DisplayBuffer(Buffer, Status);
printf("\n");
#endif /* DBG */
}
if (Status == SOCKET_ERROR) {
if (WSAGetLastError() != WSAETIMEDOUT) {
printf("Could not receive data (%d).\n", WSAGetLastError());
GlobalFree(Buffer);
return FALSE;
}
Status = 0;
}
if (Status == 0) {
printf("Request timed out.\n");
LostCount++;
GlobalFree(Buffer);
return TRUE;
}
if (!DecodeResponse(Buffer, Status, (PSOCKADDR_IN)&From)) {
/* FIXME: Wait again as it could be another ICMP message type */
printf("Request timed out (incomplete datagram received).\n");
LostCount++;
}
GlobalFree(Buffer);
return TRUE;
}
/* Program entry point */
int main(int argc, char* argv[])
{
UINT Count;
CHAR MinTime[20];
CHAR MaxTime[20];
CHAR AvgTime[20];
Reset();
if ((ParseCmdline(argc, argv)) && (Setup())) {
printf("\nPinging %s [%s] with %d bytes of data:\n\n",
TargetName, TargetIP, DataSize);
Count = 0;
while ((NeverStop) || (Count < PingCount)) {
Ping();
Sleep(Timeout);
Count++;
};
Cleanup();
/* Calculate avarage round trip time */
if ((SentCount - LostCount) > 0) {
AvgRTT.QuadPart = SumRTT.QuadPart / (SentCount - LostCount);
} else {
AvgRTT.QuadPart = 0;
}
/* Calculate loss percent */
if (LostCount > 0) {
Count = (SentCount * 100) / LostCount;
} else {
Count = 0;
}
if (!MinRTTSet)
MinRTT = MaxRTT;
TimeToMsString(MinTime, MinRTT);
TimeToMsString(MaxTime, MaxRTT);
TimeToMsString(AvgTime, AvgRTT);
/* Print statistics */
printf("\nPing statistics for %s:\n", TargetIP);
printf(" Packets: Sent = %d, Received = %d, Lost = %d (%d%% loss),\n",
SentCount, SentCount - LostCount, LostCount, Count);
printf("Approximate round trip times in milli-seconds:\n");
printf(" Minimum = %s, Maximum = %s, Average = %s\n",
MinTime, MaxTime, AvgTime);
}
return 0;
}
/* EOF */
@@ -0,0 +1,7 @@
/* $Id$ */
#define REACTOS_STR_FILE_DESCRIPTION "ReactOS TCP/IPv4 Win32 Ping\0"
#define REACTOS_STR_INTERNAL_NAME "ping\0"
#define REACTOS_STR_ORIGINAL_FILENAME "ping.exe\0"
#define REACTOS_STR_ORIGINAL_COPYRIGHT "Casper S. Hornstrup ([email protected])\0"
#include <reactos/version.rc>
@@ -0,0 +1,11 @@
<module name="ping" type="win32cui" installbase="system32" installname="ping.exe">
<include base="ping">.</include>
<define name="__USE_W32API" />
<define name="__USE_W32_SOCKETS" />
<define name="_WIN32_IE">0x600</define>
<define name="_WIN32_WINNT">0x501</define>
<library>kernel32</library>
<library>ws2_32</library>
<file>ping.c</file>
<file>ping.rc</file>
</module>
@@ -0,0 +1,94 @@
/*
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS HTTP Daemon
* FILE: list.cpp
* PURPOSE: A doubly linked list implementation
* PROGRAMMERS: Casper S. Hornstrup ([email protected])
* REVISIONS:
* CSH 01/09/2000 Created
* NOTES: The linked list does it's own heap management for
* better performance
* TODO: - InsertBefore(), InsertAfter(), Move()
*/
#include <windows.h>
#include <list.h>
// **************************** CListNode ****************************
HANDLE CListNode::hHeap = NULL;
INT CListNode::nRef = 0;
// Default constructor
CListNode::CListNode()
{
Element = NULL;
Next = NULL;
Prev = NULL;
}
// Constructor with element and next as starter values
CListNode::CListNode(PVOID element, CListNode *next, CListNode *prev)
{
Element = element;
Next = next;
Prev = prev;
}
void* CListNode::operator new(/*size_t*/ UINT size)
{
PVOID p;
if (hHeap == NULL) {
SYSTEM_INFO inf;
GetSystemInfo(&inf);
hHeap = HeapCreate(0, inf.dwAllocationGranularity, 0);
}
if ((p = HeapAlloc(hHeap, 0, size)) != NULL)
nRef++;
return p;
}
VOID CListNode::operator delete(void* p)
{
if (HeapFree(hHeap, 0, p) != FALSE)
nRef--;
if (nRef == 0) {
HeapDestroy(hHeap);
hHeap = NULL;
}
}
// Set element
VOID CListNode::SetElement(PVOID element)
{
Element = element;
}
// Set pointer to next node in list
VOID CListNode::SetNext(CListNode *next)
{
Next = next;
}
// Set pointer to previous node in list
VOID CListNode::SetPrev(CListNode *prev)
{
Prev = prev;
}
// Get element of node
PVOID CListNode::GetElement()
{
return Element;
}
// Get pointer to next node in list
CListNode *CListNode::GetNext()
{
return Next;
}
// Get pointer to previous node in list
CListNode *CListNode::GetPrev()
{
return Prev;
}
@@ -0,0 +1,6 @@
/* $Id$ */
#define REACTOS_STR_FILE_DESCRIPTION "ReactOS HTTP Win32 Server\0"
#define REACTOS_STR_INTERNAL_NAME "roshttpd\0"
#define REACTOS_STR_ORIGINAL_FILENAME "roshttpd.exe\0"
#include <reactos/version.rc>
@@ -0,0 +1,344 @@
/*
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS HTTP Daemon
* FILE: socket.cpp
* PURPOSE: Socket classes
* PROGRAMMERS: Casper S. Hornstrup ([email protected])
* REVISIONS:
* CSH 01/09/2000 Created
*/
#include <string.h>
#include <error.h>
#include <socket.h>
#include <iterator.h>
// ***************************** CSocket *****************************
// Default constructor
CSocket::CSocket()
{
Active = FALSE;
Event = WSA_INVALID_EVENT;
Events = 0;
Socket = INVALID_SOCKET;
// INET address family
SockAddrIn.sin_family = AF_INET;
// Any address will do
SockAddrIn.sin_addr.s_addr = INADDR_ANY;
// Convert to network ordering
SockAddrIn.sin_port = htons(0);
}
// Default destructor
CSocket::~CSocket()
{
}
// Return winsock socket handle
SOCKET CSocket::GetSocket()
{
return Socket;
}
// Set winsock socket handle
VOID CSocket::SetSocket(SOCKET socket)
{
Socket = socket;
}
// Return socket address
SOCKADDR_IN CSocket::GetSockAddrIn()
{
return SockAddrIn;
}
// Set socket address
VOID CSocket::SetSockAddrIn(SOCKADDR_IN sockaddrin)
{
SockAddrIn = sockaddrin;
}
// Associate winsock events with socket
VOID CSocket::SetEvents(LONG lEvents)
{
if (Event == WSA_INVALID_EVENT) {
// Create socket event
Event = WSACreateEvent();
if (Event == WSA_INVALID_EVENT)
throw ESocketOpen(TS("Unable to create event."));
}
if (lEvents != Events) {
// Associate network events with socket
if (WSAEventSelect(Socket, Event, lEvents) == SOCKET_ERROR)
throw ESocketOpen(TS("Unable to select socket events."));
Events = lEvents;
}
}
// Return associated winsock events
LONG CSocket::GetEvents()
{
return Events;
}
// Open socket
VOID CSocket::Open()
{
}
// Close socket
VOID CSocket::Close()
{
}
// *********************** CServerClientSocket ***********************
// Constructor with serversocket as parameter
CServerClientSocket::CServerClientSocket(LPCServerSocket lpServerSocket)
{
ServerSocket = lpServerSocket;
}
// Transmit data to socket
INT CServerClientSocket::Transmit( LPSTR lpsBuffer, UINT nLength)
{
return send(Socket, lpsBuffer, nLength, 0);
}
// Send a string to socket
INT CServerClientSocket::SendText( LPSTR lpsText)
{
static CHAR crlf[3] = {0x0D, 0x0A, 0x00};
INT nCount;
nCount = Transmit(lpsText, strlen(lpsText));
nCount += Transmit(crlf, strlen(crlf));
return nCount;
}
// Receive data from socket
INT CServerClientSocket::Receive(LPSTR lpsBuffer, UINT nLength)
{
return recv(Socket, lpsBuffer, nLength, 0);
}
// Process winsock messages if any
VOID CServerClientSocket::MessageLoop()
{
UINT nStatus;
WSANETWORKEVENTS NetworkEvents;
nStatus = WSAWaitForMultipleEvents(1, &Event, FALSE, 0, FALSE);
if ((nStatus == 0) && (WSAEnumNetworkEvents(Socket, Event, &NetworkEvents) != SOCKET_ERROR)) {
if ((NetworkEvents.lNetworkEvents & FD_READ) != 0) {
OnRead();
}
if ((NetworkEvents.lNetworkEvents & FD_CLOSE) != 0) {
OnClose();
}
}
}
// Return server socket that own this socket
LPCServerSocket CServerClientSocket::GetServerSocket()
{
return ServerSocket;
}
// *********************** CServerClientThread ***********************
CServerClientThread::CServerClientThread(LPCServerClientSocket lpSocket)
{
ClientSocket = lpSocket;
}
CServerClientThread::~CServerClientThread()
{
ClientSocket->GetServerSocket()->RemoveClient((LPCServerClientThread) this);
}
// ************************** CServerSocket **************************
// Default constructor
CServerSocket::CServerSocket()
{
}
// Default destructor
CServerSocket::~CServerSocket()
{
if (Active)
Close();
}
// Open server socket so clients can connect
VOID CServerSocket::Open()
{
assert(!Active);
// Convert to network ordering
SockAddrIn.sin_port = htons(Port);
if (Socket == INVALID_SOCKET) {
// Create socket
Socket = socket(AF_INET, SOCK_STREAM, 0);
if (Socket == INVALID_SOCKET)
throw ESocketOpen(TS("Unable to allocate a socket."));
}
// Associate an address with server socket
if (bind(Socket, (struct sockaddr FAR *) &SockAddrIn, sizeof(SockAddrIn)) == SOCKET_ERROR)
throw ESocketOpen(TS("Unable to associate address with socket."));
// Listen for incoming connections
if (listen(Socket, MAX_PENDING_CONNECTS) != 0)
throw ESocketOpen(TS("Unable to listen on socket."));
// Associate network events with socket
SetEvents(FD_ACCEPT | FD_CONNECT | FD_CLOSE);
Active = TRUE;
}
// Close server socket and all current connections
VOID CServerSocket::Close()
{
assert(Active);
if (Event != WSA_INVALID_EVENT) {
// Tell winsock not to notify us about any events
if (WSAEventSelect(Socket, Event, 0) == SOCKET_ERROR)
throw ESocketClose(TS("Unable to select socket events."));
if (!WSACloseEvent(Event))
throw ESocketClose(TS("Unable to close socket event."));
Event = WSA_INVALID_EVENT;
}
CIterator<LPCServerClientThread> *i = Connections.CreateIterator();
// Terminate and free all client threads
for (i->First(); !i->IsDone(); i->Next()) {
//i->CurrentItem()->Terminate();
delete i->CurrentItem();
}
delete i;
Connections.RemoveAll();
closesocket(Socket);
Socket = INVALID_SOCKET;
Active = FALSE;
}
// Set port number to listen on
VOID CServerSocket::SetPort(UINT nPort)
{
assert(!Active);
Port = nPort;
}
// Process messages from winsock if any
VOID CServerSocket::MessageLoop()
{
UINT nStatus;
INT nAddrLen;
SOCKET ClientSocket;
SOCKADDR_IN SockAddrIn;
WSANETWORKEVENTS NetworkEvents;
LPCServerClientSocket lpClient;
LPCServerClientThread lpThread;
nStatus = WSAWaitForMultipleEvents(1, &Event, FALSE, 0, FALSE);
if ((nStatus == 0) && (WSAEnumNetworkEvents(Socket, Event, &NetworkEvents) != SOCKET_ERROR)) {
if ((NetworkEvents.lNetworkEvents & FD_ACCEPT) != 0) {
lpClient = OnGetSocket(this);
nAddrLen = sizeof(SockAddrIn);
ClientSocket = accept(Socket, (SOCKADDR *) &SockAddrIn, &nAddrLen);
if (ClientSocket != INVALID_SOCKET) {
// Set socket handle
lpClient->SetSocket(ClientSocket);
// Set socket address
lpClient->SetSockAddrIn(SockAddrIn);
// Set winsock events
lpClient->SetEvents(FD_READ | FD_CLOSE);
// Create client connection thread
lpThread = OnGetThread(lpClient);
// Add client thread to connection list
InsertClient(lpThread);
// Call OnAccept event handler
OnAccept(lpThread);
} else {
delete lpClient;
lpClient = NULL;
throw ESocketOpen(TS("No more sockets available."));
}
}
/*if ((NetworkEvents.lNetworkEvents & FD_CONNECT) != 0) {
}
if ((NetworkEvents.lNetworkEvents & FD_CLOSE) != 0) {
}*/
}
}
// Insert client into connection list
VOID CServerSocket::InsertClient(LPCServerClientThread lpClient)
{
Connections.Insert(lpClient);
}
// Remove client from connection list
VOID CServerSocket::RemoveClient(LPCServerClientThread lpClient)
{
Connections.Remove(lpClient);
}
// OnGetSocket event handler
LPCServerClientSocket CServerSocket::OnGetSocket(LPCServerSocket lpServerSocket)
{
return NULL;
}
// OnGetThread event handler
LPCServerClientThread CServerSocket::OnGetThread(LPCServerClientSocket lpSocket)
{
return NULL;
}
// Initialize WinSock DLL
VOID InitWinsock()
{
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD(2, 0);
if (WSAStartup(wVersionRequested, &wsaData) != 0)
// Return FALSE as we couldn't find a usable WinSock DLL
throw ESocketWinsock(TS("Unable to initialize winsock dll."));
/* Confirm that the WinSock DLL supports 2.0 */
if (LOBYTE(wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 0) {
// We couldn't find a usable winsock dll
WSACleanup();
throw ESocketDll(TS("Winsock dll version is not 2.0 or higher."));
}
}
// Deinitialize WinSock DLL
VOID DeinitWinsock()
{
if (WSACleanup() != 0)
throw ESocketWinsock(TS("Unable to deinitialize winsock dll."));
}
@@ -0,0 +1,80 @@
/*
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS HTTP Daemon
* FILE: thread.cpp
* PURPOSE: Generic thread class
* PROGRAMMERS: Casper S. Hornstrup ([email protected])
* REVISIONS:
* CSH 01/09/2000 Created
*/
#include <debug.h>
#include <assert.h>
#include <windows.h>
#include <thread.h>
// This is the thread entry code
DWORD WINAPI ThreadEntry(LPVOID parameter)
{
ThreadData *p = (ThreadData*) parameter;
p->ClassPtr->Execute();
SetEvent(p->hFinished);
return 0;
}
// Default constructor
CThread::CThread()
{
bTerminated = FALSE;
// Points to the class that is executed within thread
Data.ClassPtr = this;
// Create synchronization event
Data.hFinished = CreateEvent(NULL, TRUE, FALSE, NULL);
// FIXME: Do some error handling
assert(Data.hFinished != NULL);
// Create thread
hThread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)ThreadEntry, &Data, 0, &dwThreadId);
// FIXME: Do some error handling
assert(hThread != NULL);
}
// Default destructor
CThread::~CThread()
{
if ((hThread != NULL) && (Data.hFinished != NULL)) {
if (!bTerminated)
Terminate();
WaitForSingleObject(Data.hFinished, INFINITE);
CloseHandle(Data.hFinished);
CloseHandle(hThread);
hThread = NULL;
}
}
// Execute thread code
void CThread::Execute()
{
while (!bTerminated) Sleep(0);
}
// Post a message to the thread's message queue
BOOL CThread::PostMessage(UINT Msg, WPARAM wParam, LPARAM lParam)
{
return PostThreadMessage(dwThreadId, Msg, wParam, lParam);
}
// Gracefully terminate thread
void CThread::Terminate()
{
bTerminated = TRUE;
}
// Returns TRUE if thread is terminated, FALSE if not
BOOL CThread::Terminated()
{
return bTerminated;
}
@@ -0,0 +1,131 @@
/*
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS HTTP Daemon
* FILE: config.cpp
* PURPOSE: Daemon configuration
* PROGRAMMERS: Casper S. Hornstrup ([email protected])
* REVISIONS:
* CSH 01/09/2000 Created
*/
#include <new>
#include <stdlib.h>
#include <string.h>
#include <config.h>
#include <tchar.h>
using namespace std;
LPCConfig pConfiguration;
LPCHttpDaemonThread pDaemonThread;
// Default constructor
CConfig::CConfig()
{
Reset();
}
// Default destructor
CConfig::~CConfig()
{
Clear();
}
// Clear configuration
void CConfig::Reset()
{
MainBase = NULL;
HttpBase = NULL;
DefaultResources.RemoveAll();
}
// Create default configuration. Can throw bad_alloc
void CConfig::Default()
{
Clear();
MainBase = (LPWSTR)_wcsdup(dcfgMainBase);
HttpBase = _strdup(dcfgHttpBase);
LPSTR lpsStr;
try {
lpsStr = _strdup(dcfgDefaultResource);
DefaultResources.Insert(lpsStr);
} catch (bad_alloc e) {
free((void *)lpsStr);
Clear();
throw;
}
Port = dcfgDefaultPort;
}
// Clear configuration
void CConfig::Clear()
{
if (MainBase != NULL)
free((void *)MainBase);
if (HttpBase != NULL)
free((void *)HttpBase);
// Free memory for all strings
CIterator<LPSTR> *i = DefaultResources.CreateIterator();
for (i->First(); !i->IsDone(); i->Next())
free((void *)i->CurrentItem());
delete i;
Reset();
}
// Load configuration
BOOL CConfig::Load()
{
Default();
return TRUE;
}
// Save configuration
BOOL CConfig::Save()
{
return TRUE;
}
// Return MainBase
LPWSTR CConfig::GetMainBase()
{
return MainBase;
}
// Set MainBase
void CConfig::SetMainBase(LPWSTR lpwsMainBase)
{
MainBase = lpwsMainBase;
}
// Return HttpBase
LPSTR CConfig::GetHttpBase()
{
return HttpBase;
}
// Set HttpBase
void CConfig::SetHttpBase(LPSTR lpsHttpBase)
{
HttpBase = lpsHttpBase;
}
// Return DefaultResources
CList<LPSTR>* CConfig::GetDefaultResources()
{
return &DefaultResources;
}
// Return bound port
USHORT CConfig::GetPort()
{
return Port;
}
// Set port
VOID CConfig::SetPort(USHORT wPort)
{
Port = wPort;
}
@@ -0,0 +1,16 @@
/*
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS HTTP Daemon
* FILE: error.cpp
* PURPOSE: Error reporting
* PROGRAMMERS: Casper S. Hornstrup ([email protected])
* REVISIONS:
* CSH 01/09/2000 Created
*/
#include <error.h>
#include <stdio.h>
void ReportErrorStr(LPTSTR lpsText)
{
wprintf((wchar_t*)lpsText);
}
@@ -0,0 +1,380 @@
/*
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS HTTP Daemon
* FILE: http.cpp
* PURPOSE: HTTP 1.1 parser engine
* PROGRAMMERS: Casper S. Hornstrup ([email protected])
* REVISIONS:
* CSH 01/09/2000 Created
* TODO: - Implement message-body
* - Implement more generel-header entries
* - Implement more request-header entries
* - Implement more entity-header entries
*/
#include <debug.h>
#include <iostream.h>
#include <string.h>
#include <http.h>
CHAR MethodTable[NUMMETHODS][8] = {"OPTIONS", "GET", "HEAD", "POST", "PUT",
"DELETE", "TRACE"};
CHAR GenerelTable[NUMGENERELS][18] = {"Cache-Control", "Connection", "Date", "Pragma",
"Transfer-Encoding", "Upgrade", "Via"};
CHAR RequestTable[NUMREQUESTS][20] = {"Accept", "Accept-Charset", "Accept-Encoding",
"Accept-Language", "Authorization", "From", "Host", "If-Modified-Since", "If-Match",
"If-None-Match", "If-Range", "If-Unmodified-Since", "Max-Forwards",
"Proxy-Authorization", "Range", "Referer", "User-Agent"};
CHAR EntityTable[NUMENTITIES][17] = {"Allow", "Content-Base", "Content-Encoding",
"Content-Language", "Content-Length", "Content-Location", "Content-MD5",
"Content-Range", "Content-Type", "ETag", "Expires", "Last-Modified"};
// *************************** CHttpParser ***************************
// Default constructor
CHttpParser::CHttpParser()
{
nHead = 0;
nTail = 0;
}
// Default destructor
CHttpParser::~CHttpParser()
{
}
// Returns TRUE if a complete HTTP message is in buffer
BOOL CHttpParser::Complete()
{
UINT nTmp;
/*DPRINT("--1:-%d---\n", sBuffer[nHead-2]);
DPRINT("--2:-%d---\n", sBuffer[nHead-1]);
sBuffer[nHead] = '!';
sBuffer[nHead+1] = 0;
DPRINT("Examining buffer: (Head: %d, Tail: %d)\n", nHead, nTail);
DPRINT("%s\n", (LPSTR)&sBuffer[nTail]);*/
nTmp = nTail;
if (!Parse()) {
if (!bUnknownMethod)
nTail = nTmp;
return FALSE;
} else
return TRUE;
}
// Read a character from buffer
BOOL CHttpParser::ReadChar(LPSTR lpsStr)
{
if (nTail <= nHead) {
if (nTail != nHead) {
lpsStr[0] = sBuffer[nTail];
nTail++;
return TRUE;
} else {
lpsStr[0] = 0;
return FALSE;
}
} else {
if (nTail == sizeof(sBuffer))
nTail = 0;
if (nTail != nHead) {
lpsStr[0] = sBuffer[nTail];
nTail++;
return TRUE;
} else {
lpsStr[0] = 0;
return FALSE;
}
}
}
// Peek at a character in the buffer
BOOL CHttpParser::PeekChar(LPSTR lpsStr)
{
UINT nFakeTail;
if (nTail == sizeof(sBuffer))
nFakeTail = 0;
else
nFakeTail = nTail;
if (nFakeTail != nHead) {
lpsStr[0] = sBuffer[nFakeTail];
return TRUE;
} else {
lpsStr[0] = 0;
return FALSE;
}
}
// Read a string from buffer. Only A-Z, a-z, 0-9 and '-' are valid characters
BOOL CHttpParser::ReadString(LPSTR lpsStr, UINT nLength)
{
UINT i = 0;
CHAR sTmp;
while (PeekChar(&sTmp)) {
if (((sTmp >= 'A') && (sTmp <= 'Z')) || ((sTmp >= 'a') && (sTmp <= 'z')) ||
((sTmp >= '0') && (sTmp <= '9')) || (sTmp == '-')) {
if (i >= (nLength - 1)) {
lpsStr[0] = 0;
return FALSE;
}
ReadChar(&sTmp);
lpsStr[i] = sTmp;
i++;
} else {
lpsStr[i] = 0;
return TRUE;
}
}
lpsStr[0] = 0;
return FALSE;
}
// Read a string from buffer. Stop if SP or CR is found or when there are no more
// characters
BOOL CHttpParser::ReadSpecial(LPSTR lpsStr, UINT nLength)
{
UINT i = 0;
CHAR sTmp;
while (PeekChar(&sTmp) && (sTmp != ' ') && (sTmp != 13)) {
if (i >= (nLength - 1)) {
lpsStr[nLength - 1] = 0;
return FALSE;
}
ReadChar(&sTmp);
lpsStr[i] = sTmp;
i++;
}
lpsStr[i] = 0;
return TRUE;
}
// Skip until "sCh" is found
VOID CHttpParser::Skip(CHAR sCh)
{
CHAR sTmp;
while (PeekChar(&sTmp) && (sTmp != sCh))
ReadChar(&sTmp);
}
// Return TRUE if sCh is the next character
BOOL CHttpParser::Expect(CHAR sCh)
{
CHAR sTmp;
if (PeekChar(&sTmp)) {
if (sTmp == sCh) {
ReadChar(&sTmp);
return TRUE;
}
}
return FALSE;
}
// Return TRUE if CRLF are the next characters
BOOL CHttpParser::ExpectCRLF()
{
return (Expect(13) && Expect(10));
}
// Request = RequestLine | *( GenerelHeader | RequestHeader | EntityHeader )
// CRLF [ MessageBody ]
BOOL CHttpParser::Parse()
{
BOOL bStatus;
CHAR ch;
if (RequestLine()) {
do {
if (!ReadString(sHeader, sizeof(sHeader)))
break;
bStatus = (GenerelHeader());
bStatus = (RequestHeader() || bStatus);
bStatus = (EntityHeader() || bStatus);
} while (bStatus);
// CRLF
if (!ExpectCRLF())
return FALSE;
MessageBody();
return TRUE;
}
return FALSE;
}
// RequestLine = Method SP RequestURI SP HTTP-Version CRLF
BOOL CHttpParser::RequestLine()
{
CHAR sCh;
UINT i;
bUnknownMethod = FALSE;
// RFC 2068 states that servers SHOULD ignore any empty nine(s) received where a
// Request-Line is expected
while (PeekChar(&sCh) && ((sCh == 13) || (sCh == 10)));
if (!ReadString(sMethod, sizeof(sMethod)))
return FALSE;
for (i = 0; i < NUMMETHODS; i++) {
if (strcmp(MethodTable[i], sMethod) == 0) {
nMethodNo = i;
if (!Expect(' '))
return FALSE;
// URI (ie. host/directory/resource)
if (!ReadSpecial(sUri, sizeof(sUri)))
return FALSE;
if (!Expect(' '))
return FALSE;
// HTTP version (eg. HTTP/1.1)
if (!ReadSpecial(sVersion, sizeof(sVersion)))
return FALSE;
// CRLF
if (!ExpectCRLF())
return FALSE;
return TRUE;
}
}
bUnknownMethod = TRUE;
return FALSE;
}
// GenerelHeader = Cache-Control | Connection | Date | Pragma | Transfer-Encoding |
// Upgrade | Via
BOOL CHttpParser::GenerelHeader()
{
INT i;
for (i = 0; i < NUMGENERELS; i++) {
if (strcmp(GenerelTable[i], sHeader) == 0) {
switch (i) {
case 1: {
//Connection
Expect(':');
Expect(' ');
Skip(13);
ExpectCRLF();
break;
}
default: {
Expect(':');
Expect(' ');
Skip(13);
ExpectCRLF();
}
}
return TRUE;
}
}
return FALSE;
}
// RequestHeader = Accept | Accept-Charset | Accept-Encoding | Accept-Language |
// Authorization | From | Host | If-Modified-Since | If-Match |
// If-None-Match | If-Range | If-Unmodified-Since | Max-Forwards |
// Proxy-Authorization | Range | Referer | User-Agent
BOOL CHttpParser::RequestHeader()
{
INT i;
for (i = 0; i < NUMREQUESTS; i++) {
if (strcmp(RequestTable[i], sHeader) == 0) {
switch (i) {
case 0: {
//Accept
Expect(':');
Expect(' ');
Skip(13);
ExpectCRLF();
break;
}
case 2: {
//Accept-Encoding
Expect(':');
Expect(' ');
Skip(13);
ExpectCRLF();
break;
}
case 3: {
//Accept-Language
Expect(':');
Expect(' ');
Skip(13);
ExpectCRLF();
break;
}
case 6: {
//Host
Expect(':');
Expect(' ');
Skip(13);
ExpectCRLF();
break;
}
case 16: {
//User-Agent
Expect(':');
Expect(' ');
Skip(13);
ExpectCRLF();
break;
}
default: {
Expect(':');
Expect(' ');
Skip(13);
ExpectCRLF();
return TRUE;
}
}
return TRUE;
}
}
return FALSE;
}
// EntityHeader = Allow | Content-Base | Content-Encoding | Content-Language |
// Content-Length | Content-Location | Content-MD5 |
// Content-Range | Content-Type | ETag | Expires |
// Last-Modified | extension-header
BOOL CHttpParser::EntityHeader()
{
INT i;
for (i = 0; i < NUMENTITIES; i++) {
if (strcmp(EntityTable[i], sHeader) == 0) {
switch (i) {
case 0:
default: {
//cout << "<Entity-Header>: #" << i << endl;
Expect(':');
Expect(' ');
Skip(13);
ExpectCRLF();
return TRUE;
}
}
return FALSE;
}
}
return FALSE;
}
// MessageBody = *OCTET
BOOL CHttpParser::MessageBody()
{
return FALSE;
}
@@ -0,0 +1,492 @@
/*
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS HTTP Daemon
* FILE: httpd.cpp
* PURPOSE: HTTP daemon
* PROGRAMMERS: Casper S. Hornstrup ([email protected])
* REVISIONS:
* CSH 01/09/2000 Created
*/
#include <debug.h>
#include <new>
#include <malloc.h>
#include <string.h>
#include <config.h>
#include <httpd.h>
#include <error.h>
using namespace std;
CHAR HttpMsg400[] = "<HEAD><TITLE>400 Bad Request</TITLE></HEAD>\n\r<BODY><H1>400 Bad Request</H1>\n\rThe request had bad syntax.<BR>\n\r</BODY>\n\r\n\r";
CHAR HttpMsg404[] = "<HEAD><TITLE>404 Not Found</TITLE></HEAD>\n\r<BODY><H1>404 Not Found</H1>\n\rThe requested URL was not found on this server.<BR>\n\r</BODY>\n\r\n\r";
CHAR HttpMsg405[] = "<HEAD><TITLE>405 Method Not Allowed</TITLE></HEAD>\n\r<BODY><H1>405 Method Not Allowed</H1>\n\rThe requested method is not supported on this server.<BR>\n\r</BODY>\n\r\n\r";
CHAR HttpMsg500[] = "<HEAD><TITLE>500 Internal Server Error</TITLE></HEAD>\n\r<BODY><H1>500 Internal Server Error</H1>\n\rAn internal error occurred.<BR>\n\r</BODY>\n\r\n\r";
CHAR HttpMsg501[] = "<HEAD><TITLE>501 Not Implemented</TITLE></HEAD>\n\r<BODY><H1>501 Not Implemented</H1>\n\rThe feature is not implemented.<BR>\n\r</BODY>\n\r\n\r";
// *************************** CHttpClient ***************************
// Default constructor
CHttpClient::CHttpClient()
{
}
// Constructor with server socket as starter value
CHttpClient::CHttpClient(CServerSocket *serversocket)
{
ServerSocket = serversocket;
}
// Split URIs into its parts (ie. |http://|www.host.com|/resource|?parameters|)
VOID CHttpClient::SplitUri(LPSTR lpsUri, LPSTR lpsHost, LPSTR lpsResource, LPSTR lpsParams)
{
LPSTR lpsPos;
LPSTR lpsStr;
UINT i;
strcpy(lpsHost, "");
strcpy(lpsResource, "");
strcpy(lpsParams, "");
lpsPos = strstr(lpsUri, "://");
if (lpsPos != NULL)
lpsStr = &lpsPos[3];
else
lpsStr = lpsUri;
lpsPos = strstr(lpsStr, "/");
if (lpsPos != NULL) {
strncat(lpsHost, lpsPos, lpsPos - lpsStr);
lpsStr = &lpsPos[1];
lpsPos = strstr(lpsStr, "?");
if (lpsPos != NULL) {
strncat(lpsResource, lpsStr, lpsPos - lpsStr);
strcpy(lpsParams, &lpsPos[1]);
} else {
strcpy(lpsResource, lpsStr);
strcpy(lpsParams, "");
}
// Replace "/" with "\"
for (i = 0; i < strlen(lpsResource); i++) {
if (lpsResource[i] == '/')
lpsResource[i] = '\\';
}
}
}
// Split resource into its parts (ie. |/path/|filename|.extension|)
VOID CHttpClient::SplitResource(LPSTR lpsResource, LPSTR lpsPath, LPSTR lpsFilename, LPSTR lpsExtension)
{
INT i,len,fileptr,extptr;
strcpy(lpsPath, "");
strcpy(lpsFilename, "");
strcpy(lpsExtension, "");
len = strlen(lpsResource);
if (len != 0) {
if (lpsResource[len - 1] == '/') {
// There is only a path
strcpy(lpsPath, lpsResource);
} else {
// Find extension
i = len - 1;
while ((i >= 0) && (lpsResource[i] != '.')) i--;
extptr = i;
while ((i >= 0) && (lpsResource[i] != '/')) i--;
if (i > 0) {
// There is at least one directory in the path (besides root directory)
fileptr = i + 1;
strncat(lpsPath, lpsResource, fileptr);
} else
fileptr = 1;
// Get filename and possibly extension
if (extptr != 0) {
strncat(lpsFilename, &lpsResource[fileptr], extptr - fileptr);
// Get extension
strncat(lpsExtension, &lpsResource[extptr + 1], len - extptr - 1);
} else
strncat(lpsFilename, &lpsResource[fileptr], len - fileptr);
}
}
}
// Process HTTP request
VOID CHttpClient::ProcessRequest()
{
CHAR sStr[255];
CHAR sHost[255];
CHAR sResource[255];
CHAR sParams[255];
// Which method?
switch (Parser.nMethodNo) {
case hmGET: {
SplitUri(Parser.sUri, sHost, sResource, sParams);
// Default resource?
if (strlen(sResource) == 0) {
CIterator<LPSTR> *i = pConfiguration->GetDefaultResources()->CreateIterator();
// FIXME: All default resources should be tried
// Iterate through all strings
//for (i->First(); !i->IsDone(); i->Next())
i->First();
if (!i->IsDone()) {
strcat(sResource, i->CurrentItem());
delete i;
} else {
// File not found
Report("404 Not Found", HttpMsg404);
break;
}
}
strcpy(sStr, pConfiguration->GetHttpBase());
strcat(sStr, sResource);
SendFile(sStr);
break;
}
default: {
// Method is not implemented
Report("501 Not Implemented", HttpMsg501);
}
}
}
// Send a file to socket
VOID CHttpClient::SendFile(LPSTR lpsFilename)
{
CHAR str[255];
CHAR str2[32];
union BigNum {
// unsigned __int64 Big;
unsigned long long Big;
struct {
DWORD Low;
DWORD High;
} u;
} nTotalBytes;
DWORD nBytesToRead;
DWORD nBytesRead;
BOOL bStatus;
// Try to open file
hFile = CreateFileA(lpsFilename,
GENERIC_READ, // Open for reading
FILE_SHARE_READ, // Share for reading
NULL, // No security
OPEN_EXISTING, // Existing file only
FILE_ATTRIBUTE_NORMAL, // Normal file
NULL); // No attr. template
if (hFile == INVALID_HANDLE_VALUE) {
// File not found
Report("404 Not Found", HttpMsg404);
return;
}
// Get file size
nTotalBytes.u.Low = GetFileSize(hFile, &nTotalBytes.u.High);
if ((nTotalBytes.u.Low == 0xFFFFFFFF) && ((GetLastError()) != NO_ERROR)) {
// Internal server error
Report("500 Internal Server Error", HttpMsg500);
// Close file
CloseHandle(hFile);
return;
}
// Determine buffer size
if (nTotalBytes.Big < 65536)
nBufferSize = 1024;
else
nBufferSize = 32768;
// Allocate memory on heap
lpsBuffer = (PCHAR) malloc(nBufferSize);
if (lpsBuffer == NULL) {
// Internal server error
Report("500 Internal Server Error", HttpMsg500);
// Close file
CloseHandle(hFile);
return;
}
SendText("HTTP/1.1 200 OK");
SendText("Server: ROSHTTPD");
SendText("MIME-version: 1.0");
SendText("Content-Type: text/plain");
SendText("Accept-Ranges: bytes");
strcpy(str, "Content-Length: ");
_itoa(nTotalBytes.u.Low, str2, 10);
strcat(str, str2);
SendText(str);
SendText("");
// Read and transmit file
nTotalRead = 0;
nFileSize = nTotalBytes.Big;
bStop = FALSE;
fd_set wfds;
FD_ZERO(&wfds);
FD_SET(Socket, &wfds);
do {
MessageLoop();
if (nTotalRead + nBufferSize < nFileSize)
nBytesToRead = nBufferSize;
else nBytesToRead = nFileSize - nTotalRead;
bStatus = ReadFile(hFile, lpsBuffer, nBytesToRead, &nBytesRead, NULL);
if (bStatus) {
select(0, NULL, &wfds, NULL, NULL);
bStatus = (Transmit(lpsBuffer, nBytesRead) == (INT)nBytesRead);
nTotalRead += nBytesRead;
}
} while ((!bStop) && (bStatus) && (nTotalRead < nFileSize));
if (bStatus)
SendText("");
else
// We can't send an error message here as we are in the process of sending a file.
// We have to terminate the connection instead
Close();
// Free allocated memory
free(lpsBuffer);
// Close file
CloseHandle(hFile);
}
// Report something to client
VOID CHttpClient::Report(LPSTR lpsCode, LPSTR lpsStr)
{
CHAR sTmp[128];
CHAR sTmp2[16];
strcpy(sTmp, "HTTP/1.1 ");
strcat(sTmp, lpsCode);
SendText(sTmp);
SendText("Server: ROSHTTPD");
SendText("MIME-version: 1.0");
SendText("Content-Type: text/html");
SendText("Accept-Ranges: bytes");
strcpy(sTmp, "Content-Length: ");
if (lpsStr != NULL) {
_itoa(strlen(lpsStr), sTmp2, 10);
strcat(sTmp, sTmp2);
} else
strcat(sTmp, "0");
SendText(sTmp);
SendText("");
if (lpsStr != NULL)
SendText(lpsStr);
SendText("");
}
// OnRead event handler
VOID CHttpClient::OnRead()
{
LONG nCount;
nCount = Receive((LPSTR) &Parser.sBuffer[Parser.nHead],
sizeof(Parser.sBuffer) - Parser.nHead);
Parser.nHead += nCount;
if (Parser.nHead >= sizeof(Parser.sBuffer))
Parser.nHead = 0;
if (Parser.Complete()) {
ProcessRequest();
}
if (Parser.bUnknownMethod) {
// Method Not Allowed
Report("405 Method Not Allowed", HttpMsg405);
// Terminate connection
Close();
}
}
/*
// OnWrite event handler
VOID CHttpClient::OnWrite()
{
DWORD nBytesToRead;
DWORD nBytesRead;
OutputDebugString(TS("Can write\n"));
if (bSendingFile) {
if (nTotalRead + nBufferSize < nFileSize)
nBytesToRead = nBufferSize;
else nBytesToRead = nFileSize - nTotalRead;
bError = ReadFile(hFile, Buffer, nBytesToRead, &nBytesRead, NULL);
if (!bError) {
Transmit(Buffer, nBytesRead);
nTotalRead += nBytesRead;
}
}
}
*/
// OnClose event handler
VOID CHttpClient::OnClose()
{
// Stop sending file if we are doing that now
bStop = TRUE;
}
// ************************ CHttpClientThread ************************
// Constructor with client socket as starter value
CHttpClientThread::CHttpClientThread(LPCServerClientSocket lpSocket)
{
ClientSocket = lpSocket;
}
// Execute client thread code
VOID CHttpClientThread::Execute()
{
MSG Msg;
while (!Terminated()) {
(( CHttpClient *) ClientSocket)->MessageLoop();
if (PeekMessage(&Msg, 0, 0, 0, PM_REMOVE) != 0) {
switch (Msg.message) {
case HTTPD_START: {
// TODO: Start thread
break;
}
case HTTPD_STOP: {
// TODO: Stop thread
break;
}
default:
DispatchMessage(&Msg);
}
}
}
if (ClientSocket != NULL) {
delete ClientSocket;
ClientSocket = NULL;
}
}
// *************************** CHttpDaemon ***************************
// Default constructor
CHttpDaemon::CHttpDaemon()
{
State = hsStopped;
Start();
}
// Default destructor
CHttpDaemon::~CHttpDaemon()
{
if (State==hsRunning)
Stop();
}
// Return daemon state
HTTPdState CHttpDaemon::GetState() const
{
return State;
}
// Start HTTP daemon
BOOL CHttpDaemon::Start()
{
assert(State==hsStopped);
SetPort(pConfiguration->GetPort());
Open();
State = hsRunning;
return TRUE;
}
// Stop HTTP daemon
BOOL CHttpDaemon::Stop()
{
assert(State==hsRunning);
Close();
State = hsStopped;
return TRUE;
}
// OnGetSocket event handler
LPCServerClientSocket CHttpDaemon::OnGetSocket(LPCServerSocket lpServerSocket)
{
return new CHttpClient(lpServerSocket);
}
// OnGetThread event handler
LPCServerClientThread CHttpDaemon::OnGetThread(LPCServerClientSocket lpSocket)
{
return new CHttpClientThread(lpSocket);
}
// OnAccept event handler
VOID CHttpDaemon::OnAccept(LPCServerClientThread lpThread)
{
}
// ************************ CHttpDaemonThread ************************
// Execute daemon thread code
VOID CHttpDaemonThread::Execute()
{
MSG Msg;
try {
Daemon = NULL;
Daemon = new CHttpDaemon;
while (!Terminated()) {
Daemon->MessageLoop();
if (PeekMessage(&Msg, 0, 0, 0, PM_REMOVE) != 0) {
switch (Msg.message) {
case HTTPD_START: {
if (Daemon->GetState() == hsStopped)
Daemon->Start();
break;
}
case HTTPD_STOP: {
if (Daemon->GetState() == hsRunning)
Daemon->Stop();
break;
}
case HTTPD_SUSPEND: {
if (Daemon->GetState() == hsRunning){}
// FIXME: Suspend service
break;
}
case HTTPD_RESUME: {
if (Daemon->GetState() != hsSuspended){}
// FIXME: Resume service
break;
}
default:
DispatchMessage(&Msg);
}
}
}
delete Daemon;
} catch (ESocket e) {
ReportErrorStr(e.what());
} catch (bad_alloc e) {
ReportErrorStr(TS("Insufficient resources."));
}
}
@@ -0,0 +1,49 @@
/*
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS HTTP Daemon
* FILE: include/config.h
*/
#ifndef __CONFIG_H
#define __CONFIG_H
#include <list.h>
#include <httpd.h>
// General constants
#define APP_DESCRIPTION _T("ReactOS HTTP Daemon")
// Default configuration
#define dcfgDescription _T("Default configuration")
#define dcfgMainBase _T("C:\\roshttpd\\")
#define dcfgHttpBase "C:\\roshttpd\\HttpBase\\"
#define dcfgDefaultResource "index.html"
#define dcfgDefaultPort 80
class CConfig {
public:
CConfig();
~CConfig();
VOID Default();
VOID Clear();
BOOL Load();
BOOL Save();
LPWSTR GetMainBase();
VOID SetMainBase(LPWSTR lpwsMainBase);
LPSTR GetHttpBase();
VOID SetHttpBase(LPSTR lpsHttpBase);
CList<LPSTR>* GetDefaultResources();
USHORT GetPort();
VOID SetPort(USHORT wPort);
private:
VOID Reset();
LPWSTR MainBase;
LPSTR HttpBase;
CList<LPSTR> DefaultResources;
USHORT Port;
};
typedef CConfig* LPCConfig;
extern LPCConfig pConfiguration;
extern LPCHttpDaemonThread pDaemonThread;
#endif /* __CONFIG_H */
@@ -0,0 +1,17 @@
/*
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS HTTP Daemon
* FILE: include/debug.h
*/
#ifndef __DEBUG_H
#define __DEBUG_H
#include <stdio.h>
#ifdef DBG
#define DPRINT(x...) printf(x)
#else
#define DPRINT(x...)
#endif
#endif /* __DEBUG_H */
@@ -0,0 +1,15 @@
/*
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS HTTP Daemon
* FILE: include/error.h
*/
#ifndef __ERROR_H
#define __ERROR_H
#include <windows.h>
#define TS(x) (LPTSTR)TEXT(x)
void ReportErrorStr(LPTSTR lpsText);
#endif /* __ERROR_H */
@@ -0,0 +1,57 @@
/*
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS HTTP Daemon
* FILE: include/http.h
*/
#ifndef __HTTP_H
#define __HTTP_H
#include <windows.h>
// Generel HTTP related constants
#define NUMMETHODS 7
#define NUMGENERELS 7
#define NUMREQUESTS 17
#define NUMENTITIES 12
// HTTP method constants
#define hmOPTIONS 0
#define hmGET 1
#define hmHEAD 2
#define hmPOST 3
#define hmPUT 4
#define hmDELETE 5
#define hmTRACE 6
class CHttpParser {
public:
CHAR sBuffer[2048];
UINT nHead;
UINT nTail;
CHAR sUri[255];
CHAR sVersion[15];
CHAR sHeader[63];
CHAR sMethod[63];
UINT nMethodNo;
BOOL bUnknownMethod;
BOOL bBadRequest;
CHttpParser();
~CHttpParser();
BOOL Complete();
BOOL Parse();
private:
BOOL ReadChar(LPSTR lpsStr);
BOOL PeekChar(LPSTR lpsStr);
BOOL ReadString(LPSTR lpsStr, UINT nLength);
BOOL ReadSpecial(LPSTR lpStr, UINT nLength);
VOID Skip(CHAR sStr);
BOOL Expect(CHAR sStr);
BOOL ExpectCRLF();
BOOL RequestLine();
BOOL GenerelHeader();
BOOL RequestHeader();
BOOL EntityHeader();
BOOL MessageBody();
};
#endif /* __HTTP_H */
@@ -0,0 +1,85 @@
/*
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS HTTP Daemon
* FILE: include/httpd.h
*/
#ifndef __HTTPD_H
#define __HTTPD_H
#include <thread.h>
#include <socket.h>
#include <http.h>
#define HTTPD_START WM_USER + 1
#define HTTPD_STOP WM_USER + 2
#define HTTPD_SUSPEND WM_USER + 3
#define HTTPD_RESUME WM_USER + 4
enum HTTPdState {
hsStopped = 0,
hsRunning,
hsSuspended
};
class CHttpDaemon;
class CHttpClient : public CServerClientSocket {
public:
CHttpClient();
CHttpClient(LPCServerSocket lpServerSocket);
virtual void OnRead();
//virtual void OnWrite();
virtual void OnClose();
HANDLE ThreadHandle;
DWORD ThreadId;
CHttpParser Parser;
void SplitUri(const LPSTR lpsUri, LPSTR lpsHost, LPSTR lpsResource, LPSTR lpsParams);
void SplitResource(const LPSTR lpsResource, LPSTR lpsPath, LPSTR lpsFilename, LPSTR lpsExtension);
void ProcessRequest();
void SendFile(const LPSTR lpsFilename);
void Report(const LPSTR lpsCode, const LPSTR lpsStr);
private:
BOOL bStop;
LPSTR lpsBuffer;
LONG nBufferSize;
// unsigned __int64 nTotalRead;
unsigned long long nTotalRead;
// unsigned __int64 nFileSize;
unsigned long long nFileSize;
HANDLE hFile;
};
typedef CHttpClient* LPCHttpClient;
class CHttpClientThread : public CServerClientThread {
public:
CHttpClientThread() {};
CHttpClientThread(LPCServerClientSocket Socket);
virtual void Execute();
};
typedef CHttpClientThread* LPCHttpClientThread;
class CHttpDaemon : public CServerSocket {
public:
CHttpDaemon();
virtual ~CHttpDaemon();
HTTPdState GetState() const;
virtual BOOL Start();
virtual BOOL Stop();
virtual LPCServerClientSocket OnGetSocket(LPCServerSocket lpServerSocket);
virtual LPCServerClientThread OnGetThread(LPCServerClientSocket Socket);
virtual void OnAccept(const LPCServerClientThread lpThread);
private:
HTTPdState State;
};
typedef CHttpDaemon* LPCHttpDaemon;
class CHttpDaemonThread : public CThread {
public:
CHttpDaemonThread() {};
virtual void Execute();
private:
CHttpDaemon *Daemon;
};
typedef CHttpDaemonThread* LPCHttpDaemonThread;
#endif /* __HTTPD_H */
@@ -0,0 +1,20 @@
/*
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS HTTP Daemon
* FILE: include/iterator.h
*/
#ifndef __ITERATOR_H
#define __ITERATOR_H
#include <windows.h>
template <class Item>
class CIterator {
public:
virtual VOID First() = 0;
virtual VOID Next() = 0;
virtual BOOL IsDone() const = 0;
virtual Item CurrentItem() const = 0;
};
#endif /* __ITERATOR_H */
@@ -0,0 +1,233 @@
/*
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS HTTP Daemon
* FILE: include/list.h
*/
#ifndef __LIST_H
#define __LIST_H
#include <windows.h>
#include <iterator.h>
class CListNode {
public:
CListNode();
CListNode(VOID *element, CListNode *next, CListNode *prev);
~CListNode() {};
void* operator new(/*size_t s*/ UINT s);
VOID operator delete(void* p);
VOID SetElement(PVOID element);
VOID SetNext(CListNode *next);
VOID SetPrev(CListNode *prev);
PVOID GetElement();
CListNode *GetNext();
CListNode *GetPrev();
private:
PVOID Element;
CListNode *Next;
CListNode *Prev;
static HANDLE hHeap;
static INT nRef;
};
template <class Item> class CList {
public:
//CList(CList&);
CList();
~CList();
CList& operator=(CList&);
CIterator<Item> *CreateIterator() const;
LONG Count() const;
Item& Get(const LONG index) const;
// Can throw bad_alloc
VOID Insert(Item& element);
VOID Remove(Item& element);
VOID RemoveAll();
CListNode *GetHeader() const;
CListNode *GetTrailer() const;
private:
CListNode *Search(Item& element) const;
LONG NodeCount;
CListNode *Header;
CListNode *Trailer;
};
template <class Item> class CListIterator : public CIterator<Item> {
public:
CListIterator(const CList<Item> *list);
virtual VOID First();
virtual VOID Next();
virtual BOOL IsDone() const;
virtual Item CurrentItem() const;
private:
const CList<Item> *List;
CListNode *Current;
};
// ****************************** CList ******************************
// Default constructor
template <class Item>
CList<Item>::CList()
{
// Create dummy nodes
Trailer = new CListNode;
Header = new CListNode;
Header->SetNext(Trailer);
Trailer->SetPrev(Header);
}
// Default destructor
template <class Item>
CList<Item>::~CList()
{
RemoveAll();
delete Trailer;
delete Header;
}
// Create an iterator for the list
template <class Item>
CIterator<Item> *CList<Item>::CreateIterator() const
{
return new CListIterator<Item>((CList<Item> *) this);
}
// Return number of elements in list
template <class Item>
LONG CList<Item>::Count() const
{
return NodeCount;
}
// Return element at index
template <class Item>
Item& CList<Item>::Get(const LONG index) const
{
CListNode *node;
if ((index < 0) || (index >= NodeCount))
return NULL;
node = Header;
for (int i = 0; i <= index; i++)
node = node->GetNext();
return (Item *) node->GetElement();
}
// Insert an element into the list
template <class Item>
VOID CList<Item>::Insert(Item& element)
{
CListNode *node;
node = new CListNode((PVOID)element, Trailer, Trailer->GetPrev());
Trailer->GetPrev()->SetNext(node);
Trailer->SetPrev(node);
NodeCount++;
}
// Remove an element from the list
template <class Item>
VOID CList<Item>::Remove(Item& element)
{
CListNode *node;
node = Search(element);
if (node != NULL) {
node->GetPrev()->SetNext(node->GetNext());
node->GetNext()->SetPrev(node->GetPrev());
NodeCount--;
delete node;
}
}
// Remove all elements in list
template <class Item>
VOID CList<Item>::RemoveAll()
{
CListNode *node;
CListNode *tmp;
node = Header->GetNext();
while (node != Trailer) {
tmp = node->GetNext();
delete node;
node = tmp;
}
Header->SetNext(Trailer);
Trailer->SetPrev(Header);
NodeCount = 0;
}
// Return header node
template <class Item>
CListNode *CList<Item>::GetHeader() const
{
return Header;
}
// Return trailer node
template <class Item>
CListNode *CList<Item>::GetTrailer() const
{
return Trailer;
}
// Searches for a node that contains the element. Returns NULL if element is not found
template <class Item>
CListNode *CList<Item>::Search(Item& element) const
{
CListNode *node;
node = Header;
while (((node = node->GetNext()) != Trailer) && (node->GetElement() != element));
if (node != Trailer)
return node;
else
return NULL;
}
// ************************** CListIterator **************************
// Default constructor
template <class Item>
CListIterator<Item>::CListIterator(const CList<Item> *list) : List(list)
{
First();
}
// Go to first element in list
template <class Item>
VOID CListIterator<Item>::First()
{
Current = List->GetHeader()->GetNext();
}
// Go to next element in list
template <class Item>
VOID CListIterator<Item>::Next()
{
if (!IsDone())
Current = Current->GetNext();
}
// Return FALSE when there are more elements in list and TRUE when there are no more
template <class Item>
BOOL CListIterator<Item>::IsDone() const
{
return (Current == List->GetTrailer());
}
// Return current element
template <class Item>
Item CListIterator<Item>::CurrentItem() const
{
return IsDone()? NULL : (Item) Current->GetElement();
}
#endif /* __LIST_H */
@@ -0,0 +1,141 @@
/*
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS HTTP Daemon
* FILE: include/socket.h
*/
#ifndef __SOCKET_H
#define __SOCKET_H
#include <msvcrt/stdio.h>
#include <windows.h>
#include <winsock2.h>
#include <thread.h>
#include <list.h>
#include <exception>
#include <assert.h>
#define MAX_PENDING_CONNECTS 4 // The backlog allowed for listen()
VOID InitWinsock();
VOID DeinitWinsock();
class CSocket;
class CClientSocket;
class CServerClientSocket;
class CServerClientThread;
class CServerSocket;
typedef CSocket* LPCSocket;
typedef CClientSocket* LPCClientSocket;
typedef CServerClientSocket* LPCServerClientSocket;
typedef CServerClientThread* LPCServerClientThread;
typedef CServerSocket* LPCServerSocket;
class ESocket {
public:
ESocket() { Description = NULL; }
ESocket(LPTSTR description) { Description = description; }
LPTSTR what() { return Description; }
protected:
LPTSTR Description;
};
class ESocketWinsock : public ESocket {
public:
ESocketWinsock(LPTSTR description) { Description = description; }
};
class ESocketDll : public ESocket {
public:
ESocketDll(LPTSTR description) { Description = description; }
};
class ESocketOpen : public ESocket {
public:
ESocketOpen(LPTSTR description) { Description = description; }
};
class ESocketClose : public ESocket {
public:
ESocketClose(LPTSTR description) { Description = description; }
};
class ESocketSend : public ESocket {
public:
ESocketSend(LPTSTR description) { Description = description; }
};
class ESocketReceive : public ESocket {
public:
ESocketReceive(LPTSTR description) { Description = description; }
};
class CSocket {
public:
CSocket();
virtual ~CSocket();
virtual SOCKET GetSocket();
virtual VOID SetSocket(SOCKET socket);
virtual SOCKADDR_IN GetSockAddrIn();
virtual VOID SetSockAddrIn(SOCKADDR_IN sockaddrin);
virtual VOID SetEvents(LONG lEvents);
virtual LONG GetEvents();
virtual VOID SetPort( UINT nPort) {};
virtual VOID Open();
virtual VOID Close();
virtual INT Transmit( LPSTR lpsBuffer, UINT nLength) { return 0; };
virtual INT Receive(LPSTR lpsBuffer, UINT nLength) { return 0; };
virtual INT SendText( LPSTR lpsStr) { return 0; };
protected:
SOCKET Socket;
SOCKADDR_IN SockAddrIn;
WSAEVENT Event;
UINT Port;
BOOL Active;
private:
LONG Events;
};
class CServerClientSocket : public CSocket {
public:
CServerClientSocket() {};
CServerClientSocket(LPCServerSocket lpServerSocket);
CServerSocket *GetServerSocket();
virtual INT Transmit( LPSTR lpsBuffer, UINT nLength);
virtual INT Receive(LPSTR lpsBuffer, UINT nLength);
virtual INT SendText( LPSTR lpsText);
virtual VOID MessageLoop();
virtual VOID OnRead() {};
//virtual VOID OnWrite() {};
virtual VOID OnClose() {};
protected:
LPCServerSocket ServerSocket;
};
class CServerClientThread : public CThread {
public:
CServerClientThread() {};
CServerClientThread(CServerClientSocket *socket);
virtual ~CServerClientThread();
protected:
CServerClientSocket *ClientSocket;
};
class CServerSocket : public CSocket {
public:
CServerSocket();
virtual ~CServerSocket();
virtual VOID SetPort( UINT nPort);
virtual VOID Open();
virtual VOID Close();
virtual LPCServerClientSocket OnGetSocket(LPCServerSocket lpServerSocket);
virtual LPCServerClientThread OnGetThread(LPCServerClientSocket lpSocket);
virtual VOID OnAccept( LPCServerClientThread lpThread) {};
virtual VOID MessageLoop();
VOID InsertClient(LPCServerClientThread lpClient);
VOID RemoveClient(LPCServerClientThread lpClient);
protected:
CList<LPCServerClientThread> Connections;
};
#endif /* __SOCKET_H */
@@ -0,0 +1,34 @@
/*
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS HTTP Daemon
* FILE: include/thread.h
*/
#ifndef __THREAD_H
#define __THREAD_H
#include <windows.h>
class CThread;
struct ThreadData {
CThread *ClassPtr;
HANDLE hFinished;
};
class CThread {
public:
CThread();
virtual ~CThread();
BOOL PostMessage(UINT Msg, WPARAM wParam, LPARAM lParam);
virtual void Execute();
virtual void Terminate();
BOOL Terminated();
protected:
BOOL bTerminated;
DWORD dwThreadId;
HANDLE hThread;
ThreadData Data;
};
typedef CThread *LPCThread;
#endif /* __THREAD_H */
@@ -0,0 +1,66 @@
/*
* COPYRIGHT: See COPYING in the top level directory
* PROJECT: ReactOS HTTP Daemon
* FILE: roshttpd.cpp
* PURPOSE: Main program
* PROGRAMMERS: Casper S. Hornstrup ([email protected])
* REVISIONS:
* CSH 01/09/2000 Created
*/
#include <debug.h>
#include <new>
#include <winsock2.h>
#include <stdio.h>
#include <config.h>
#include <error.h>
#include <httpd.h>
using namespace std;
VOID Run()
{
InitWinsock();
pDaemonThread = NULL;
pConfiguration = NULL;
try {
// Create configuration object
pConfiguration = new CConfig;
pConfiguration->Default();
// Create daemon object
pDaemonThread = new CHttpDaemonThread;
MSG Msg;
BOOL bQuit = FALSE;
while ((!bQuit) && (!pDaemonThread->Terminated())) {
bQuit = PeekMessage(&Msg, NULL, 0, 0, PM_REMOVE);
if (!bQuit)
DispatchMessage(&Msg);
}
delete pDaemonThread;
if (pConfiguration != NULL)
delete pConfiguration;
} catch (bad_alloc e) {
if (pConfiguration != NULL)
delete pConfiguration;
ReportErrorStr(TS("Insufficient resources."));
}
DeinitWinsock();
}
/* Program entry point */
int main(int argc, char* argv[])
{
printf("ReactOS HTTP Daemon\n");
printf("Type Control-C to stop.\n");
Run();
printf("Daemon stopped.\n");
}
+308
View File
@@ -0,0 +1,308 @@
/* Poor man's route
*
* Supported commands:
*
* "print"
* "add" target ["mask" mask] gw ["metric" metric]
* "delete" target gw
*
* Goals:
*
* Flexible, simple
*/
#include <stdio.h>
#include <windows.h>
#include <iphlpapi.h>
#include <winsock2.h>
#include <tchar.h>
#define IPBUF 17
#define IN_ADDR_OF(x) *((struct in_addr *)&(x))
static int Usage()
{
_ftprintf( stderr,
_T("route usage:\n"
"route print\n"
" prints the route table\n"
"route add <target> [mask <mask>] <gw> [metric <m>]\n"
" adds a route\n"
"route delete <target> <gw>\n"
" deletes a route\n") );
return 1;
}
static int PrintRoutes()
{
PMIB_IPFORWARDTABLE IpForwardTable = NULL;
PIP_ADAPTER_INFO pAdapterInfo;
ULONG Size = 0;
DWORD Error = 0;
ULONG adaptOutBufLen = sizeof(IP_ADAPTER_INFO);
TCHAR DefGate[16];
TCHAR Destination[IPBUF], Gateway[IPBUF], Netmask[IPBUF];
unsigned int i;
/* set required buffer size */
pAdapterInfo = (IP_ADAPTER_INFO *) malloc( adaptOutBufLen );
if (pAdapterInfo == NULL)
{
Error = ERROR_NOT_ENOUGH_MEMORY;
goto Error;
}
if (GetAdaptersInfo( pAdapterInfo, &adaptOutBufLen) == ERROR_BUFFER_OVERFLOW)
{
free (pAdapterInfo);
pAdapterInfo = (IP_ADAPTER_INFO *) malloc (adaptOutBufLen);
if (pAdapterInfo == NULL)
{
Error = ERROR_NOT_ENOUGH_MEMORY;
goto Error;
}
}
if( (GetIpForwardTable( NULL, &Size, TRUE )) == ERROR_INSUFFICIENT_BUFFER )
{
if (!(IpForwardTable = malloc( Size )))
{
free(pAdapterInfo);
Error = ERROR_NOT_ENOUGH_MEMORY;
goto Error;
}
}
if (((Error = GetAdaptersInfo(pAdapterInfo, &adaptOutBufLen)) == NO_ERROR) &&
((Error = GetIpForwardTable(IpForwardTable, &Size, TRUE)) == NO_ERROR))
{
_stprintf(DefGate,
#if UNICODE
_T("%hs"),
#else
_T("%s"),
#endif
pAdapterInfo->GatewayList.IpAddress.String);
_tprintf(_T("===========================================================================\n"));
_tprintf(_T("Interface List\n"));
/* FIXME - sort by the index! */
while (pAdapterInfo)
{
_tprintf(_T("0x%lu ........................... "
#if UNICODE
"%hs\n"),
#else
"%s\n"),
#endif
pAdapterInfo->Index, pAdapterInfo->Description);
pAdapterInfo = pAdapterInfo->Next;
}
_tprintf(_T("===========================================================================\n"));
_tprintf(_T("===========================================================================\n"));
_tprintf(_T("Active Routes:\n"));
_tprintf( _T("%-27s%-17s%-14s%-11s%-10s\n"),
_T("Network Destination"),
_T("Netmask"),
_T("Gateway"),
_T("Interface"),
_T("Metric") );
for( i = 0; i < IpForwardTable->dwNumEntries; i++ )
{
_stprintf( Destination,
#if UNICODE
_T("%hs"),
#else
_T("%s"),
#endif
inet_ntoa( IN_ADDR_OF(IpForwardTable->table[i].dwForwardDest) ) );
_stprintf( Netmask,
#if UNICODE
_T("%hs"),
#else
_T("%s"),
#endif
inet_ntoa( IN_ADDR_OF(IpForwardTable->table[i].dwForwardMask) ) );
_stprintf( Gateway,
#if UNICODE
_T("%hs"),
#else
_T("%s"),
#endif
inet_ntoa( IN_ADDR_OF(IpForwardTable->table[i].dwForwardNextHop) ) );
_tprintf( _T("%17s%17s%17s%16ld%9ld\n"),
Destination,
Netmask,
Gateway,
IpForwardTable->table[i].dwForwardIfIndex,
IpForwardTable->table[i].dwForwardMetric1 );
}
_tprintf(_T("Default Gateway:%18s\n"), DefGate);
_tprintf(_T("===========================================================================\n"));
_tprintf(_T("Persistent Routes:\n"));
free(IpForwardTable);
free(pAdapterInfo);
return ERROR_SUCCESS;
}
else
{
Error:
_ftprintf( stderr, _T("Route enumerate failed\n") );
return Error;
}
}
static int convert_add_cmd_line( PMIB_IPFORWARDROW RowToAdd,
int argc, TCHAR **argv ) {
int i;
#if UNICODE
char addr[16];
#endif
if( argc > 1 )
{
#if UNICODE
sprintf( addr, "%ls", argv[0] );
RowToAdd->dwForwardDest = inet_addr( addr );
#else
RowToAdd->dwForwardDest = inet_addr( argv[0] );
#endif
}
else
return FALSE;
for( i = 1; i < argc; i++ )
{
if( !_tcscmp( argv[i], _T("mask") ) )
{
i++; if( i >= argc ) return FALSE;
#if UNICODE
sprintf( addr, "%ls", argv[i] );
RowToAdd->dwForwardDest = inet_addr( addr );
#else
RowToAdd->dwForwardMask = inet_addr( argv[i] );
#endif
}
else if( !_tcscmp( argv[i], _T("metric") ) )
{
i++;
if( i >= argc )
return FALSE;
RowToAdd->dwForwardMetric1 = _ttoi( argv[i] );
}
else
{
#if UNICODE
sprintf( addr, "%ls", argv[i] );
RowToAdd->dwForwardNextHop = inet_addr( addr );
#else
RowToAdd->dwForwardNextHop = inet_addr( argv[i] );
#endif
}
}
return TRUE;
}
static int add_route( int argc, TCHAR **argv ) {
MIB_IPFORWARDROW RowToAdd = { 0 };
DWORD Error;
if( argc < 2 || !convert_add_cmd_line( &RowToAdd, argc, argv ) )
{
_ftprintf( stderr,
_T("route add usage:\n"
"route add <target> [mask <mask>] <gw> [metric <m>]\n"
" Adds a route to the IP route table.\n"
" <target> is the network or host to add a route to.\n"
" <mask> is the netmask to use (autodetected if unspecified)\n"
" <gw> is the gateway to use to access the network\n"
" <m> is the metric to use (lower is preferred)\n") );
return 1;
}
if( (Error = CreateIpForwardEntry( &RowToAdd )) == ERROR_SUCCESS )
return 0;
_ftprintf( stderr, _T("Route addition failed\n") );
return Error;
}
static int del_route( int argc, TCHAR **argv )
{
MIB_IPFORWARDROW RowToDel = { 0 };
DWORD Error;
if( argc < 2 || !convert_add_cmd_line( &RowToDel, argc, argv ) )
{
_ftprintf( stderr,
_T("route delete usage:\n"
"route delete <target> <gw>\n"
" Removes a route from the IP route table.\n"
" <target> is the network or host to add a route to.\n"
" <gw> is the gateway to remove the route from.\n") );
return 1;
}
if( (Error = DeleteIpForwardEntry( &RowToDel )) == ERROR_SUCCESS )
return 0;
_ftprintf( stderr, _T("Route addition failed\n") );
return Error;
}
#if defined(_UNICODE) && defined(__GNUC__)
static
#endif
int _tmain( int argc, TCHAR **argv )
{
if( argc < 2 )
return Usage();
else if ( !_tcscmp( argv[1], _T("print") ) )
return PrintRoutes();
else if( !_tcscmp( argv[1], _T("add") ) )
return add_route( argc-2, argv+2 );
else if( !_tcscmp( argv[1], _T("delete") ) )
return del_route( argc-2, argv+2 );
else
return Usage();
}
#if defined(_UNICODE) && defined(__GNUC__)
/* HACK - MINGW HAS NO OFFICIAL SUPPORT FOR wmain()!!! */
int main( int argc, char **argv )
{
WCHAR **argvW;
int i, j, Ret = 1;
if ((argvW = malloc(argc * sizeof(WCHAR*))))
{
/* convert the arguments */
for (i = 0, j = 0; i < argc; i++)
{
if (!(argvW[i] = malloc((strlen(argv[i]) + 1) * sizeof(WCHAR))))
{
j++;
}
swprintf(argvW[i], L"%hs", argv[i]);
}
if (j == 0)
{
/* no error converting the parameters, call wmain() */
Ret = wmain(argc, argvW);
}
/* free the arguments */
for (i = 0; i < argc; i++)
{
if (argvW[i])
free(argvW[i]);
}
free(argvW);
}
return Ret;
}
#endif
@@ -0,0 +1,7 @@
/* $Id$ */
#define REACTOS_STR_FILE_DESCRIPTION "ReactOS TCP/IPv4 Win32 Route\0"
#define REACTOS_STR_INTERNAL_NAME "route\0"
#define REACTOS_STR_ORIGINAL_FILENAME "route.exe\0"
#define REACTOS_STR_ORIGINAL_COPYRIGHT "Art Yerkes ([email protected])\0"
#include <reactos/version.rc>
@@ -0,0 +1,11 @@
<module name="route" type="win32cui" installbase="system32" installname="route.exe">
<include base="route">.</include>
<define name="__USE_W32API" />
<define name="UNICODE" />
<define name="_UNICODE" />
<library>kernel32</library>
<library>ws2_32</library>
<library>iphlpapi</library>
<file>route.c</file>
<file>route.rc</file>
</module>
@@ -0,0 +1,142 @@
#
# Makefile for Console Telnet
# Last modified 4/15/2000 by Paul Brannan
#
SRCDIR=./src
OBJDIR=src
RESDIR=resource
SRC=$(wildcard $(SRCDIR)/*.cpp)
RESOURCES=$(wildcard $(RESDIR)/*.rc)
OBJ1=$(SRC:.c=.o)
OBJ=$(OBJ1:.cpp=.o) $(RESOURCES:.rc=.o)
INCLUDES=-I$(RESDIR)
OUT=telnet.exe
# Modify these for your system if necessary
# Note: DJGPP+RDXNTDJ configuration is untested.
# --CYGWIN--
#CC=gcc
#CCC=g++
#LDFLAGS=-lwsock32 -lmsvcrt
#CFLAGS=-O2 -Wall -mwindows -mno-cygwin -D__CYGWIN__
#CCFLAGS=$(CFLAGS)
#RES=
#RC=windres
#RCFLAGS=-O coff
# --MINGW32(+EGCS)--
CC=gcc
CCC=g++
LDFLAGS=-lkernel32 -luser32 -lgdi32 -lshell32 -lwsock32
CFLAGS=-O2 -Wall
CCFLAGS=$(CFLAGS)
RES=
RC=windres
RCFLAGS=
# --DJGPP+RSXNTDJ--
#CC=gcc -Zwin32 -Zmt -Zcrtdll
#CCC=$(CC)
#LDFLAGS=
#CFLAGS= -g
#CCFLAGS=$(CFLAGS)
#RES=rsrc
#RC=grc
#RCFLAGS=-r
# You should not have to modify anything below this line
all: dep $(OUT)
.SUFFIXES: .c .cpp .rc
.c.o:
$(CC) $(INCLUDES) $(CFLAGS) -c $< -o $@
.cpp.o:
$(CCC) $(INCLUDES) $(CCFLAGS) -c $< -o $@
.rc.o:
$(RC) -i $< $(RCFLAGS) -o $@
$(OUT): $(OBJ)
$(CCC) $(OBJ) $(LDFLAGS) $(LIBS) -o $(OUT)
strip $(OUT)
depend: dep
dep:
start /min makedepend -- $(CFLAGS) -- $(INCLUDES) $(SRC)
clean:
del $(OBJDIR)\*.o
del $(OUT)
# DO NOT DELETE
./src/ansiprsr.o: ./src/ansiprsr.h ./src/tnconfig.h ./src/tnerror.h
./src/ansiprsr.o: ./src/tnmsg.h ./src/tparser.h ./src/tconsole.h
./src/ansiprsr.o: ./src/keytrans.h ./src/tkeydef.h ./src/tkeymap.h
./src/ansiprsr.o: ./src/stl_bids.h ./src/tscroll.h ./src/tmouse.h
./src/ansiprsr.o: ./src/tnclip.h ./src/tnetwork.h ./src/tcharmap.h
./src/keytrans.o: ./src/keytrans.h ./src/tkeydef.h ./src/tkeymap.h
./src/keytrans.o: ./src/stl_bids.h ./src/tnerror.h ./src/tnmsg.h
./src/tcharmap.o: ./src/tcharmap.h ./src/tnconfig.h ./src/tnerror.h
./src/tcharmap.o: ./src/tnmsg.h
./src/tconsole.o: ./src/tconsole.h ./src/tnconfig.h ./src/tnerror.h
./src/tconsole.o: ./src/tnmsg.h
./src/tkeydef.o: ./src/tkeydef.h
./src/tkeymap.o: ./src/tkeymap.h ./src/stl_bids.h ./src/tkeydef.h
./src/tmapldr.o: ./src/tmapldr.h ./src/keytrans.h ./src/tkeydef.h
./src/tmapldr.o: ./src/tkeymap.h ./src/stl_bids.h ./src/tcharmap.h
./src/tmapldr.o: ./src/tnerror.h ./src/tnmsg.h ./src/tnconfig.h
./src/tmouse.o: ./src/tmouse.h ./src/tnclip.h ./src/tnetwork.h
./src/tmouse.o: ./src/tconsole.h ./src/tnconfig.h ./src/tnerror.h
./src/tmouse.o: ./src/tnmsg.h
./src/tnclass.o: ./src/tnclass.h ./src/tnconfig.h ./src/tnerror.h
./src/tnclass.o: ./src/tnmsg.h ./src/ttelhndl.h ./src/tparser.h
./src/tnclass.o: ./src/tconsole.h ./src/keytrans.h ./src/tkeydef.h
./src/tnclass.o: ./src/tkeymap.h ./src/stl_bids.h ./src/tscroll.h
./src/tnclass.o: ./src/tmouse.h ./src/tnclip.h ./src/tnetwork.h
./src/tnclass.o: ./src/tcharmap.h ./src/tncon.h ./src/tparams.h
./src/tnclass.o: ./src/ansiprsr.h ./src/tmapldr.h ./src/tnmisc.h
./src/tnclip.o: ./src/tnclip.h ./src/tnetwork.h
./src/tncon.o: ./src/tncon.h ./src/tparams.h ./src/ttelhndl.h ./src/tparser.h
./src/tncon.o: ./src/tconsole.h ./src/tnconfig.h ./src/tnerror.h
./src/tncon.o: ./src/tnmsg.h ./src/keytrans.h ./src/tkeydef.h ./src/tkeymap.h
./src/tncon.o: ./src/stl_bids.h ./src/tscroll.h ./src/tmouse.h ./src/tnclip.h
./src/tncon.o: ./src/tnetwork.h ./src/tcharmap.h
./src/tnconfig.o: ./src/tnconfig.h ./src/tnerror.h ./src/tnmsg.h
./src/tnerror.o: ./src/tnerror.h ./src/tnmsg.h ./src/ttelhndl.h
./src/tnerror.o: ./src/tparser.h ./src/tconsole.h ./src/tnconfig.h
./src/tnerror.o: ./src/keytrans.h ./src/tkeydef.h ./src/tkeymap.h
./src/tnerror.o: ./src/stl_bids.h ./src/tscroll.h ./src/tmouse.h
./src/tnerror.o: ./src/tnclip.h ./src/tnetwork.h ./src/tcharmap.h
./src/tnetwork.o: ./src/tnetwork.h
./src/tnmain.o: ./src/tnmain.h ./src/tncon.h ./src/tparams.h ./src/ttelhndl.h
./src/tnmain.o: ./src/tparser.h ./src/tconsole.h ./src/tnconfig.h
./src/tnmain.o: ./src/tnerror.h ./src/tnmsg.h ./src/keytrans.h
./src/tnmain.o: ./src/tkeydef.h ./src/tkeymap.h ./src/stl_bids.h
./src/tnmain.o: ./src/tscroll.h ./src/tmouse.h ./src/tnclip.h
./src/tnmain.o: ./src/tnetwork.h ./src/tcharmap.h ./src/tnclass.h
./src/tnmain.o: ./src/ansiprsr.h ./src/tmapldr.h ./src/tnmisc.h
./src/tnmisc.o: ./src/tnmisc.h
./src/tscript.o: ./src/tscript.h ./src/tnetwork.h
./src/tscroll.o: ./src/tscroll.h ./src/tconsole.h ./src/tnconfig.h
./src/tscroll.o: ./src/tnerror.h ./src/tnmsg.h ./src/tmouse.h ./src/tnclip.h
./src/tscroll.o: ./src/tnetwork.h ./src/tncon.h ./src/tparams.h
./src/tscroll.o: ./src/ttelhndl.h ./src/tparser.h ./src/keytrans.h
./src/tscroll.o: ./src/tkeydef.h ./src/tkeymap.h ./src/stl_bids.h
./src/tscroll.o: ./src/tcharmap.h
./src/ttelhndl.o: ./src/ttelhndl.h ./src/tparser.h ./src/tconsole.h
./src/ttelhndl.o: ./src/tnconfig.h ./src/tnerror.h ./src/tnmsg.h
./src/ttelhndl.o: ./src/keytrans.h ./src/tkeydef.h ./src/tkeymap.h
./src/ttelhndl.o: ./src/stl_bids.h ./src/tscroll.h ./src/tmouse.h
./src/ttelhndl.o: ./src/tnclip.h ./src/tnetwork.h ./src/tcharmap.h
./src/ttelhndl.o: ./src/telnet.h ./src/tparams.h
@@ -0,0 +1,261 @@
Hi!
Now I come back to telnet source, and make some changes, wich you suggest
to me:
1. telnet.rc renamed to telnet.cfg
2. I change syntax of 'keys' command (but I did'nt found a tool for edit
msg*.bin files - so it's remain unchanged). Syntax are
keys load keymapname [file]
keys display
keys switch number
I fix some 'political' ;) problem with charmap, now we (citizens of xUSSR)
have koi8, koi8r and koi8u(RFC on draft) on UNIX, wich are diff's on 6 or
8 letters; cp866 and many (3 or 4) very near to cp866 on DOS.
So, I rewrite code to able a charmap addition like a keymap done.
And I make more smart command line processing, look at telCommandLine().
And last: my english is not so good :( to rewrite documentation, but there are
things, wich would be described - look on next page. I think that you will
translate my english to more understable, ok?
and now is a list of files, wich I touch
old new
ANSIPRSR.CPP 32763 05.10.97 11:09 33237 24.12.97 17:42
ANSIPRSR.H 3311 04.09.97 0:25 3410 23.12.97 13:18
KEYTRANS.CPP 9504 28.05.97 22:43 26547 03.02.98 21:33
KEYTRANS.H 8020 25.01.97 16:06 8090 03.02.98 19:53
TNCLASS.CPP 13663 17.08.97 23:55 13891 03.02.98 20:09
TNCLASS.H 1112 01.06.97 14:19 1233 03.02.98 20:09
TNMAIN.CPP 12668 02.10.97 20:38 16610 03.02.98 21:22
TNNET.CPP 3445 01.06.97 14:21 3474 23.12.97 13:16
TNPARSER.CPP 17653 05.10.97 11:09 17715 23.12.97 18:03
TNPARSER.H 2129 01.06.97 14:22 2188 23.12.97 13:25
KEYS.CFG erased
TELNET.CFG new
TELNET.IDE 65810 26.10.97 16:53 66118 03.02.98 21:34
I was start my work with file telc2b4s.zip with size 132619 bytes, and now send
to you just files, wich I touch.
with best regards
Andrei V. Smilianets
[email protected]
22:25 03 Feb 1998
There are all of my changes (from 2.04b), wich have to be described:
1. command line (telnet>) processing
a 'keys' command
was
keys keymapname [file]
new
keys load keymapname [file] // mean unchanged
keys display // display a list of loaded keymaps
keys switch number // switch to keymap
more smart command processing
command might be writed shortly
cl[ose]
op[en]
ke[ys]
qu[it]
subcommands of 'keys'
l[oad]
d[isplay]
s[witch]
synonym of '?' -> h[elp]
2. file 'keys.cfg' renamed to 'telnet.cfg'
3. Added codepage conversion, look [charmap]
4. completely changed conception of telnet.cfg
Now you can define multiple keymaps, character maps, combine it in your
ways.
file is splitted into following sections:
[COMMENT]
...
[END COMMENT]
it is for comment a big part of text. can be nested.
in text also work:
; - first printable character in line, which is completelly
ignored.
// - like C++ comment
[GLOBAL]
...
[END GLOBAL]
mean of [global] unchanged
[KEYMAP name]
...
[END KEYMAP]
'name' - is a keymap name for reference. in 'name' you can use
any char exept spaces, '+', ':' and ']'. '+' and ':' reserved for
CONFIG section.
body is a sequence of key definition:
<vk_name> [keymodifier[+keymodifier[+...]]] <keytranslation>
example:
VK_F1 RIGHT_ALT+RIGHT_CTRL this_would_print
vk_name is an ASCII string equivalent to an entry in [GLOBAL].
valid keymodifiers are:
RIGHT_ALT
LEFT_ALT
RIGHT_CTRL
LEFT_CTRL
SHIFT
ENHANCED
Undefined enhanced keys will use the non-enhanced definition.
keytranslation is the string you want printed for the key.
The notation ^[ can be used to denote an escape character.
Any ASCII value can be represented by
\nnn where nnn is a 3 digit decimal ASCII value or
\xhh where hh is a 2 digit hexadecimal ASCII value.
Leading zeros may not be omitted.
A value of \000(\x00) will not be transmitted.
note: In order to have both left and right alt have the same
action, you must create a separate def for left and right.
[CHARMAP name]
...
[END CHARMAP]
'name' - is a charmap name for reference. requirements is the same
as for keymap name.
body is a sequence of char conversion definition:
<host_char> <console_char>
where host_char is a char received from host, and console_char
is a char, which would be displayed on console.
The main purpose of it is a conversion between differents code
pages, for example, on former USSR part of world most unix's hosts
uses 'koi8' code page, and on W95 machines - 866 code page and
(as say I.Ioannou) Greece has the same problem with 737 and 928
code-pages.
Any ASCII value can be represented by
\nnn where nnn is a 3 digit decimal ASCII value or
\xhh where hh is a 2 digit hexadecimal ASCII value.
Leading zeros may be omitted.
A value of \000(\x00) will not be accepted.
look for example at [charmap koi8-cp866].
[CONFIG name]
...
[END CONFIG]
'name' - is a configuration name for reference. requirements is
the same as for keymap name.
you must define one with name 'default', which will be used as
default.
in body of this part you can combine keymaps and set charmap,
format is:
KEYMAP name_list [: <vk_name> [keymodifier[+keymodifier[+...]]] ]
where
name_list:
keymap_name
keymap_name '+' name_list
keymap_name is a name of [KEYMAP]
You can specify multiple keymaps, for first (mean default)
you can not define ': <vk_name> ...' part, but for rests
(secondary) you must!
The ': <vk_name> ...' part define a key for switch to this
keymap.
Assigning a switching key to first (default) keymap will be
ignored, but you can switch to by pressing second time switch
key of current keymap.
If a key not found in switched keymap, a program will be look
for it in default keymap. So, you can redefine only needed keys
in secondary keymaps.
CHARMAP name_list
where
name_list:
charmap_name
charmap_name '+' name_list
charmap_name is a name of [CHARMAP]
define wich charmap(s) is to use.
examples:
[config default]
keymap default
[end config]
[config linux]
keymap default + linux
[end config]
[config default_koi8]
keymap default
keymap koi8u + koi8r : VK_/ RIGHT_ALT // russian keyboard
keymap koi8u : VK_. RIGHT_ALT // ukranian
charmap koi8-cp866
[end config]
[config linux_koi8]
keymap default + linux
keymap koi8u + koi8r : VK_/ RIGHT_ALT // russian keyboard
keymap koi8u : VK_. RIGHT_ALT // ukranian
charmap koi8-cp866 + koi8u-cp866
[end config]
so, for switch to russian keyboard just press RIGHT_ALT and '/'.
and, for switch back to default press it again.
@@ -0,0 +1,24 @@
**********************************************
*** Console Telnet 2.1 beta 2. Known Bugs ***
**********************************************
Wrap_Line = 0 Doesn't work very well. It works with elvis or talk on linux,
but messes up bash at last line.
Enable_Mouse=1 Causes the display to slow in fullscreen mode, since the
mouse has to be erased and then drawn again for every
screen write.
Term_Width or Term_Height != -1 or Wide_Enable=1
Specifying any of these can cause display problems if
the font size is not set to auto.
Resizing the current window while running telnet can cause problems, especially
if doing so makes the buffer smaller. This should be more of a problem on
NT/W2K than on 95/98. Part of the problem is that the telnet NAWS option
negotiation isn't done properly. On a related note, turning on scrollbars can
decrease performance.
There are many other bugs, most of which are documented in the code. Just
grep the source for "FIX ME".
@@ -0,0 +1,239 @@
**********************************************
*** Console Telnet version 2.1 Change log ***
**********************************************
Version 2.1b2 -- October 16, 2000
Redirection fix (Mark Miesfield)
Allow "o" to open a connecton on the command line
Fixed problem with special keys (ALt-[, Alt-], Alt-\, etc.)
Added MTE Support (Ziglio Frediano)
Speed improvements in ttelhndl.cpp -- may be buggy?
Wrap_line option is now modifiable via telnet command line
Lock_linewrap option added
Cleaned up console code
Fixed some color issues with nonstandard consoles
Tab setting/resetting
Fixed "telnet.exe" installer problem
Fixed miscellaneous parsing bugs
Fixed vt100-compliance
Added NAWS support, but it doesn't work (RFC 1073)
Added X Display Location support (RFC 1096)
Version 2.1b1 -- April 5, 2000
-Bugfixes
Console code writes to bottom of buffer (W2K scrollback buffer now works)
Updated Winsock error messages (Craig Nellist)
Sleeping while thread paused, to give up CPU time (Craig Nellist)
Ctrl_Break_as_C now works properly
Restore original screen colors; use initial screen colors as default
-New features
Cursor size sequences (Jose Cesar Otero Ridriguez)
Network piping
Line mode support added
Support for telnet:// URLs
Command-line history (Craig Nellist)
Connection Aliases
-Translator updates
New code structure
Unified character map class
More configurable "special" keys:
tn_escape, tn_scrollback, tn_dial, tn_paste, tn_null, tn_cr, tn_crlf
Transmission of NUL character possible
Czech keyboard definition (Jakub Sterba)
-New INI options
Window_Width, Window_Height
Scriptname (not functional), Script_Enable (not functional)
Netpipe (functional), Iopipe (not functional)
Version 2.0 -- July 5, 1999
-Bugfixes
Save/restore console title, character mapping fix (Pedro Gutierrez)
Telnet prompt fix, suspend telnet, string-based port (Craig Davidson)
Mutt/Lynx colors/underline fix, repeat character fix
Color display problem fixed (I.Ioannou)
Newline properly handled, added APP4_KEY, better key translation
Problem with icons not displaying properly fixed
Small bug with telnet crashing at exit (Sam Robertson, Daniel Straub)
Bug getting name of executable (Thomas Briggs)
-Updates
Better key translation
Spanish keyboard definition (Cesar Otero)
-New ini options
Set_Title (Adi Seiker)
Scroll_Enable/Scroll_Size
CtrlBreak_as_CtrlC (Bryan Montgomery)
Clear_on_Tabset removed
Version 2.0b7.1 -- Dec. 5, 1998
-Minor changes
Fixed problems with Scrollback and Clipboard
Minor updates to terminal emulation
Keyboard init improvements (Vassili Bourdo)
Repeat sequence support, German key config (Titus von Boxberg)
Version 2.0b7 -- Oct. 21, 1988
-To do still:
ZModem support
Update key translator/character maps
Finish scrollback
-Changes
Options added: Term_Width, Term_Height, Wide_Enable, Buffer_Size, Dial_key,
Keyboard_Paste, Status_bg, Status_fg, Input_Redir, Output_Redir
Application keypad mode support
Numlock/scroll lock support in KEYS.CFG
Del/. key now works properly
Ctrl-break bugfixes (Thomas Briggs)
Added suspend and fast quit to the command line (Thomas Briggs)
Error message for unable to load ini file (Thomas Briggs)
Fixed TELNET_INI environment variable (BK Oxley)
Support for changing screen size
Support for switching to 132-column mode via ANSI sequences
Fixed minor memory leaks
Mouse speedups/bugfixes, scrolling speedups/bugfixes
Miscellaneous ANSI parser fixes
Added support for changing the icon in the corner of the window
Fixed bug with mIRC
Fixed "try again" error message
Input and output redirection now separate (TELNET_REDIR still supported)
Modified "set" command to operate on groups
Character mapping now works again
Version 2.0b6 28 Jul 1998
-To Do still:
ZModem support
Finish mouse support
Fix character maps
-Changes:
ANSI Parser should be almost complete
Reorganized source
Display speedups
Preliminary mouse support
Enhanced scrollback support
Miscellaneous bug fixes
Version 2.0b5 05 Jun 1998
-Version 2b5 released from I.Ioannou <[email protected]>
-To Do Still:
Too many to mention :-)
-To Do, Maybe:
Mouse cut/paste support.
Support secure telnet options.
Real blinking attributes.
Zmodem & Kermit DL Protocols.
Any ideas acceptable :-)
May 1998
-Changes
Paul Brannan <[email protected]> add telnet.ini code
improve telnet's speed, add some VT emulation, port telnet to
MSVC, rewrote the command line options processing with GNU getopt,
fix many bugs, and more. Good work Paul :-)
I.Ioannou <[email protected]> . A few bugs fixes, and a icon.
Also I convert tnmsg files to use a resource compiler.
December 1997
-Changes
Andrey V. Smilianets ([email protected])
rewrote the keys translator to support many different
keymaps, charmaps and configurations.
Also add editing support to telnet> prompt.
Version 2.0b4 10/6/97
-Updated by Brad Johnson who can be contacted at
<[email protected]> http://nounname.com
-Changes
Added command line history at the telnet> prompt.
Added ability to "unmap" a key by setting it equal to \000 in the key.cfg.
Added log-file option '-dFILENAME'.
Added print screen/line commands by I.Ioannou <[email protected]>.
Added Support for running in an emacs buffer <[email protected]>.
Added better support for international character sets
<[email protected]>.
-To Do Still:
Support for local echo.
Scrollback buffer.
Fix Scrolling bug.
-To Do, Maybe:
Change the telnet options to initiate the negotiation.
Mouse cut/paste support.
Support secure telnet options.
Real blinking attributes.
Zmodem & Kermit DL Protocols.
Version 2.0b3 12/25/96:
-Updated by Brad Johnson who can be contacted at
<[email protected]> http://nounname.com
-Changes
Screen colors and buffer settings are now preserved on exit.
Fixed WindowSize height/width 255 exception :-).
Found out that the paste problem is a bug in Win 95 (not my problem)!
Fixed screen buffer problems under NT when the window
was smaller than the buffer.
Added custom key maps by I.Ioannou <[email protected]>.
-To Do Still:
Fix advance to next line error when writing past column
Extend NAWS window negotiation to include buffer size changes.
Change the telnet options to initiate the negotiation.
Add print screen/line commands.
-To Do, Maybe:
Support for running in an emacs buffer.
Mouse cut/paste support.
Support secure telnet options.
Real blinking attributes.
Zmodem & Kermit DL Protocols.
Version 2.0b2 09/29/96:
-Updated by Brad Johnson who can be contacted at
<[email protected]> http://nounname.com
-Changes
Added code to move cursor to end of screen and reset attributes on close
Fixed potential IAC parsing problem
Fixed ClearScreen Last line problem
Fixed parse problem that prevented line clears on unix history
Changed scroll code to scroll the entire buffer
Removed destructive backspace. May cause problems with terminals that want
destructive backspaces.
Added binary telnet option to use 8bit.
-To Do Next
Paste still doesn't work!
Version 2.0b1 09/22/96:
-Updated by Brad Johnson who can be contacted at
<[email protected]> http://nounname.com
-Changes
Added Color ANSI support. It works!
Added option for user specified port addresses on the command line.
Added ANSI keyboard mapping support for cursor keys.
Added destructive Backspace.
Added escape key 'ALT-]'.
Added TermType and WindowSize telnet options.
Added/Fixed various other ANSI codes.
Now (I hope) all ANSI codes handled correctly!
Fixed cursor left/right/save/restore commands.
Fixed clear line and clear screen command.
Expanded and altered network buffer to prevent some lockups :-).
Added Unix style telnet prompt "telnet>" with options.
-To Do Next
Should parse for IAC separate from ANSI.
Version 1.0a:
- This release fixes a bug which caused it to hang when connecting to
UNIX boxes. The program simply ignored Telnet DO instead of replying
with WON'T as required by RFC 854.
Version 1.0:
- First release
@@ -0,0 +1,340 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
675 Mass Ave, Cambridge, MA 02139, USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Library General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
Appendix: How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) 19yy <name of author>
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., 675 Mass Ave, Cambridge, MA 02139, USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) 19yy name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Library General
Public License instead of this License.
@@ -0,0 +1,187 @@
This file describes all the environment variables and options that are
available in TELNET.INI. If you are having problems with a terminal setting,
this is the file you want to read first. If this file does not help you,
please send a bug report to Paul Brannan <[email protected]>.
Environment variables
---------------------
Before there was a telnet.ini file, all the options were controlled
through environment variables. These have been left in for compatibility
with previous versions, and for specifying locations of files. They
override any values in telnet.ini.
TELNET_CFG Specifies the location of the keys.cfg file
TELNET_REDIR Specifies whether file redirection needs to be supported
INPUT_REDIR Specicies only to redirect input
OUTPUT_REDIR Specifies only to redirect output
TELNET_INI Specifies the location of the telnet.ini file
Configuration options
---------------------
These are the options that you can specify in telnet.ini. This file is in
the same format as any normal Windows ini file. You can also change some
of these options using the SET command at the telnet> prompt.
[Terminal] section
Dumpfile
Specifies the filename of a file to dump output to. (Default = "")
Term
The name of the terminal type to send to the server. You
can use this if Telnet is sending "ANSI" but you have a
vt100 terminal. If you use this options, please read about
some of the other options below. (Default = ansi)
EightBit_Ansi
Some machines use the ASCII characters 128 to 155 for ANSI
sequences. These are usually the newer VAX systems. Turning
this option on may cause problems with certain foreign
(non-American) character sets. (Default = FALSE)
VT100_Mode
This option turns on VT100 mode. There are a few minor
differences between ANSI terminals and DEC VT100 terminals.
I recommend trying TERM=vt220 or TERM=vt102 before trying
this option, but if you must have true VT100 emulation,
this is the only way to get it. (Default = FALSE)
Destructive_Backspace
This will probably cause problems with most programs, but if you need the
backspace to erase the previous character (as with some BBSes), use this
option. (Default = FALSE)
Speaker_Beep
If you set this to true you will hear beeps through the PC speaker; setting
it to false will play the default system beep sound through your sound
card. (Default = TRUE)
Beep
Setting this to false turns off all beeps; setting this to true turns on
all beeps. (Default = TRUE)
Preserve_Colors
This turns on color preservation for systems that require it (like SCO).
(Default = FALSE)
Wrap_line
This turns on/off line wrap. (Default = TRUE)
Lock_linewrap
Turning on this option disables the ability of the remote end to control
line wrap, and "locks" it into whatever it is set to in the ini file.
(Default = FALSE)
Fast_write
This turns on/off fast screen write. Turning it off allows you to see
control characters if your application requires it. (Default = TRUE)
Term_width
Term_height
These options specify the size of the terminal. You can specify non-standard
sizes if you are running telnet in a window. You may want to specify
a font size if you use these (using "Auto" can cause display problems).
Specifying -1 means use the settings for the parent console.
(Default = -1, -1)
Wide_enable
This is to allow the ANSI parser to change the screen size when sent certain
escape sequences. This is for vt100 compatibility. (Default = FALSE)
Buffer_size
This is the size of the ANSI buffer used for parsing sequences. Increasing
this value speeds up the parser, and decreasing it allows the mouse to
respond faster. (Default = 2048)
Input_redir
Output_redir
These are for redirecting input and output. (Default = 0, 0)
Any value greater than 0 turns redir on. Turn Output_redir on to bypass
the Console Telnet screen writing and positioning functions and simply
pass the data stream as received from the host straight through.
Strip_redir
If enabled, this option will attempt to strip the stream before passing it on
through redirected output. This will have no effect on non-redirected output.
(Default=FALSE)
[Colors] section
Setting the following to -1 disables them:
Blink_bg Background color to use for blink (default = -1)
Blink_fg Foreground color to use for blink (default = -1)
Underline_bg Background color to use for underline (default = -1)
Underline_fg Foreground color to use for underline (default = -1)
UlBlink_bg Background color to use for blink+uline (default = -1)
UlBlink_fg Foreground color to use for blink+uline (default = -1)
Setting the following to -1 uses colors detected at startup:
Normal_bg Normal text background color (default = -1)
Normal_fg Normal text foreground color (default = -1)
Please do not set these values to -1:
Scroll_bg Background color for scrollback mode (default = 0)
Scroll_fg Foreground color for scrollback mode (default = 7)
Status_bg Bg color of status line in scrollback (default = 1)
Status_fg Fg color of status line in scrollback (default = 15)
Here's a list of colors:
0 - black, 1 - blue, 2 - green, 3 - cyan, 4 - red, 5 - magenta, 6 - brown
7 - lt. grey (dk. white), 8 - dk. grey, 9 - bright blue, 10 - bright green,
11 - bright cyan, 12 - bright red, 13 - bright magenta, 14 - yellow
15 - bright white
[Mouse] section
Enable_Mouse
Turns on mouse support. (Default = TRUE)
[Printer] section
Printer_Name
The DOS name for the printer. (Default = LPT1)
[Keyboard] section
Many of these options are also available from telnet.cfg.
Escape_key
The key to break out of a telnet session. (Default = ])
Scrollback_key
The key for switching to scrollback mode. (Default = [)
Dial_key
You can start a new telnet session with this key. (Default = \)
Alt_erase
If you set this to true, it will swap backspace and delete.
(Default = FALSE)
Keyboard_paste
This option allows pasting to the screen via shift-insert. (Default = FALSE)
Keyfile
Selects an alternate telnet.cfg file. (Default = TELNET.CFG)
Default_Config
Selects a different keyboard definition. All of these are defined in
telnet.cfg.
[Scrollback] section
Scroll_Mode
Selects the default mode for scrollback. Valid selections are:
HEX Hex dump
DUMP Dump, control characters are shown as "."
DUMPB Binary dump
TEXT Text mode
Note: you can press TAB in scrollback mode to cycle through these.
(Default = DUMP)
Command-line Options
--------------------
-d<filename> Specifies the name of the dumpfile.
-h Gives a help screen.
@@ -0,0 +1,280 @@
**************************************************
** Console Telnet v2.1b2 README.TXT 16 Oct 2000 **
**************************************************
RELEASE NOTES:
--------------
This release of TELNET is a beta one. This means that it is working as far
as it is tested, and has a few bugs. Hopefully this will be a stable
version. Please send comments and bug reports to me at
[email protected], or to the mailing list (see below). See file
CHANGES.TXT for a detailed log of changes. See file BUGS.TXT for known
bugs.
DESCRIPTION:
------------
This is a telnet client with full color ANSI support for Windows NT/95
console. You can use this program from the Win95 command line (MsDos) and
run it in full screen text mode. You may also redirect the telnet session
to STDIN and STDOUT for use with other programs. Telnet will communicate
the number of lines and rows to the host, and can operate in any console
mode. Most of it's options are customizable.
COPYRIGHT/LICENSE/WARRANTY
--------------------------
Telnet Win32, Copyright (C) 1996-1997, Brad Johnson <[email protected]>
Copyright (C) 1998 I.Ioannou, Copyright (C) 1999-2000 Paul Brannan. Telnet
is a free project released under the GNU public license. This program comes
with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome
to redistribute it under the licence contitions. See LICENSE.TXT for
details.
REQUIREMENTS:
-------------
This program requires a Microsoft Win32 enviroment (Windows 95/98/NT) with
Winsock TCP/IP. 16 bit Win3.x or Win32s are not supported.
FEATURES:
---------
Full ANSI colors and (almost) complete ANSI emulation.
User configurable options via telnet.ini.
User configurable key bindings with alternative keyboards.
Icoming character translations.
Redirection of telnet session.
Telnet output can be dumped to a file.
Local printer support.
Basic scrollback support.
Basic VT emulation.
Mouse support.
Clipboard (cut-and-paste) support.
Support for multiple screen sizes.
WHERE TO GET IT:
----------------
Since version 2.0, Console Telnet's new home page is
http://www.musc.edu/~brannanp/telnet/. You can get the latest version from
ftp://argeas.cs-net.gr/Telnet-Win32 or from the web page. Telnet is
available as full project (sources included) or as binaries only. If you
would like to help to the development check the /devel directory on the ftp
site for a recent alpha version.
MAILING LIST:
-------------
Telnet has it's own mailing list for announcements, bug reports, support,
suggestions etc. To subscribe send e-mail to [email protected]
with empty Subject, and the word subscribe in the body. List's address is
[email protected] You can find the old archives at
http://www.cs-net.gr/lists
If you are only interested in announcements, follow the above procedures to
subscribe to telnet-win32-announce. The development list is
telnet-win32-devel.
HOW TO HELP:
------------
Telnet is a free project made from volunteers. If you know C/C++ and would
like to help in the development you are welcome :-) Just contact
[email protected], and/or subscribe to the mailing list. Check
ftp://argeas.cs-net.gr/Telnet-Win32/devel for a recent alpha version.
INSTALLATION
------------
Just copy telnet.exe, telnet.ico, telnet.ini and keys.cfg to a directory.
I prefer a directory included in the PATH (such as C:\WINDOWS, but this will
overwrite the telnet that comes with Windows -- which is not necessarily a
bad thing). If you are upgrading from a previous version please look below
(Key file definitions) : the keys.cfg file has changed a bit. Also look at
the Configuration section below, TELNET now has a ini file.
USAGE:
-------
TELNET
Begins telnet and enters telnet> command line.
TELNET [params][host [port]]
Connects to port on host. Port defaults to 23 for TELNET.
params -d FILENAME.EXT Dumps all incoming data to FILENAME.EXT
Note lowercase 'd'.
--variable=value Overrides ini variable to be set to value.
host Host name or IP to connect to
port Service port to open connection on
(default is telnet port 23).
TELNET -?
Gives usage information.
Pressing the escape key (default ALT-]) will break out of a telnet session and
return you to the telnet> prompt. Pressing return will resume your session.
All the options are available from the telnet> prompt. Type ? to get help.
Pressing the scrollback key (default ALT-[) will give you a basic scrollback
view. Pressing ESC will resume your session.
BUGS:
-----
There are :-). Hopefully this version is more stable than the previous. See
BUGS.TXT, and grep for FIX ME's in the sources. Any help ?
NOTES:
------
If the environment variable LANG has a valid value (e.g. LANG=de for German
characters) and the file LOCALE.DLL is installed somewhere along the PATH
TELNET will not ignore local characters.
If you have problems with paste under Win 95 try unchecking the fast paste
option in the MsDos properties. The paste function works correctly under NT.
This is a Microsoft bug :-)
CONFIGURATION
-------------
The configuration is made through telnet.ini and keys.cfg. These files (at
least telnet.ini) must be in the same directory which telnet.exe is. The
basic options are loaded from the file telnet.ini. If you are having problems
with a terminal setting, check the file OPTIONS.TXT for configuration
information.
Key file definitions (telnet.cfg)
-------------------------------
Use the key file (telnet.cfg) to define the characters that telnet is sending
to the host. From version 2b5 you can configure the output keys (KEYMAP
sections), the input character translations (CHARMAP sections) and you can
combine all to as many configurations as you like (CONFIG sections). You
can also have alternative keymaps in a configuration, and keys to switch
between them. See the comments in keys.cfg for details.
NOTE: if you are upgrading from a previous version you must put your old keys
in the KEYMAP sections.
Please send any national specific keymaps / charmaps / configurations to be
included to the next version.
HOW TO COMPILE IT
-------------------
Telnet compiles with a variety of compilers. You will need at least
Borland 4.x or newer compiler, or MSVC 2.0 or newer, or download a version
of gcc for Win32 (see http://www.musc.edu/~brannanp/telnet/gccwin32.html).
Copy the files from the directories BORLAND or MSVC to the main directory,
change them to fit to your system, and recompile. The project comes with
IDE files and makefiles.
Follow the instructions for your compiler to compile telnet. A Makefile
for use with mingw32 or other gcc variants has been included, so if you have
gcc, you can just type "make" at the command line.
SPECIAL THANKS:
---------------
Many people have worked for this project. Please forgive me (and let me
know!) if I have forgotten anyone. We all thank them :-)
Igor Milavec <[email protected]>
Original Author of version 1.1
Igor wrote the basic telnet program and released it to public.
Brad Johnson <[email protected]> http://nounname.com
Author of versions 2.0b to 2b4. Brad has wrote plenty of code for
telnet like ansi colors, emulation, scrollback option, and many
others.
[email protected]
Ansi emulation improvements
German keyboard configuration
I.Ioannou [email protected]
KeyTranslator class (version 2b3)
Maintainer (since version 2b5)
Andrei V. Smilianets <[email protected]> (version 2b5)
KeyTranslator class (version 2b5)
Prompt improvments
Paul Brannan <[email protected]>
Telnet.ini author, MSVC port, speed improvements, VT support,
and many others.
Maintainer (since version 2b6)
Leo Leibovici <[email protected]>
Fixed some crashes in the ANSI parser
Wrote UK keymap
Dmitry Lapenkov <[email protected]>
Wrote AT386 keymaps
Improved telnet icon
Thomas Briggs <[email protected]>
Fixed problem with Ctrl-Break
Added suspend and fast quit options to the command line
Error messages for unable to load ini file
Fixed bug w/ getting name of executable
BK Oxley
Fixed TELNET_INI environment variable
Sam Robertson
Fixed compilation problems with MSVC6
Bugfix with telnet crashing at exit
Vassili Bourdo <[email protected]>
Keyboard initialization improvements
Craig Davidson <[email protected]>
Bugfixes for telnet prompt
Added suspend telnet option
Set port number using name rather than number
Pedro Gutierrez <[email protected]>
Save/restore console title
Bugfix w/ character mapping
Daniel Straub <[email protected]>
Bugfix with telnet crashing at exit
Jose Cesar Otero Rodriguez <[email protected]>
Spanish Keyboard definition
Cursor size sequences
Bryan Montgomery <[email protected]>
Added CtrlBreak_as_CtrlC option
Added Scroll_Enable option
Adi Seiker
Added Set_Title ini file option
Craig Nellist
Updated Winsock error messages
Sleeping while thread paused, to give up CPU time
Command-line history
Jakub Sterba
Czech keyboard definition
Ziglio Frediano
MTE (Meridian Terminal) Support
Mark Miesfield
Fixed redirection
Wrote documentation for redirection
---
Paul Brannan <[email protected]>
@@ -0,0 +1,22 @@
It should be possible to add ssh support to console telnet, as console telnet has a very modular design when it comes to the networking code. There is already support for pipes, and if there exists an ssh client for Win32 that will output to stdout, then you're in business. I'm yet to find such a client, but if one existed, an SSH session could be started like so:
C:\> telnet
Copyright message, license.txt, stuff, etc.
telnet> set io_netpipe "C:\BIN\SSH.EXE -l username host"
telnet> open blah
login:
password:
Unfortunately, all the ssh clients I've found don't work this way. You can output CMD.EXE to telnet this way, though, and get a very pretty ansi interpreter. If you want to try to get OpenSSH working, here's step-by-step instructions to get you started (please read them all the way though):
1) Get Perl from http://www.activestate.com/ActivePerl/download.htm
2) Get Openssl from http://www.openssl.org/source/
- Follow directions in INSTALL.W32
- Copy the .LIB files from OUT32DLL to your LIB directory (C:\DevStudio\VC\LIB)
- Copy the .DLL files from OUT32DLLto your system directory (C:\Winnt\System32 or C:\Windows\System)
- Copy the .H files from INC32\OPENSSL to your include\ssl (C:\DevStudio\VC\include\ssl)
- Copy these same files to include\openssl (C:\DevStudio\VC\include\openssl)
3) Get Openssh from http://www.openssh.com
4) Modify Openssh so it will compile, and get rid of all the termios stuff
Obviously this is a lot of work. If you need a good ssh client, try PuTTY from http://www.chiark.greenend.org.uk/~sgtatham/putty/. It may be possible to integrate PuTTY and Telnet, and that would certainly be easier than the above option. PuTTY is licensed under the MIT license, which seems to be compatible with the GPL. The primary advantage of integrating the two projects is that PuTTY would gain the key mappings that telnet has, and telnet would gain encryption.
@@ -0,0 +1,108 @@
//{{NO_DEPENDENCIES}}
// Microsoft Developer Studio generated include file.
// Used by Tnmsg.rc
//
#define MSG_COPYRIGHT 0x01
#define MSG_COPYRIGHT_1 0x02
#define MSG_USAGE 0x03
#define MSG_USAGE_1 0x04
#define MSG_HELP 0x05
#define MSG_HELP_1 0x06
#define MSG_INVCMD 0x07
#define MSG_ERROR 0x08
#define MSG_INFO 0x09
#define MSG_WARNING 0x0a
#define MSG_TRYING 0x0b
#define MSG_CONNECTED 0x0c
#define MSG_TERMBYREM 0x0d
#define MSG_KEYMAP 0x0e
#define MSG_ERRKEYMAP 0x0f
#define MSG_DUMPFILE 0x10
#define MSG_CONFIG 0x11
#define MSG_NOINI 0x12
#define MSG_BADVAL 0x13
#define MSG_NOSPAWN 0x14
#define MSG_RESOLVING 0x15
#define MSG_NOSERVICE 0x16
#define MSG_SIZEALIAS 0x17
#define MSG_ERRPIPE 0x18
#define MSG_BADUSAGE 0x19
#define MSG_ALREADYCONNECTED 0x1a
#define MSG_KEYNOVAL 1001
#define MSG_KEYBADVAL 1002
#define MSG_KEYBADSTRUCT 1003
#define MSG_KEYBADCHARS 1004
#define MSG_KEYUNEXPLINE 1005
#define MSG_KEYUNEXPEOF 1006
#define MSG_KEYUNEXPTOK 1007
#define MSG_KEYUNEXPTOKIN 1008
#define MSG_KEYUNEXP 1009
#define MSG_KEYNOGLOBAL 1010
#define MSG_KEYNOCONFIG 1011
#define MSG_KEYUSECONFIG 1012
#define MSG_KEYNOSWKEY 1013
#define MSG_KEYCANNOTDEF 1014
#define MSG_KEYDUPSWKEY 1015
#define MSG_KEYUNKNOWNMAP 1016
#define MSG_KEYNOCHARMAPS 1017
#define MSG_KEYNOKEYMAPS 1018
#define MSG_KEYNUMMAPS 1019
#define MSG_KEYBADMAP 1020
#define MSG_KEYMAPSWITCHED 1021
#define MSG_WSAEINTR 0x2714
#define MSG_WSAEBADF 0x2719
#define MSG_WSAEACCESS 0x271D
#define MSG_WSAEDEFAULT 0x271E
#define MSG_WSAEINVAL 0x2726
#define MSG_WSAEMFILE 0x2728
#define MSG_WSAEWOULDBLOCK 0x2733
#define MSG_WSAEINPROGRESS 0x2734
#define MSG_WSAEALREADY 0x2735
#define MSG_WSAENOTSOCK 0x2736
#define MSG_WSAEDESTADDRREQ 0x2737
#define MSG_WSAEMSGSIZE 0x2738
#define MSG_WSAEPROTOTYPE 0x2739
#define MSG_WSAENOPROTOOPT 0x273A
#define MSG_WSAEPROTONOTSUPPORT 0x273B
#define MSG_WSAESOCKNOTSUPPORT 0x273C
#define MSG_WSAEOPNOTSUPP 0x273D
#define MSG_WSAEPFNOTSUPPORT 0x273E
#define MSG_WSAEAFNOTSUPPORT 0x273F
#define MSG_WSAEADDRINUSE 0x2740
#define MSG_WSAEADDRNOTAVAIL 0x2741
#define MSG_WSAENETDOWN 0x2742
#define MSG_WSAENETUNREACH 0x2743
#define MSG_WSAENETRESET 0x2744
#define MSG_WSAECONNABORTED 0x2745
#define MSG_WSAECONNRESET 0x2746
#define MSG_WSAENOBUFS 0x2747
#define MSG_WSAEISCONN 0x2748
#define MSG_WSAENOTCONN 0x2749
#define MSG_WSAESHUTDOWN 0x274A
#define MSG_WSAETOOMANYREFS 0x274B
#define MSG_WSAETIMEDOUT 0x274C
#define MSG_WSAECONNREFUSED 0x274D
#define MSG_WSAELOOP 0x274E
#define MSG_WSAENAMETOOLONG 0x274F
#define MSG_WSAEHOSTDOWN 0x2750
#define MSG_WSAEHOSTUNREACH 0x2751
#define MSG_WSAESYSNOTREADY 0x276B
#define MSG_WSAVERNOTSUPPORTED 0x276C
#define MSG_WSANOTINITIALISED 0x276D
#define MSG_WSAHOST_NOT_FOUND 0x2AF9
#define MSG_WSATRY_AGAIN 0x2AFA
#define MSG_WSANO_RECOVERY 0x2AFB
#define MSG_WSANO_DATA 0x2AFC
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 101
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1000
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
@@ -0,0 +1,107 @@
#include "tnmsg.h"
LANGUAGE 0,0
// String Table
STRINGTABLE DISCARDABLE
BEGIN
MSG_COPYRIGHT "Telnet Win32 v2.1b2, Copyright (C) 2000 Paul Brannan <[email protected]>\nand the team. This program comes with ABSOLUTELY NO WARRANTY; for details\nread LICENSE.TXT. "
MSG_COPYRIGHT_1 "This is free software, and you are welcome to redistribute\nit under certain conditions.\n\n"
MSG_USAGE "Usage: TELNET [params][host [port]]\n\n params\n -d:FILENAME.EXT Dumps all incoming data to FILENAME.EXT.\n host Host name or IP address of the remote host to connect to.\n"
MSG_USAGE_1 " port Service port to open (default is telnet port 23).\n\n"
MSG_HELP "Commands may be abbreviated. Commands are:\n \ncl[ose] close current connection\nop[en] connect to a site\nq[uit] exit telnet\n"
MSG_HELP_1 "ke[ys] changes/displays keymaps (write keys to see the options)\nse[t] displays/alters configuration options\nz suspend\n? h[elp] print help information\n"
MSG_INVCMD "Invalid command. Type ? for help.\n"
MSG_ERROR "%1 failed.\n"
MSG_INFO "%1\n"
MSG_WARNING "%1\n"
MSG_TRYING "Trying %1.%2.%3.%4:%5...\n"
MSG_CONNECTED "Connected to %1. Escape key is ALT-%2.\n"
MSG_TERMBYREM "Connection terminated.\n"
MSG_KEYMAP "Loading %1 from %2.\n"
MSG_ERRKEYMAP "Error loading keymap.\n"
MSG_DUMPFILE "Writing output to file %1.\n"
MSG_CONFIG "Loading configuration options from %1.\n"
MSG_NOINI "Error loading configuration file %1.\nLoading default options.\n"
MSG_BADVAL "Warning: invalid variable %1.\n"
MSG_NOSPAWN "Unable to spawn process.\n"
MSG_RESOLVING "Looking up host: %1..."
MSG_NOSERVICE "Could not find TCP service %1.\n"
MSG_SIZEALIAS "Warning: size of alias %1 is too big, ignoring.\n"
MSG_ERRPIPE "Error: unable to spawn process for pipe.\n"
MSG_BADUSAGE "Error: invalid usage of command.\n"
MSG_ALREADYCONNECTED "Already connected to %1.\n"
MSG_WSAEINTR "Interrupted function call.\n"
MSG_WSAEBADF "WSAEBADF\n"
MSG_WSAEACCESS "Permission denied.\n"
MSG_WSAEDEFAULT "WSAEDEFAULT\n"
MSG_WSAEINVAL "Invalid argument.\n"
MSG_WSAEMFILE "Too many open files.\n"
MSG_WSAEWOULDBLOCK "Resource temporalily unavailable.\n"
MSG_WSAEINPROGRESS "Operation now in progress.\n"
MSG_WSAEALREADY "Operation already in progress.\n"
MSG_WSAENOTSOCK "Socket operation on non-socket.\n"
MSG_WSAEDESTADDRREQ "Destination address required.\n"
MSG_WSAEMSGSIZE "Message too long.\n"
MSG_WSAEPROTOTYPE "Protocol wrong type for socket.\n"
MSG_WSAENOPROTOOPT "Bad protocol option.\n"
MSG_WSAEPROTONOTSUPPORT "Protocol not supported.\n"
MSG_WSAESOCKNOTSUPPORT "Socket type not supported.\n"
MSG_WSAEOPNOTSUPP "Operation not supported.\n"
MSG_WSAEPFNOTSUPPORT "Protocol family not supported.\n"
MSG_WSAEAFNOTSUPPORT "Address family not supported by protocol family.\n"
MSG_WSAEADDRINUSE "Address already in use.\n"
MSG_WSAEADDRNOTAVAIL "Cannot assign requested address.\n"
MSG_WSAENETDOWN "Network is down.\n"
MSG_WSAENETUNREACH "Network is unreachable.\n"
MSG_WSAENETRESET "Network dropped connection on reset.\n"
MSG_WSAECONNABORTED "Software caused connection abort.\n"
MSG_WSAECONNRESET "Connection reset by peer.\n"
MSG_WSAENOBUFS "No buffer space available.\n"
MSG_WSAEISCONN "Socket is already connected.\n"
MSG_WSAENOTCONN "Socket is not connected.\n"
MSG_WSAESHUTDOWN "Cannot send after socket shutdown.\n"
MSG_WSAETOOMANYREFS "WSAETOOMANYREFS\n"
MSG_WSAETIMEDOUT "Connection timed out.\n"
MSG_WSAECONNREFUSED "Connection refused.\n"
MSG_WSAELOOP "WSAELOOP\n"
MSG_WSAENAMETOOLONG "Name too long.\n"
MSG_WSAEHOSTDOWN "Host is down.\n"
MSG_WSAEHOSTUNREACH "No route to host.\n"
MSG_WSAESYSNOTREADY "Network subsystem is unavailable.\n"
MSG_WSAVERNOTSUPPORTED "WINSOCK.DLL version out of range.\n"
MSG_WSANOTINITIALISED "Successful WSAStartup not yet performed.\n"
MSG_WSAHOST_NOT_FOUND "Host not found.\n"
MSG_WSATRY_AGAIN "Non-authoritative host not found.\n"
MSG_WSANO_RECOVERY "This is a non-recoverable error.\n"
MSG_WSANO_DATA "Valid name, no data record of requested type.\n"
MSG_KEYNOVAL "[GLOBAL]: No value for %1.\n"
MSG_KEYBADVAL "[GLOBAL]: Bad value for %1.\n"
MSG_KEYBADSTRUCT "%1: Bad structure.\n"
MSG_KEYBADCHARS "%1: Bad chars? %1 -> %3.\n"
MSG_KEYUNEXPLINE "Unexpected line ""%1"".\n"
MSG_KEYUNEXPEOF "Unexpended end of file.\n"
MSG_KEYUNEXPTOK "Unexpected token %1.\n"
MSG_KEYUNEXPTOKIN "Unexpected token in %1.\n"
MSG_KEYUNEXP "Unexpected end of file or token.\n"
MSG_KEYNOGLOBAL "No [GLOBAL] definition!\n"
MSG_KEYNOCONFIG "No [CONFIG %1].\n"
MSG_KEYUSECONFIG "Use configuration: %1.\n"
MSG_KEYNOSWKEY "No switch key for ""%1"".\n"
MSG_KEYCANNOTDEF "You cannot define switch key for default keymap - ignored.\n"
MSG_KEYDUPSWKEY "Duplicate switching key.\n"
MSG_KEYUNKNOWNMAP "Unknown keymap %1.\n"
MSG_KEYNOCHARMAPS "No charmaps loaded.\n"
MSG_KEYNOKEYMAPS "No keymaps loaded.\n"
MSG_KEYNUMMAPS "There are %1 maps.\n"
MSG_KEYBADMAP "Bad keymap number - try 'keys display'\n"
MSG_KEYMAPSWITCHED "keymap switched.\n"
END
#if defined(__MINGW32__) || defined(__CYGWIN__)
TelnetIcon ICON "telnet.ico"
#else
TelnetIcon ICON "../telnet.ico"
#endif
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,85 @@
#ifndef __ANSIPRSR_H
#define __ANSIPRSR_H
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include "tnconfig.h"
#include "tparser.h"
// added this color table to make things go faster (Paul Branann 5/8/98)
enum Colors {BLACK=0, BLUE, GREEN, CYAN, RED, MAGENTA, YELLOW, WHITE};
extern const int ANSIColors[];
// This should be greater than the largest conceivable window size
// 200 should suffice
#define MAX_TAB_POSITIONS 200
// Added by Frediano Ziglio 6/2/2000
// Include Meridian Emulator support
// undefine it to remove support
#define MTE_SUPPORT 1
// TANSIParser is now properly no longer a base class for TTelnetParser.
// Screen output is handled in TConsole.cpp.
// (Paul Brannan 6/15/98)
class TANSIParser : public TParser {
private:
char* ParseEscapeANSI(char* pszBuffer, char* pszBufferEnd);
char* ParseANSIBuffer(char* pszBuffer, char* pszBufferEnd);
char* ParseEscape(char* pszBuffer, char* pszBufferEnd);
// Added by I.Ioannou 06/04/97
char* PrintBuffer(char* pszBuffer, char* pszBufferEnd);
char* PrintGoodChars(char * pszHead, char * pszTail);
#ifdef MTE_SUPPORT
// Added by Frediano Ziglio, 5/31/2000
char* ParseEscapeMTE(char* pszBuffer, char* pszBufferEnd);
short int mteRegionXF,mteRegionYF;
#endif
void ConSetAttribute(unsigned char wAttr);
const char *GetTerminalID();
void ConSetCursorPos(int x, int y);
void ResetTerminal();
void Init();
void SaveCurX(int iX);
void SaveCurY(int iY);
void resetTabStops();
int iSavedCurX;
int iSavedCurY;
unsigned char iSavedAttributes;
FILE * dumpfile;
// Added by I.Ioannou 06 April 1997
FILE * printfile;
char InPrintMode;
int inGraphMode;
char last_char; // TITUS++: 2. November 98
char map_G0, map_G1;
int current_map;
bool vt52_mode;
bool print_ctrl;
bool ignore_margins;
bool fast_write;
bool newline_mode;
int tab_stops[MAX_TAB_POSITIONS];
public:
// Changed by Paul Brannan 5/13/98
TANSIParser(TConsole &Console, KeyTranslator &RefKeyTrans,
TScroller &RefScroller, TNetwork &NetHandler, TCharmap &RefCharmap);
~TANSIParser();
char* ParseBuffer(char* pszBuffer, char* pszBufferEnd);
static int StripBuffer(char* pszBuffer, char* pszBufferEnd, int width);
};
#endif
@@ -0,0 +1,227 @@
///////////////////////////////////////////////////////////////////////////////
//Telnet Win32 : an ANSI telnet client.
//Copyright (C) 1998-2000 Paul Brannan
//Copyright (C) 1998 I.Ioannou
//Copyright (C) 1997 Brad Johnson
//
//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., 675 Mass Ave, Cambridge, MA 02139, USA.
//
//I.Ioannou
//[email protected]
//
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
// Key translations - I.Ioannou ([email protected]) //
// Athens - Greece December 18, 1996 02:56am //
// Reads a .cfg file and keeps the definitions //
// modified for alternate keymap swiching //
// by Andrey V. Smilianets ([email protected]) //
// Kiev - Ukraine, December 1997. //
// modified to work with MSVC and the Standard Template //
// library by Paul Brannan <[email protected]>, //
// May 25, 1998 //
// updated June 7, 1998 by Paul Brannan to remove cout and //
// cerr statements //
// APP_KEY and APP2_Key added July 12, 1998 by Paul Brannan //
///////////////////////////////////////////////////////////////////
// class KeyTranslator //
// Load : loads or replaces the keymap //
// TranslateKey : returns a char * to the key def //
// AddKeyDef : Changes or adds the key translation //
// DeleteKeyDef : Deletes a key def from the list //
///////////////////////////////////////////////////////////////////
#include <windows.h>
// changed to make work with VC++ (Paul Brannan 5/25/98)
// FIX ME !!! Ioannou: This must be __BORLANDC__ && VERSION < 5
// but what is the directive for Borland version ????
// FIXED Sept. 31, 2000 (Bernard Badger)
//
#if defined(__BORLANDC__) && (__BORLANDC < 0x0500)
#include <mem.h>
#else
#include <memory.h>
#endif
#include "keytrans.h"
#include "tnerror.h"
/////////////////////////////////////////////////////////////
// class KeyTranslator //
// Load : loads or replaces the keymap //
// TranslateKey : returns a sz to the key def //
// AddKeyDef : Changes or adds the key translation //
// DeleteKeyDef : Deletes a key def from the list //
/////////////////////////////////////////////////////////////
KeyTranslator::KeyTranslator():
mapArray(0,0,sizeof(KeyMap)),
globals(0,0,sizeof(TKeyDef)) {
ext_mode = 0; // Paul Brannan 8/28/98
currentKeyMap = mainKeyMap = -1;
};
//AVS
// perform keymap switching
int KeyTranslator::switchMap(TKeyDef& tk) {
if ( mapArray.IsEmpty() ) {
return currentKeyMap = -1;
};
int i = mapArray.Find(KeyMap(tk));
if ( i != INT_MAX ) {
if (currentKeyMap == i)
currentKeyMap = mainKeyMap; // restore to default
else currentKeyMap = i;
return 1;
};
return 0;
};
// Let the calling function interpret the error code (Paul Brannan 12/17/98)
int KeyTranslator::SwitchTo(int to) {
int max = mapArray.GetItemsInContainer();
if (max == 0) return -1;
if (to < 0 || to > (max-1)) return 0;
currentKeyMap = to;
return 1;
};
//AVS
// rewrited to support multiple keymaps
const char *KeyTranslator::TranslateKey(WORD wVirtualKeyCode,
DWORD dwControlKeyState)
{
if ( mapArray.IsEmpty() ) return NULL;
TKeyDef ask(NULL, dwControlKeyState, wVirtualKeyCode);
// if a keymap switch pressed
if ( switchMap(ask) > 0 ) return "";
int i = mapArray[currentKeyMap].map.Find(ask);
if ( i != INT_MAX) return mapArray[currentKeyMap].map[i].GetszKey();
// if not found in current keymap
if ( currentKeyMap != mainKeyMap ) {
i = mapArray[mainKeyMap].map.Find(ask);
if ( i != INT_MAX) return mapArray[mainKeyMap].map[i].GetszKey();
};
return NULL;
};
//AVS
// rewrited to support multiple keymaps
int KeyTranslator::AddKeyDef(WORD wVirtualKeyCode, DWORD dwControlKeyState,
char*lpzKeyDef)
{
if ( ! mapArray[currentKeyMap].map.IsEmpty() ) {
int i = mapArray[currentKeyMap].map.Find(TKeyDef(NULL, dwControlKeyState, wVirtualKeyCode));
if ( i != INT_MAX) {
mapArray[currentKeyMap].map[i] = lpzKeyDef;
return 1;
}
};
return mapArray[currentKeyMap].map.Add( TKeyDef(lpzKeyDef, dwControlKeyState, wVirtualKeyCode));
}
// Paul Brannan Feb. 22, 1999
int KeyTranslator::AddKeyDef(WORD wVirtualKeyCode, DWORD dwControlKeyState,
tn_ops the_op)
{
optype op;
op.sendstr = 0;
op.the_op = the_op;
if ( ! mapArray[currentKeyMap].map.IsEmpty() ) {
int i = mapArray[currentKeyMap].map.Find(TKeyDef(NULL, dwControlKeyState, wVirtualKeyCode));
if ( i != INT_MAX) {
mapArray[currentKeyMap].map[i] = op;
return 1;
}
};
return mapArray[currentKeyMap].map.Add( TKeyDef(op, dwControlKeyState, wVirtualKeyCode));
}
// AVS
int KeyTranslator::LookOnGlobal(char* vkey) {
if ( ! globals.IsEmpty() ) {
int max = globals.GetItemsInContainer();
for ( int i = 0; i < max ; i++ )
if ( stricmp(globals[i].GetszKey(), vkey) == 0 )
return i;
};
return INT_MAX;
};
int KeyTranslator::AddGlobalDef(WORD wVirtualKeyCode, char*lpzKeyDef) {
if ( ! globals.IsEmpty() ) {
int max = globals.GetItemsInContainer();
for ( int i = 0; i < max ; i++ ) {
const char *s = globals[i].GetszKey();
if ( stricmp(s, lpzKeyDef) == 0 ) {
globals[i] = DWORD(wVirtualKeyCode);
return 1;
}
}
}
return globals.Add( TKeyDef(lpzKeyDef, 0, wVirtualKeyCode));
}
//AVS
// rewrited to support multiple keymaps
int KeyTranslator::DeleteKeyDef(WORD wVirtualKeyCode, DWORD dwControlKeyState)
{
if ( mapArray.IsEmpty() || mapArray[currentKeyMap].map.IsEmpty() )
return 0;
int i = mapArray[currentKeyMap].map.Find(TKeyDef(NULL, dwControlKeyState, wVirtualKeyCode));
if ( i != INT_MAX) {
mapArray[currentKeyMap].map.Destroy(i);
return 1;
};
return 0;
};
//AVS
// rewritten to support multiple keymaps
void KeyTranslator::DeleteAllDefs(void)
{
// This code wants to crash under the STL; Apparently the Destroy()
// function actually deletes the entry, rather than simply releasing
// memory. I think flush() should do the same thing, at least the
// way it is written with STL_BIDS (Paul Brannan 5/25/98).
int max;
max = mapArray.GetItemsInContainer();
if ( ! mapArray.IsEmpty() ) {
for ( int i = 0; i < max; i++ ) {
if ( !mapArray[i].map.IsEmpty() ) {
mapArray[i].map.Flush();
};
};
};
globals.Flush();
mapArray.Flush();
currentKeyMap = -1;
mainKeyMap = -1;
};
@@ -0,0 +1,97 @@
///////////////////////////////////////////////////////////////////
// //
// //
// Key translations - I.Ioannou ([email protected]) //
// Athens - Greece December 18, 1996 02:56am //
// Reads a .cfg file and keeps the key definitions //
// for the WIN32 console telnet //
// modified for alternate keymap swiching //
// by Andrey V. Smilianets ([email protected]) //
// Kiev - Ukraine, December 1997. //
///////////////////////////////////////////////////////////////////
// //
// class KeyTranslator //
// //
// Load : loads or replaces the keymap //
// TranslateKey : returns a char * to the key def //
// AddKeyDef : Changes or adds the key translation //
// DeleteKeyDef : Deletes a key def from the list //
///////////////////////////////////////////////////////////////////
#ifndef __KEYTRANS_H
#define __KEYTRANS_H
#include "tkeydef.h"
#include "tkeymap.h"
#define TOKEN_DELIMITERS " +\t" // The word's delimiters
// Ioannou 2 June 98: Borland needs them - quick hack
#ifdef __BORLANDC__
#define bool BOOL
#define true TRUE
#define false FALSE
#endif // __BORLANDC__
// Maybe not portable, but this is for application cursor mode
// (Paul Brannan 5/27/98)
// Updated for correct precedence in tncon.cpp (Paul Brannan 12/9/98)
#define APP4_KEY 0x8000
#define APP3_KEY 0x4000
#define APP2_KEY 0x2000
#define APP_KEY 0x1000
/////////////////////////////////////////////////////////////
// class KeyTranslator //
// Load : loads or replaces the keymap //
// TranslateKey : returns a sz to the key def //
// AddKeyDef : Changes or adds the key translation //
// DeleteKeyDef : Deletes a key def from the list //
/////////////////////////////////////////////////////////////
class KeyTranslator {
friend class TMapLoader; // FIX ME!! This isn't the best solution
public:
KeyTranslator();
~KeyTranslator() { DeleteAllDefs(); }
int SwitchTo(int); // switch to selected keymap
int switchMap(TKeyDef& tk);
// Returns a pointer to the string that should be printed.
// Should return NULL if there is no translation for the key.
const char *TranslateKey(WORD wVirtualKeyCode, DWORD dwControlKeyState);
// Changes or adds the key translation associated with
// wVirtualScanCode and dwControlKeyState.
// Return 1 on success.
int AddKeyDef(WORD wVirtualKeyCode, DWORD dwControlKeyState, char *lpzKeyDef);
int AddKeyDef(WORD wVirtualKeyCode, DWORD dwControlKeyState, tn_ops op);
// Delete a key translation
int DeleteKeyDef(WORD wVirtualKeyCode, DWORD dwControlKeyState);
// Paul Brannan 8/28/98
void set_ext_mode(DWORD mode) {ext_mode |= mode;}
void unset_ext_mode(DWORD mode) {ext_mode &= ~mode;}
void clear_ext_mode() {ext_mode = 0;}
DWORD get_ext_mode() {return ext_mode;}
private:
DWORD Fix_ControlKeyState(char *);
char* Fix_Tok(char *);
DWORD ext_mode; // Paul Brannan 8/28/98
TArrayAsVector<KeyMap> mapArray;
TArrayAsVector<TKeyDef> globals;
void DeleteAllDefs(void);
int AddGlobalDef(WORD wVirtualKeyCode, char*lpzKeyDef);
int LookOnGlobal(char* vkey);
DWORD GetGlobalCode(int i) {return globals[i].GetCodeKey();}
int currentKeyMap, mainKeyMap; // AVS
};
#endif // __KEYTRANS_H
@@ -0,0 +1,159 @@
// This is the STL wrapper for classlib/arrays.h from Borland's web site
// It has been modified to be compatible with vc++ (Paul Branann 5/7/98)
#ifndef STL_ARRAY_AS_VECTOR
#define STL_ARRAY_AS_VECTOR
#ifdef _MSC_VER
#pragma warning(disable: 4786)
#endif
// #include <vector.h>
// #include <algo.h>
#include <vector>
#include <algorithm>
using namespace std;
template <class T>
class TArrayAsVector : public vector<T> {
private:
const unsigned int growable;
typedef size_t size_type;
typedef typename vector<T>::const_iterator const_iterator;
const size_type lowerbound;
public:
TArrayAsVector(size_type upper,
size_type lower = 0,
int delta = 0) :
vector<T>( ),
growable(delta),
lowerbound(lower)
{ vector<T>::reserve(upper-lower + 1);}
~TArrayAsVector( )
{ // This call is unnecessary? (Paul Brannan 5/7/98)
// vector<T>::~vector( );
}
int Add(const T& item)
{ if(!growable && vector<T>::size( ) == vector<T>::capacity( ))
return 0;
else
insert(vector<T>::end( ), item);
return 1; }
int AddAt(const T& item, size_type index)
{ if(!growable &&
((vector<T>::size( ) == vector<T>::capacity( )) ||
(ZeroBase(index > vector<T>::capacity( )) )))
return 0;
if(ZeroBase(index) > vector<T>::capacity( )) // out of bounds
{ insert(vector<T>::end( ),
ZeroBase(index) - vector<T>::size( ), T( ));
insert(vector<T>::end( ), item); }
else
{ insert(vector<T>::begin( ) + ZeroBase(index), item); }
return 1;
}
size_type ArraySize( )
{ return vector<T>::capacity( ); }
size_type BoundBase(size_type location) const
{ if(location == UINT_MAX)
return INT_MAX;
else
return location + lowerbound; }
void Detach(size_type index)
{ erase(vector<T>::begin( ) + ZeroBase(index)); }
void Detach(const T& item)
{ Destroy(Find(item)); }
void Destroy(size_type index)
{ erase(vector<T>::begin( ) + ZeroBase(index)); }
void Destroy(const T& item)
{ Destroy(Find(item)); }
size_type Find(const T& item) const
{ const_iterator location = find(vector<T>::begin( ),
vector<T>::end( ), item);
if(location != vector<T>::end( ))
return BoundBase(size_type(location -
vector<T>::begin( )));
else
return INT_MAX; }
size_type GetItemsInContainer( )
{ return vector<T>::size( ); }
void Grow(size_type index)
{ if( index < lowerbound )
Reallocate(ArraySize( ) + (index -
lowerbound));
else if( index >= BoundBase(vector<T>::size( )))
Reallocate(ZeroBase(index) ); }
int HasMember(const T& item)
{ if(Find(item) != INT_MAX)
return 1;
else
return 0; }
int IsEmpty( )
{ return vector<T>::empty( ); }
int IsFull( )
{ if(growable)
return 0;
if(vector<T>::size( ) == vector<T>::capacity( ))
return 1;
else
return 0; }
size_type LowerBound( )
{ return lowerbound; }
T& operator[] (size_type index)
{ return vector<T>::
operator[](ZeroBase(index)); }
const T& operator[] (size_type index) const
{ return vector<T>::
operator[](ZeroBase(index)); }
void Flush( )
{
vector<T>::clear();
}
void Reallocate(size_type sz,
size_type offset = 0)
{ if(offset)
insert(vector<T>::begin( ), offset, T( ));
vector<T>::reserve(sz);
erase(vector<T>::end( ) - offset, vector<T>::end( )); }
void RemoveEntry(size_type index)
{ Detach(index); }
void SetData(size_type index, const T& item)
{ (*this)[index] = item; }
size_type UpperBound( )
{ return BoundBase(vector<T>::capacity( )) - 1; }
size_type ZeroBase(size_type index) const
{ return index - lowerbound; }
// The assignment operator is not inherited (Paul Brannan 5/25/98)
TArrayAsVector& operator=(const TArrayAsVector& v) {
vector<T>::operator=(v);
// should growable and lowerbound be copied as well?
return *this;
}
};
#endif
@@ -0,0 +1,220 @@
///////////////////////////////////////////////////////////////////////////////
//Telnet Win32 : an ANSI telnet client.
//Copyright (C) 1998-2000 Paul Brannan
//Copyright (C) 1998 I.Ioannou
//Copyright (C) 1997 Brad Johnson
//
//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., 675 Mass Ave, Cambridge, MA 02139, USA.
//
//I.Ioannou
//[email protected]
//
///////////////////////////////////////////////////////////////////////////
// TCharmap.cpp
// A simple class for handling character maps
// Written by Paul Brannan <[email protected]>
// Last modified 7/12/98
#include <string.h>
#include "tcharmap.h"
#include "tnconfig.h"
// map B (US ASCII)
// this maps each character to itself
static char mapB[256] = {
(char)0x00,(char)0x01,(char)0x02,(char)0x03,(char)0x04,(char)0x05,(char)0x06,(char)0x07, // 0x00 - 0x0f
(char)0x08,(char)0x09,(char)0x0a,(char)0x0b,(char)0x0c,(char)0x0d,(char)0x0e,(char)0x0f,
(char)0x10,(char)0x11,(char)0x12,(char)0x13,(char)0x14,(char)0x15,(char)0x16,(char)0x17, // 0x10 - 0x1f
(char)0x18,(char)0x19,(char)0x1a,(char)0x1b,(char)0x1c,(char)0x1d,(char)0x1e,(char)0x1f,
(char)0x20,(char)0x21,(char)0x22,(char)0x23,(char)0x24,(char)0x25,(char)0x26,(char)0x27, // 0x20 - 0x2f
(char)0x28,(char)0x29,(char)0x2a,(char)0x2b,(char)0x2c,(char)0x2d,(char)0x2e,(char)0x2f,
(char)0x30,(char)0x31,(char)0x32,(char)0x33,(char)0x34,(char)0x35,(char)0x36,(char)0x37, // 0x30 - 0x3f
(char)0x38,(char)0x39,(char)0x3a,(char)0x3b,(char)0x3c,(char)0x3d,(char)0x3e,(char)0x3f,
(char)0x40,(char)0x41,(char)0x42,(char)0x43,(char)0x44,(char)0x45,(char)0x46,(char)0x47, // 0x40 - 0x4f
(char)0x48,(char)0x49,(char)0x4a,(char)0x4b,(char)0x4c,(char)0x4d,(char)0x4e,(char)0x4f,
(char)0x50,(char)0x51,(char)0x52,(char)0x53,(char)0x54,(char)0x55,(char)0x56,(char)0x57, // 0x50 - 0x5f
(char)0x58,(char)0x59,(char)0x5a,(char)0x5b,(char)0x5c,(char)0x5d,(char)0x5e,(char)0x5f,
(char)0x60,(char)0x61,(char)0x62,(char)0x63,(char)0x64,(char)0x65,(char)0x66,(char)0x67, // 0x60 - 0x6f
(char)0x68,(char)0x69,(char)0x6a,(char)0x6b,(char)0x6c,(char)0x6d,(char)0x6e,(char)0x6f,
(char)0x70,(char)0x71,(char)0x72,(char)0x73,(char)0x74,(char)0x75,(char)0x76,(char)0x77, // 0x70 - 0x7f
(char)0x78,(char)0x79,(char)0x7a,(char)0x7b,(char)0x7c,(char)0x7d,(char)0x7e,(char)0x7f,
(char)0x80,(char)0x81,(char)0x82,(char)0x83,(char)0x84,(char)0x85,(char)0x86,(char)0x87, // 0x80 - 0x8f
(char)0x88,(char)0x89,(char)0x8a,(char)0x8b,(char)0x8c,(char)0x8d,(char)0x8e,(char)0x8f,
(char)0x90,(char)0x91,(char)0x92,(char)0x93,(char)0x94,(char)0x95,(char)0x96,(char)0x97, // 0x90 - 0x9f
(char)0x98,(char)0x99,(char)0x9a,(char)0x9b,(char)0x9c,(char)0x9d,(char)0x9e,(char)0x9f,
(char)0xa0,(char)0xa1,(char)0xa2,(char)0xa3,(char)0xa4,(char)0xa5,(char)0xa6,(char)0xa7, // 0xa0 - 0xaf
(char)0xa8,(char)0xa9,(char)0xaa,(char)0xab,(char)0xac,(char)0xad,(char)0xae,(char)0xaf,
(char)0xb0,(char)0xb1,(char)0xb2,(char)0xb3,(char)0xb4,(char)0xb5,(char)0xb6,(char)0xb7, // 0xb0 - 0xbf
(char)0xb8,(char)0xb9,(char)0xba,(char)0xbb,(char)0xbc,(char)0xbd,(char)0xbe,(char)0xbf,
(char)0xc0,(char)0xc1,(char)0xc2,(char)0xc3,(char)0xc4,(char)0xc5,(char)0xc6,(char)0xc7, // 0xc0 - 0xcf
(char)0xc8,(char)0xc9,(char)0xca,(char)0xcb,(char)0xcc,(char)0xcd,(char)0xce,(char)0xcf,
(char)0xd0,(char)0xd1,(char)0xd2,(char)0xd3,(char)0xd4,(char)0xd5,(char)0xd6,(char)0xd7, // 0xd0 - 0xdf
(char)0xd8,(char)0xd9,(char)0xda,(char)0xdb,(char)0xdc,(char)0xdd,(char)0xde,(char)0xdf,
(char)0xe0,(char)0xe1,(char)0xe2,(char)0xe3,(char)0xe4,(char)0xe5,(char)0xe6,(char)0xe7, // 0xe0 - 0xef
(char)0xe8,(char)0xe9,(char)0xea,(char)0xeb,(char)0xec,(char)0xed,(char)0xee,(char)0xef,
(char)0xf0,(char)0xf1,(char)0xf2,(char)0xf3,(char)0xf4,(char)0xf5,(char)0xf6,(char)0xf7, // 0xf0 - 0xff
(char)0xf8,(char)0xf9,(char)0xfa,(char)0xfb,(char)0xfc,(char)0xfd,(char)0xfe,(char)0xff
};
// map A (UK/National)
static char mapA[256] = {
(char)0x00,(char)0x01,(char)0x02,(char)0x03,(char)0x04,(char)0x05,(char)0x06,(char)0x07, // 0x00 - 0x0f
(char)0x08,(char)0x09,(char)0x0a,(char)0x0b,(char)0x0c,(char)0x0d,(char)0x0e,(char)0x0f,
(char)0x10,(char)0x11,(char)0x12,(char)0x13,(char)0x14,(char)0x15,(char)0x16,(char)0x17, // 0x10 - 0x1f
(char)0x18,(char)0x19,(char)0x1a,(char)0x1b,(char)0x1c,(char)0x1d,(char)0x1e,(char)0x1f,
(char)0x20,(char)0x21,(char)0x22,(char)0x9c,(char)0x24,(char)0x25,(char)0x26,(char)0x27, // 0x20 - 0x2f
(char)0x28,(char)0x29,(char)0x2a,(char)0x2b,(char)0x2c,(char)0x2d,(char)0x2e,(char)0x2f,
(char)0x30,(char)0x31,(char)0x32,(char)0x33,(char)0x34,(char)0x35,(char)0x36,(char)0x37, // 0x30 - 0x3f
(char)0x38,(char)0x39,(char)0x3a,(char)0x3b,(char)0x3c,(char)0x3d,(char)0x3e,(char)0x3f,
(char)0x40,(char)0x41,(char)0x42,(char)0x43,(char)0x44,(char)0x45,(char)0x46,(char)0x47, // 0x40 - 0x4f
(char)0x48,(char)0x49,(char)0x4a,(char)0x4b,(char)0x4c,(char)0x4d,(char)0x4e,(char)0x4f,
(char)0x50,(char)0x51,(char)0x52,(char)0x53,(char)0x54,(char)0x55,(char)0x56,(char)0x57, // 0x50 - 0x5f
(char)0x58,(char)0x59,(char)0x5a,(char)0x5b,(char)0x5c,(char)0x5d,(char)0x5e,(char)0x5f,
(char)0x60,(char)0x61,(char)0x62,(char)0x63,(char)0x64,(char)0x65,(char)0x66,(char)0x67, // 0x60 - 0x6f
(char)0x68,(char)0x69,(char)0x6a,(char)0x6b,(char)0x6c,(char)0x6d,(char)0x6e,(char)0x6f,
(char)0x70,(char)0x71,(char)0x72,(char)0x73,(char)0x74,(char)0x75,(char)0x76,(char)0x77, // 0x70 - 0x7f
(char)0x78,(char)0x79,(char)0x7a,(char)0x7b,(char)0x7c,(char)0x7d,(char)0x7e,(char)0x7f,
(char)0x80,(char)0x81,(char)0x82,(char)0x83,(char)0x84,(char)0x85,(char)0x86,(char)0x87, // 0x80 - 0x8f
(char)0x88,(char)0x89,(char)0x8a,(char)0x8b,(char)0x8c,(char)0x8d,(char)0x8e,(char)0x8f,
(char)0x90,(char)0x91,(char)0x92,(char)0x93,(char)0x94,(char)0x95,(char)0x96,(char)0x97, // 0x90 - 0x9f
(char)0x98,(char)0x99,(char)0x9a,(char)0x9b,(char)0x9c,(char)0x9d,(char)0x9e,(char)0x9f,
(char)0xa0,(char)0xa1,(char)0xa2,(char)0xa3,(char)0xa4,(char)0xa5,(char)0xa6,(char)0xa7, // 0xa0 - 0xaf
(char)0xa8,(char)0xa9,(char)0xaa,(char)0xab,(char)0xac,(char)0xad,(char)0xae,(char)0xaf,
(char)0xb0,(char)0xb1,(char)0xb2,(char)0xb3,(char)0xb4,(char)0xb5,(char)0xb6,(char)0xb7, // 0xb0 - 0xbf
(char)0xb8,(char)0xb9,(char)0xba,(char)0xbb,(char)0xbc,(char)0xbd,(char)0xbe,(char)0xbf,
(char)0xc0,(char)0xc1,(char)0xc2,(char)0xc3,(char)0xc4,(char)0xc5,(char)0xc6,(char)0xc7, // 0xc0 - 0xcf
(char)0xc8,(char)0xc9,(char)0xca,(char)0xcb,(char)0xcc,(char)0xcd,(char)0xce,(char)0xcf,
(char)0xd0,(char)0xd1,(char)0xd2,(char)0xd3,(char)0xd4,(char)0xd5,(char)0xd6,(char)0xd7, // 0xd0 - 0xdf
(char)0xd8,(char)0xd9,(char)0xda,(char)0xdb,(char)0xdc,(char)0xdd,(char)0xde,(char)0xdf,
(char)0xe0,(char)0xe1,(char)0xe2,(char)0xe3,(char)0xe4,(char)0xe5,(char)0xe6,(char)0xe7, // 0xe0 - 0xef
(char)0xe8,(char)0xe9,(char)0xea,(char)0xeb,(char)0xec,(char)0xed,(char)0xee,(char)0xef,
(char)0xf0,(char)0xf1,(char)0xf2,(char)0xf3,(char)0xf4,(char)0xf5,(char)0xf6,(char)0xf7, // 0xf0 - 0xff
(char)0xf8,(char)0xf9,(char)0xfa,(char)0xfb,(char)0xfc,(char)0xfd,(char)0xfe,(char)0xff
};
// map 0
// Special graphics and line drawing
static char map0[256] = {
(char)0x00,(char)0x01,(char)0x02,(char)0x03,(char)0x04,(char)0x05,(char)0x06,(char)0x07, // 0x00 - 0x0f
(char)0x08,(char)0x09,(char)0x0a,(char)0x0b,(char)0x0c,(char)0x0d,(char)0x0e,(char)0x0f,
(char)0x10,(char)0x11,(char)0x12,(char)0x13,(char)0x14,(char)0x15,(char)0x16,(char)0x17, // 0x10 - 0x1f
(char)0x18,(char)0x19,(char)0x1a,(char)0x1b,(char)0x1c,(char)0x1d,(char)0x1e,(char)0x1f,
(char)0x20,(char)0x21,(char)0x22,(char)0x23,(char)0x24,(char)0x25,(char)0x26,(char)0x27, // 0x20 - 0x2f
(char)0x28,(char)0x29,(char)0x2a,(char)0x2b,(char)0x2c,(char)0x2d,(char)0x2e,(char)0x2f,
(char)0x30,(char)0x31,(char)0x32,(char)0x33,(char)0x34,(char)0x35,(char)0x36,(char)0x37, // 0x30 - 0x3f
(char)0x38,(char)0x39,(char)0x3a,(char)0x3b,(char)0x3c,(char)0x3d,(char)0x3e,(char)0x3f,
(char)0x40,(char)0x41,(char)0x42,(char)0x43,(char)0x44,(char)0x45,(char)0x46,(char)0x47, // 0x40 - 0x4f
(char)0x48,(char)0x49,(char)0x4a,(char)0x4b,(char)0x4c,(char)0x4d,(char)0x4e,(char)0x4f,
(char)0x50,(char)0x51,(char)0x52,(char)0x53,(char)0x54,(char)0x55,(char)0x56,(char)0x57, // 0x50 - 0x5f
(char)0x58,(char)0x59,(char)0x5a,(char)0x5b,(char)0x04,(char)0x5d,(char)0x5e,(char)0xdb,
(char)0x04,(char)0xb1,(char)0x09,(char)0x0c,(char)0x0d,(char)0x0a,(char)0xf8,(char)0xf1, // 0x60 - 0x6f
(char)0x68,(char)0x0b,(char)0xd9,(char)0xbf,(char)0xda,(char)0xc0,(char)0xc5,(char)0xa9,
(char)0xa9,(char)0xc4,(char)0x5f,(char)0x5f,(char)0xc3,(char)0xb4,(char)0xc1,(char)0xc2, // 0x70 - 0x7f
(char)0xb3,(char)0xf3,(char)0xf2,(char)0xe3,(char)0x2f,(char)0x9c,(char)0xfe,(char)0x7f,
(char)0x80,(char)0x81,(char)0x82,(char)0x83,(char)0x84,(char)0x85,(char)0x86,(char)0x87, // 0x80 - 0x8f
(char)0x88,(char)0x89,(char)0x8a,(char)0x8b,(char)0x8c,(char)0x8d,(char)0x8e,(char)0x8f,
(char)0x90,(char)0x91,(char)0x92,(char)0x93,(char)0x94,(char)0x95,(char)0x96,(char)0x97, // 0x90 - 0x9f
(char)0x98,(char)0x99,(char)0x9a,(char)0x9b,(char)0x9c,(char)0x9d,(char)0x9e,(char)0x9f,
(char)0xa0,(char)0xa1,(char)0xa2,(char)0xa3,(char)0xa4,(char)0xa5,(char)0xa6,(char)0xa7, // 0xa0 - 0xaf
(char)0xa8,(char)0xa9,(char)0xaa,(char)0xab,(char)0xac,(char)0xad,(char)0xae,(char)0xaf,
(char)0xb0,(char)0xb1,(char)0xb2,(char)0xb3,(char)0xb4,(char)0xb5,(char)0xb6,(char)0xb7, // 0xb0 - 0xbf
(char)0xb8,(char)0xb9,(char)0xba,(char)0xbb,(char)0xbc,(char)0xbd,(char)0xbe,(char)0xbf,
(char)0xc0,(char)0xc1,(char)0xc2,(char)0xc3,(char)0xc4,(char)0xc5,(char)0xc6,(char)0xc7, // 0xc0 - 0xcf
(char)0xc8,(char)0xc9,(char)0xca,(char)0xcb,(char)0xcc,(char)0xcd,(char)0xce,(char)0xcf,
(char)0xd0,(char)0xd1,(char)0xd2,(char)0xd3,(char)0xd4,(char)0xd5,(char)0xd6,(char)0xd7, // 0xd0 - 0xdf
(char)0xd8,(char)0xd9,(char)0xda,(char)0xdb,(char)0xdc,(char)0xdd,(char)0xde,(char)0xdf,
(char)0xe0,(char)0xe1,(char)0xe2,(char)0xe3,(char)0xe4,(char)0xe5,(char)0xe6,(char)0xe7, // 0xe0 - 0xef
(char)0xe8,(char)0xe9,(char)0xea,(char)0xeb,(char)0xec,(char)0xed,(char)0xee,(char)0xef,
(char)0xf0,(char)0xf1,(char)0xf2,(char)0xf3,(char)0xf4,(char)0xf5,(char)0xf6,(char)0xf7, // 0xf0 - 0xff
(char)0xf8,(char)0xf9,(char)0xfa,(char)0xfb,(char)0xfc,(char)0xfd,(char)0xfe,(char)0xff
};
// map 0 (safe version for being unable to write ROM chars)
// Special graphics and line drawing
static char map0_safe[256] = {
(char)0x00,(char)0x01,(char)0x02,(char)0x03,(char)0x04,(char)0x05,(char)0x06,(char)0x07, // 0x00 - 0x0f
(char)0x08,(char)0x09,(char)0x0a,(char)0x0b,(char)0x0c,(char)0x0d,(char)0x0e,(char)0x0f,
(char)0x10,(char)0x11,(char)0x12,(char)0x13,(char)0x14,(char)0x15,(char)0x16,(char)0x17, // 0x10 - 0x1f
(char)0x18,(char)0x19,(char)0x1a,(char)0x1b,(char)0x1c,(char)0x1d,(char)0x1e,(char)0x1f,
(char)0x20,(char)0x21,(char)0x22,(char)0x23,(char)0x24,(char)0x25,(char)0x26,(char)0x27, // 0x20 - 0x2f
(char)0x28,(char)0x29,(char)0x2a,(char)0x2b,(char)0x2c,(char)0x2d,(char)0x2e,(char)0x2f,
(char)0x30,(char)0x31,(char)0x32,(char)0x33,(char)0x34,(char)0x35,(char)0x36,(char)0x37, // 0x30 - 0x3f
(char)0x38,(char)0x39,(char)0x3a,(char)0x3b,(char)0x3c,(char)0x3d,(char)0x3e,(char)0x3f,
(char)0x40,(char)0x41,(char)0x42,(char)0x43,(char)0x44,(char)0x45,(char)0x46,(char)0x47, // 0x40 - 0x4f
(char)0x48,(char)0x49,(char)0x4a,(char)0x4b,(char)0x4c,(char)0x4d,(char)0x4e,(char)0x4f,
(char)0x50,(char)0x51,(char)0x52,(char)0x53,(char)0x54,(char)0x55,(char)0x56,(char)0x57, // 0x50 - 0x5f
(char)0x58,(char)0x59,(char)0x5a,(char)0x5b,(char)0x04,(char)0x5d,(char)0x5e,(char)0xdb,
(char)0x04,(char)0xb1,(char)0xf8,(char)0xf9,(char)0xfb,(char)0xdb,(char)0xf8,(char)0xf1, // 0x60 - 0x6f
(char)0x68,(char)0xf9,(char)0xd9,(char)0xbf,(char)0xda,(char)0xc0,(char)0xc5,(char)0xa9,
(char)0xa9,(char)0xc4,(char)0x5f,(char)0x5f,(char)0xc3,(char)0xb4,(char)0xc1,(char)0xc2, // 0x70 - 0x7f
(char)0xb3,(char)0xf3,(char)0xf2,(char)0xe3,(char)0x2f,(char)0x9c,(char)0xfe,(char)0x7f,
(char)0x80,(char)0x81,(char)0x82,(char)0x83,(char)0x84,(char)0x85,(char)0x86,(char)0x87, // 0x80 - 0x8f
(char)0x88,(char)0x89,(char)0x8a,(char)0x8b,(char)0x8c,(char)0x8d,(char)0x8e,(char)0x8f,
(char)0x90,(char)0x91,(char)0x92,(char)0x93,(char)0x94,(char)0x95,(char)0x96,(char)0x97, // 0x90 - 0x9f
(char)0x98,(char)0x99,(char)0x9a,(char)0x9b,(char)0x9c,(char)0x9d,(char)0x9e,(char)0x9f,
(char)0xa0,(char)0xa1,(char)0xa2,(char)0xa3,(char)0xa4,(char)0xa5,(char)0xa6,(char)0xa7, // 0xa0 - 0xaf
(char)0xa8,(char)0xa9,(char)0xaa,(char)0xab,(char)0xac,(char)0xad,(char)0xae,(char)0xaf,
(char)0xb0,(char)0xb1,(char)0xb2,(char)0xb3,(char)0xb4,(char)0xb5,(char)0xb6,(char)0xb7, // 0xb0 - 0xbf
(char)0xb8,(char)0xb9,(char)0xba,(char)0xbb,(char)0xbc,(char)0xbd,(char)0xbe,(char)0xbf,
(char)0xc0,(char)0xc1,(char)0xc2,(char)0xc3,(char)0xc4,(char)0xc5,(char)0xc6,(char)0xc7, // 0xc0 - 0xcf
(char)0xc8,(char)0xc9,(char)0xca,(char)0xcb,(char)0xcc,(char)0xcd,(char)0xce,(char)0xcf,
(char)0xd0,(char)0xd1,(char)0xd2,(char)0xd3,(char)0xd4,(char)0xd5,(char)0xd6,(char)0xd7, // 0xd0 - 0xdf
(char)0xd8,(char)0xd9,(char)0xda,(char)0xdb,(char)0xdc,(char)0xdd,(char)0xde,(char)0xdf,
(char)0xe0,(char)0xe1,(char)0xe2,(char)0xe3,(char)0xe4,(char)0xe5,(char)0xe6,(char)0xe7, // 0xe0 - 0xef
(char)0xe8,(char)0xe9,(char)0xea,(char)0xeb,(char)0xec,(char)0xed,(char)0xee,(char)0xef,
(char)0xf0,(char)0xf1,(char)0xf2,(char)0xf3,(char)0xf4,(char)0xf5,(char)0xf6,(char)0xf7, // 0xf0 - 0xff
(char)0xf8,(char)0xf9,(char)0xfa,(char)0xfb,(char)0xfc,(char)0xfd,(char)0xfe,(char)0xff
};
TCharmap::TCharmap() {
memset(map, 0, sizeof(map));
map[0] = mapB; // default map
map[(unsigned char)'B'] = mapB;
map[(unsigned char)'A'] = mapA;
if(ini.get_fast_write()) {
map[(unsigned char)'0'] = map0_safe;
map[(unsigned char)'2'] = map0_safe;
} else {
map[(unsigned char)'0'] = map0;
map[(unsigned char)'2'] = map0;
}
current_map = map[0];
}
TCharmap::~TCharmap() {
for(int j = 0; j < 256; j++) {
if(map[j]) {
// Don't delete static maps!
switch(j) {
case 'B':
case 'A':
case '0':
case '2':
case 0: break;
default: delete map[j];
}
}
}
}
void TCharmap::modmap(char pos, char mapchar, char c) {
if(!map[(unsigned char)mapchar]) {
map[(unsigned char)mapchar] = new char[256];
for(int j = 0; j < 256; j++) map[(unsigned char)mapchar][(unsigned char)pos] = j;
}
map[(unsigned char)mapchar][(unsigned char)pos] = c;
}
@@ -0,0 +1,41 @@
// This is a simple class to handle character maps
// (Paul Brannan 6/25/98)
#ifndef __TCHARMAP_H
#define __TCHARMAP_H
class TCharmap {
private:
char *map[256];
char *current_map;
public:
TCharmap();
~TCharmap();
void init() {}
char translate(char c, char mapchar) {
if(map[(unsigned char)mapchar]) return map[(unsigned char)mapchar][(unsigned char)c];
return c;
}
char translate(char c) {
return current_map[(unsigned char)c];
}
void setmap(char mapchar) {
if(map[(unsigned char)mapchar]) current_map = map[(unsigned char)mapchar];
}
void translate_buffer(char *start, char *end) {
while(start < end) {
*start = translate(*start);
start++;
}
}
void modmap(char pos, char mapchar, char c);
int enabled;
};
#endif
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,172 @@
#ifndef __TNPARSER_H
#define __TNPARSER_H
#include "tnconfig.h"
/* A diagram of the following values:
*
* (0,0)
* +----------------------------------------+
* | |
* | |
* | |
* | |
* | |
* | |
* | |
* | |
* | |
* | |
* | |
* | |
* | |
* | CON_TOP |
* +---------------------------+.....?......| ---
* | . | | |
* | . | <-- OR --> | |
* | . | | |
* CON_LEFT | . | CON_RIGHT |
* (=0) | . | (=CON_ | CON_LINES
* |..............* | WIDTH) |
* | (CON_CUR_X, | | |
* | CON_CUR_Y) | | |
* | | | |
* | | | |
* | | | |
* +---------------------------+------------+ ---
* CON_BOTTOM (=CON_TOP + CON_HEIGHT)
*
* |--------- CON_COLS --------|
*
* Keep in mind that CON_TOP, CON_BOTTOM, CON_LEFT, and CON_RIGHT are relative
* to zero, but CON_CUR_X, CON_CUR_Y, CON_WIDTH, and CON_HEIGHT are relative to
* CON_TOP and CON_LEFT
*/
#define CON_TOP ConsoleInfo.srWindow.Top
#define CON_BOTTOM ConsoleInfo.srWindow.Bottom
#define CON_LEFT 0
#define CON_RIGHT (ConsoleInfo.dwSize.X - 1)
#define CON_HEIGHT (CON_BOTTOM - CON_TOP)
#define CON_WIDTH (CON_RIGHT - CON_LEFT)
#define CON_LINES (CON_HEIGHT + 1)
#define CON_COLS (CON_WIDTH + 1)
#define CON_CUR_X (ConsoleInfo.dwCursorPosition.X - CON_LEFT)
#define CON_CUR_Y (ConsoleInfo.dwCursorPosition.Y - CON_TOP)
class TConsole {
public:
TConsole(HANDLE hConsole);
~TConsole();
void sync();
// Cursor movement routines
int GetRawCursorX() {return CON_CUR_X;}
int GetRawCursorY() {return CON_CUR_Y;}
int GetCursorX() {return CON_CUR_X;}
int GetCursorY() {
if(iScrollStart != -1)
return CON_CUR_Y - iScrollStart;
return GetRawCursorY();
}
void SetRawCursorPosition(int x, int y);
void SetCursorPosition(int x, int y);
void SetCursorSize(int pct);
void MoveCursorPosition(int x, int y);
// Screen mode/size routines
int GetWidth() {return CON_COLS;}
int GetHeight() {return CON_LINES;}
void SetExtendedMode(int iFunction, BOOL bEnable);
void SetWindowSize(int width, int height); // Set the size of the window,
// but not the buffer
// Color/attribute routines
void SetAttrib(unsigned char wAttr) {wAttributes = wAttr;}
unsigned char GetAttrib() {return wAttributes;}
void Normal(); // Reset all attributes
void HighVideo(); // Aka "bold"
void LowVideo();
void SetForeground(unsigned char wAttrib); // Set the foreground directly
void SetBackground(unsigned char wAttrib);
void BlinkOn(); // Blink on/off
void BlinkOff();
void UnderlineOn(); // Underline on/off
void UnderlineOff();
void UlBlinkOn(); // Blink+Underline on/off
void UlBlinkOff();
void ReverseOn(); // Reverse on/off
void ReverseOff();
void Lightbg(); // High-intensity background
void Darkbg(); // Low-intensity background
void setDefaultFg(unsigned char u) {defaultfg = u;}
void setDefaultBg(unsigned char u) {defaultbg = u;}
// Text output routines
unsigned long WriteText(const char *pszString, unsigned long cbString);
unsigned long WriteString(const char* pszString, unsigned long cbString);
unsigned long WriteStringFast(const char *pszString, unsigned long cbString);
unsigned long WriteCtrlString(const char* pszString, unsigned long cbString);
unsigned long WriteCtrlChar(char c);
unsigned long NetWriteString(const char* pszString, unsigned long cbString);
// Clear screen/screen area functions
void ClearScreen(char c = ' ');
void ClearWindow(int start, int end, char c = ' ');
void ClearEOScreen(char c = ' ');
void ClearBOScreen(char c = ' ');
void ClearLine(char c = ' ');
void ClearEOLine(char c = ' ');
void ClearBOLine(char c = ' ');
// Scrolling and text output control functions
void SetScroll(int start, int end);
void ScrollDown(int iStartRow , int iEndRow, int bUp);
void ScrollAll(int bUp) {ScrollDown(iScrollStart, iScrollEnd, bUp);}
void index();
void reverse_index();
void setLineWrap(bool bEnabled){
if(!ini.get_lock_linewrap())
ini.set_value("Wrap_Line", bEnabled ? "true" : "false");
}
bool getLineWrap() {return ini.get_wrapline();}
// Insert/delete characters/lines
void InsertLine(int numlines); // Added by Titus von Boxberg 30/3/97
void InsertCharacter(int numchar); // "
void DeleteCharacter(int numchar); // "
void InsertMode(int i) {insert_mode = i;}
// Miscellaneous functions
void Beep();
protected:
HANDLE hConsole;
CONSOLE_SCREEN_BUFFER_INFO ConsoleInfo;
unsigned char wAttributes;
unsigned char fg, bg;
unsigned char defaultfg, defaultbg;
unsigned char origfg, origbg;
bool blink;
bool underline;
bool reverse;
int iScrollStart;
int iScrollEnd;
int insert_mode;
};
// Non-member functions for saving state -- used by the scrollback buffer viewer
void saveScreen(CHAR_INFO* chiBuffer);
void restoreScreen(CHAR_INFO* chiBuffer);
CHAR_INFO* newBuffer();
void deleteBuffer(CHAR_INFO* chiBuffer);
#endif
@@ -0,0 +1,305 @@
#ifndef ___TELNET_H
#define ___TELNET_H
/*
* Copyright (c) 1983 Regents of the University of California.
* All rights reserved.
*
* Redistribution and use in source and binary forms are permitted provided
* that: (1) source distributions retain this entire copyright notice and
* comment, and (2) distributions including binaries display the following
* acknowledgement: ``This product includes software developed by the
* University of California, Berkeley and its contributors'' in the
* documentation or other materials provided with the distribution and in
* all advertising materials mentioning features or use of this software.
* Neither the name of the University nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*
* @(#)telnet.h 5.12 (Berkeley) 3/5/91
*/
// This file modified 5/15/98 by Paul Brannan.
// Added (unsigned char) to the #defines.
// Formatted for readability.
/*
* Definitions for the TELNET protocol.
*/
#define IAC (unsigned char)255 /* interpret as command: */
#define DONT (unsigned char)254 /* you are not to use option */
#define DO (unsigned char)253 /* please, you use option */
#define WONT (unsigned char)252 /* I won't use option */
#define WILL (unsigned char)251 /* I will use option */
#define SB (unsigned char)250 /* interpret as subnegotiation */
#define GA (unsigned char)249 /* you may reverse the line */
#define EL (unsigned char)248 /* erase the current line */
#define EC (unsigned char)247 /* erase the current character */
#define AYT (unsigned char)246 /* are you there */
#define AO (unsigned char)245 /* abort output--but let prog finish */
#define IP (unsigned char)244 /* interrupt process--permanently */
#define BREAK (unsigned char)243 /* break */
#define DM (unsigned char)242 /* data mark--for connect. cleaning */
#define NOP (unsigned char)241 /* nop */
#define SE (unsigned char)240 /* end sub negotiation */
#define EOR (unsigned char)239 /* end of record (transparent mode) */
#define ABORT (unsigned char)238 /* Abort process */
#define SUSP (unsigned char)237 /* Suspend process */
#define xEOF (unsigned char)236 /* End of file: EOF is already used... */
#define SYNCH (unsigned char)242 /* for telfunc calls */
#ifdef TELCMDS
char *telcmds[] = {
"EOF", "SUSP", "ABORT", "EOR",
"SE", "NOP", "DMARK", "BRK", "IP", "AO", "AYT", "EC",
"EL", "GA", "SB", "WILL", "WONT", "DO", "DONT", "IAC", 0,
};
#else
extern char *telcmds[];
#endif
#define TELCMD_FIRST xEOF
#define TELCMD_LAST IAC
#define TELCMD_OK(x) ((x) <= TELCMD_LAST && (x) >= TELCMD_FIRST)
#define TELCMD(x) telcmds[(x)-TELCMD_FIRST]
/* telnet options */
#define TELOPT_BINARY (unsigned char)0 /* 8-bit data path */
#define TELOPT_ECHO (unsigned char)1 /* echo */
#define TELOPT_RCP (unsigned char)2 /* prepare to reconnect */
#define TELOPT_SGA (unsigned char)3 /* suppress go ahead */
#define TELOPT_NAMS (unsigned char)4 /* approximate message size */
#define TELOPT_STATUS (unsigned char)5 /* give status */
#define TELOPT_TM (unsigned char)6 /* timing mark */
#define TELOPT_RCTE (unsigned char)7 /* remote controlled transmission and echo */
#define TELOPT_NAOL (unsigned char)8 /* negotiate about output line width */
#define TELOPT_NAOP (unsigned char)9 /* negotiate about output page size */
#define TELOPT_NAOCRD (unsigned char)10 /* negotiate about CR disposition */
#define TELOPT_NAOHTS (unsigned char)11 /* negotiate about horizontal tabstops */
#define TELOPT_NAOHTD (unsigned char)12 /* negotiate about horizontal tab disposition */
#define TELOPT_NAOFFD (unsigned char)13 /* negotiate about formfeed disposition */
#define TELOPT_NAOVTS (unsigned char)14 /* negotiate about vertical tab stops */
#define TELOPT_NAOVTD (unsigned char)15 /* negotiate about vertical tab disposition */
#define TELOPT_NAOLFD (unsigned char)16 /* negotiate about output LF disposition */
#define TELOPT_XASCII (unsigned char)17 /* extended ascic character set */
#define TELOPT_LOGOUT (unsigned char)18 /* force logout */
#define TELOPT_BM (unsigned char)19 /* byte macro */
#define TELOPT_DET (unsigned char)20 /* data entry terminal */
#define TELOPT_SUPDUP (unsigned char)21 /* supdup protocol */
#define TELOPT_SUPDUPOUTPUT (unsigned char)22 /* supdup output */
#define TELOPT_SNDLOC (unsigned char)23 /* send location */
#define TELOPT_TTYPE (unsigned char)24 /* terminal type */
#define TELOPT_EOR (unsigned char)25 /* end or record */
#define TELOPT_TUID (unsigned char)26 /* TACACS user identification */
#define TELOPT_OUTMRK (unsigned char)27 /* output marking */
#define TELOPT_TTYLOC (unsigned char)28 /* terminal location number */
#define TELOPT_3270REGIME (unsigned char)29 /* 3270 regime */
#define TELOPT_X3PAD (unsigned char)30 /* X.3 PAD */
#define TELOPT_NAWS (unsigned char)31 /* window size */
#define TELOPT_TSPEED (unsigned char)32 /* terminal speed */
#define TELOPT_LFLOW (unsigned char)33 /* remote flow control */
#define TELOPT_LINEMODE (unsigned char)34 /* Linemode option */
#define TELOPT_XDISPLOC (unsigned char)35 /* X Display Location */
#define TELOPT_ENVIRON (unsigned char)36 /* Environment variables */
#define TELOPT_AUTHENTICATION (unsigned char)37 /* Authenticate */
#define TELOPT_ENCRYPT (unsigned char)38 /* Encryption option */
#define TELOPT_EXOPL (unsigned char)255 /* extended-options-list */
#define NTELOPTS (1+TELOPT_ENCRYPT)
#ifdef TELOPTS
char *telopts[NTELOPTS+1] = {
"BINARY", "ECHO", "RCP", "SUPPRESS GO AHEAD", "NAME",
"STATUS", "TIMING MARK", "RCTE", "NAOL", "NAOP",
"NAOCRD", "NAOHTS", "NAOHTD", "NAOFFD", "NAOVTS",
"NAOVTD", "NAOLFD", "EXTEND ASCII", "LOGOUT", "BYTE MACRO",
"DATA ENTRY TERMINAL", "SUPDUP", "SUPDUP OUTPUT",
"SEND LOCATION", "TERMINAL TYPE", "END OF RECORD",
"TACACS UID", "OUTPUT MARKING", "TTYLOC",
"3270 REGIME", "X.3 PAD", "NAWS", "TSPEED", "LFLOW",
"LINEMODE", "XDISPLOC", "ENVIRON", "AUTHENTICATION",
"ENCRYPT",
0,
};
#define TELOPT_FIRST TELOPT_BINARY
#define TELOPT_LAST TELOPT_ENCRYPT
#define TELOPT_OK(x) ((x) <= TELOPT_LAST && (x) >= TELOPT_FIRST)
#define TELOPT(x) telopts[(x)-TELOPT_FIRST]
#endif
/* sub-option qualifiers */
#define TELQUAL_IS (unsigned char)0 /* option is... */
#define TELQUAL_SEND (unsigned char)1 /* send option */
#define TELQUAL_INFO (unsigned char)2 /* ENVIRON: informational version of IS */
#define TELQUAL_REPLY (unsigned char)2 /* AUTHENTICATION: client version of IS */
#define TELQUAL_NAME (unsigned char)3 /* AUTHENTICATION: client version of IS */
/*
* LINEMODE suboptions
*/
#define LM_MODE 1
#define LM_FORWARDMASK 2
#define LM_SLC 3
#define MODE_EDIT 0x01
#define MODE_TRAPSIG 0x02
#define MODE_ACK 0x04
#define MODE_SOFT_TAB 0x08
#define MODE_LIT_ECHO 0x10
#define MODE_MASK 0x1f
/* Not part of protocol, but needed to simplify things... */
#define MODE_FLOW 0x0100
#define MODE_ECHO 0x0200
#define MODE_INBIN 0x0400
#define MODE_OUTBIN 0x0800
#define MODE_FORCE 0x1000
#define SLC_SYNCH 1
#define SLC_BRK 2
#define SLC_IP 3
#define SLC_AO 4
#define SLC_AYT 5
#define SLC_EOR 6
#define SLC_ABORT 7
#define SLC_EOF 8
#define SLC_SUSP 9
#define SLC_EC 10
#define SLC_EL 11
#define SLC_EW 12
#define SLC_RP 13
#define SLC_LNEXT 14
#define SLC_XON 15
#define SLC_XOFF 16
#define SLC_FORW1 17
#define SLC_FORW2 18
#define NSLC 18
/*
* For backwards compatability, we define SLC_NAMES to be the
* list of names if SLC_NAMES is not defined.
*/
#define SLC_NAMELIST "0", "SYNCH", "BRK", "IP", "AO", "AYT", "EOR", \
"ABORT", "EOF", "SUSP", "EC", "EL", "EW", "RP", \
"LNEXT", "XON", "XOFF", "FORW1", "FORW2", 0,
#ifdef SLC_NAMES
//char *slc_names[] = {
// SLC_NAMELIST
//};
#else
extern char *slc_names[];
#define SLC_NAMES SLC_NAMELIST
#endif
#define SLC_NAME_OK(x) ((x) >= 0 && (x) < NSLC)
#define SLC_NAME(x) slc_names[x]
#define SLC_NOSUPPORT 0
#define SLC_CANTCHANGE 1
#define SLC_VARIABLE 2
#define SLC_DEFAULT 3
#define SLC_LEVELBITS 0x03
#define SLC_FUNC 0
#define SLC_FLAGS 1
#define SLC_VALUE 2
#define SLC_ACK 0x80
#define SLC_FLUSHIN 0x40
#define SLC_FLUSHOUT 0x20
#define ENV_VALUE 0
#define ENV_VAR 1
#define ENV_ESC 2
/*
* AUTHENTICATION suboptions
*/
/*
* Who is authenticating who ...
*/
#define AUTH_WHO_CLIENT 0 /* Client authenticating server */
#define AUTH_WHO_SERVER 1 /* Server authenticating client */
#define AUTH_WHO_MASK 1
/*
* amount of authentication done
*/
#define AUTH_HOW_ONE_WAY 0
#define AUTH_HOW_MUTUAL 2
#define AUTH_HOW_MASK 2
#define AUTHTYPE_NULL 0
#define AUTHTYPE_KERBEROS_V4 1
#define AUTHTYPE_KERBEROS_V5 2
#define AUTHTYPE_SPX 3
#define AUTHTYPE_MINK 4
#define AUTHTYPE_CNT 5
#define AUTHTYPE_TEST 99
#ifdef AUTH_NAMES
char *authtype_names[] = {
"NULL", "KERBEROS_V4", "KERBEROS_V5", "SPX", "MINK", 0,
};
#else
extern char *authtype_names[];
#endif
#define AUTHTYPE_NAME_OK(x) ((x) >= 0 && (x) < AUTHTYPE_CNT)
#define AUTHTYPE_NAME(x) authtype_names[x]
/*
* ENCRYPTion suboptions
*/
#define ENCRYPT_IS 0 /* I pick encryption type ... */
#define ENCRYPT_SUPPORT 1 /* I support encryption types ... */
#define ENCRYPT_REPLY 2 /* Initial setup response */
#define ENCRYPT_START 3 /* Am starting to send encrypted */
#define ENCRYPT_END 4 /* Am ending encrypted */
#define ENCRYPT_REQSTART 5 /* Request you start encrypting */
#define ENCRYPT_REQEND 6 /* Request you send encrypting */
#define ENCRYPT_ENC_KEYID 7
#define ENCRYPT_DEC_KEYID 8
#define ENCRYPT_CNT 9
#define ENCTYPE_ANY 0
#define ENCTYPE_DES_CFB64 1
#define ENCTYPE_DES_OFB64 2
#define ENCTYPE_CNT 3
#ifdef ENCRYPT_NAMES
char *encrypt_names[] = {
"IS", "SUPPORT", "REPLY", "START", "END",
"REQUEST-START", "REQUEST-END", "ENC-KEYID", "DEC-KEYID",
0,
};
char *enctype_names[] = {
"ANY", "DES_CFB64", "DES_OFB64", 0,
};
#else
extern char *encrypt_names[];
extern char *enctype_names[];
#endif
#define ENCRYPT_NAME_OK(x) ((x) >= 0 && (x) < ENCRYPT_CNT)
#define ENCRYPT_NAME(x) encrypt_names[x]
#define ENCTYPE_NAME_OK(x) ((x) >= 0 && (x) < ENCTYPE_CNT)
#define ENCTYPE_NAME(x) enctype_names[x]
//////////////////////////////////////////////////////
//////////////////////////////////////////////////////
#endif
@@ -0,0 +1,136 @@
///////////////////////////////////////////////////////////////////////////////
//Telnet Win32 : an ANSI telnet client.
//Copyright (C) 1998-2000 Paul Brannan
//Copyright (C) 1998 I.Ioannou
//Copyright (C) 1997 Brad Johnson
//
//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., 675 Mass Ave, Cambridge, MA 02139, USA.
//
//I.Ioannou
//[email protected]
//
///////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////
// Class TkeyDef - Key Definitions //
// - kept in an array container //
// originally part of KeyTrans.cpp //
/////////////////////////////////////////////////////////
#include "tkeydef.h"
#include <string.h>
// This class did not properly release memory before, and a buffer overrun
// was apparent in operator=(char*). Fixed. (Paul Brannan Feb. 4, 1999)
TKeyDef::TKeyDef() {
uKeyDef.szKeyDef = 0;
vk_code = dwState = 0;
}
TKeyDef::TKeyDef(char *def, DWORD state, DWORD code) {
uKeyDef.szKeyDef = 0;
if (def != NULL && *def != 0) {
// szKeyDef = (char *) GlobalAlloc(GPTR, strlen(def) +1);
uKeyDef.szKeyDef = new char[strlen(def)+1];
strcpy(uKeyDef.szKeyDef, def);
}
dwState = state;
vk_code = code;
}
TKeyDef::TKeyDef(optype op, DWORD state, DWORD code) {
uKeyDef.op = new optype;
uKeyDef.op->sendstr = 0;
uKeyDef.op->the_op = op.the_op;
dwState = state;
vk_code = code;
}
TKeyDef::TKeyDef(const TKeyDef &t) {
if(t.uKeyDef.szKeyDef == NULL) {
uKeyDef.szKeyDef = (char *)NULL;
} else if(t.uKeyDef.op->sendstr == 0) {
uKeyDef.op = new optype;
uKeyDef.op->sendstr = 0;
uKeyDef.op->the_op = t.uKeyDef.op->the_op;
} else {
uKeyDef.szKeyDef = new char[strlen(t.uKeyDef.szKeyDef)+1];
strcpy(uKeyDef.szKeyDef, t.uKeyDef.szKeyDef);
}
dwState = t.dwState;
vk_code = t.vk_code;
}
TKeyDef::~TKeyDef() {
if(uKeyDef.szKeyDef) delete[] uKeyDef.szKeyDef;
}
char * TKeyDef::operator=(char *def) {
if(def != NULL && *def != 0) {
if(uKeyDef.szKeyDef) delete[] uKeyDef.szKeyDef;
uKeyDef.szKeyDef = new char[strlen(def)+1];
strcpy(uKeyDef.szKeyDef, def);
}
return uKeyDef.szKeyDef;
}
DWORD TKeyDef::operator=(DWORD code) {
return vk_code = code;
}
TKeyDef& TKeyDef::operator=(const TKeyDef &t) {
if(t.uKeyDef.szKeyDef) {
if(uKeyDef.szKeyDef) delete[] uKeyDef.szKeyDef;
if(t.uKeyDef.op->sendstr) {
uKeyDef.szKeyDef = new char[strlen(t.uKeyDef.szKeyDef)+1];
strcpy(uKeyDef.szKeyDef, t.uKeyDef.szKeyDef);
} else {
uKeyDef.op = new optype;
uKeyDef.op->sendstr = 0;
uKeyDef.op->the_op = t.uKeyDef.op->the_op;
}
} else {
uKeyDef.szKeyDef = (char *)NULL;
}
dwState = t.dwState;
vk_code = t.vk_code;
return *this;
}
const optype& TKeyDef::operator=(optype op) {
uKeyDef.op = new optype;
uKeyDef.op->sendstr = 0;
uKeyDef.op->the_op = op.the_op;
return *uKeyDef.op;
}
// STL requires that operators be friends rather than member functions
// (Paul Brannan 5/25/98)
#ifndef __BORLANDC__
bool operator==(const TKeyDef & t1, const TKeyDef & t2) {
return ((t1.vk_code == t2.vk_code) && (t1.dwState == t2.dwState));
}
// We need this function for compatibility with STL (Paul Brannan 5/25/98)
bool operator< (const TKeyDef& t1, const TKeyDef& t2) {
if (t1.vk_code == t2.vk_code) return t1.dwState < t2.dwState;
return t1.vk_code < t2.vk_code;
}
#else
int TKeyDef::operator==(TKeyDef & t) {
return ((vk_code == t.vk_code) && (dwState == t.dwState));
}
#endif
@@ -0,0 +1,71 @@
/////////////////////////////////////////////////////////
// TkeyDef - Key Definitions class //
// - keeped in an array container //
/////////////////////////////////////////////////////////
#ifndef __TKEYDEF_H
#define __TKEYDEF_H
#include <windows.h>
#ifndef __BORLANDC__ // Ioannou Dec. 8, 1998
// We need these for MSVC6 (Sam Robertson Oct. 8, 1998)
class TKeyDef;
bool operator==(const TKeyDef &t1, const TKeyDef &t2);
bool operator<(const TKeyDef &t1, const TKeyDef &t2);
////
#endif
// Paul Brannan Feb. 5, 1999
enum tn_ops {TN_ESCAPE, TN_SCROLLBACK, TN_DIAL, TN_PASTE, TN_NULL, TN_CR, TN_CRLF};
typedef struct {
char sendstr;
tn_ops the_op;
} optype;
union KeyDefType {
char *szKeyDef;
optype *op;
};
union KeyDefType_const {
const char *szKeyDef;
const optype *op;
};
class TKeyDef {
private:
KeyDefType uKeyDef;
DWORD vk_code;
DWORD dwState;
public:
TKeyDef();
TKeyDef(char *def, DWORD state, DWORD code);
TKeyDef(optype op, DWORD state, DWORD code);
TKeyDef(const TKeyDef &t);
char *operator=(char *def);
DWORD operator=(DWORD code);
TKeyDef& operator=(const TKeyDef &t);
const optype& operator=(optype op);
~TKeyDef();
#ifdef __BORLANDC__
int operator==(TKeyDef &t);
#else
// made these into friends for compatibility with stl
// (Paul Brannan 5/7/98)
friend bool operator==(const TKeyDef &t1, const TKeyDef &t2);
friend bool operator<(const TKeyDef &t1, const TKeyDef &t2);
#endif
const char *GetszKey() { return uKeyDef.szKeyDef; }
const KeyDefType GetKeyDef() { return uKeyDef; }
DWORD GetCodeKey() { return vk_code; }
};
#endif
@@ -0,0 +1,62 @@
///////////////////////////////////////////////////////////////////////////////
//Telnet Win32 : an ANSI telnet client.
//Copyright (C) 1998-2000 Paul Brannan
//Copyright (C) 1998 I.Ioannou
//Copyright (C) 1997 Brad Johnson
//
//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., 675 Mass Ave, Cambridge, MA 02139, USA.
//
//I.Ioannou
//[email protected]
//
///////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////
// Class TkeyMap - Key Mappings //
// - kept in an array container //
// originally part of KeyTrans.cpp //
/////////////////////////////////////////////////////////
#include "tkeymap.h"
KeyMap::KeyMap(DWORD state, DWORD code): map(0,0,sizeof(TKeyDef)),
key(NULL,state,code) {};
KeyMap::KeyMap(TKeyDef&tk):map(0,0,sizeof(TKeyDef)){
key = tk;
};
KeyMap::KeyMap(TKeyDef&tk, string& t):map(0,0,sizeof(TKeyDef)), orig(t){
key = tk;
};
int KeyMap::operator==(const KeyMap & t) const{
return key == t.key;
};
KeyMap& KeyMap::operator = (const KeyMap& t){
key = t.key;
map = t.map;
orig = t.orig;
return (*this);
};
#ifndef __BORLANDC__
bool operator<(const KeyMap &t1, const KeyMap &t2) {
return t1.key < t2.key;
}
#endif
KeyMap::~KeyMap() {
};
@@ -0,0 +1,39 @@
#ifndef __TKEYMAP_H
#define __TKEYMAP_H
#ifdef __BORLANDC__
#include <classlib\arrays.h>
#else
#include <string>
#include "stl_bids.h"
#endif
#include "tkeydef.h"
//AVS
typedef TArrayAsVector<TKeyDef> keyArray;
//AVS
// representation of keymap
struct KeyMap {
keyArray map; // keymap
string orig; // original string from .cfg file
TKeyDef key; // 'switch to' key
KeyMap(DWORD state, DWORD code);
KeyMap(): map(0,0,sizeof(TKeyDef)){};
KeyMap(TKeyDef&tk);
KeyMap(TKeyDef&tk, string&);
KeyMap(const string&t): map(0,0,sizeof(TKeyDef)), orig(t) {};
int operator==(const KeyMap & t) const;
KeyMap& operator = (const KeyMap& t);
#ifndef __BORLANDC__
// The STL needs this (Paul Brannan 5/25/98)
friend bool operator<(const KeyMap &t1, const KeyMap &t2);
#endif
~KeyMap();
};
#endif
@@ -0,0 +1,773 @@
///////////////////////////////////////////////////////////////////////////////
//Telnet Win32 : an ANSI telnet client.
//Copyright (C) 1998-2000 Paul Brannan
//Copyright (C) 1998 I.Ioannou
//Copyright (C) 1997 Brad Johnson
//
//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., 675 Mass Ave, Cambridge, MA 02139, USA.
//
//I.Ioannou
//[email protected]
//
///////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////
// Class TMapLoader - Key/Character Mappings //
// - Loads from telnet.cfg //
// originally part of KeyTrans.cpp //
/////////////////////////////////////////////////////////
#ifdef __BORLANDC__
#include <fstream.h>
#else
#include <string>
#include <fstream>
#endif
#include "tmapldr.h"
#include "tnerror.h"
#include "tnconfig.h"
// It's probably a good idea to turn off the "identifier was truncated" warning
// in MSVC (Paul Brannan 5/25/98)
#ifdef _MSC_VER
#pragma warning(disable: 4786)
#endif
// AVS
// skip inline comments, empty lines
static char * getline(istream& i, char* buf, int size){
int len = 0;
while (1) {
memset(buf,0,size);
if (i.eof()) break;
i.getline(buf,size,'\n');
while (buf[len]) {
if ( /*(buf[len]>=0) &&*/ buf[len]< ' ' ) buf[len] = ' ';
len++;
};
len = 0;
// not so fast, but work ;)
while ( buf[len] ) {
if ( (buf[len] == ' ') && (buf[len+1] == ' ')) {
memmove(buf+len, buf+len+1, strlen(buf+len));
} else len++;
};
if (buf[0] == ' ') memmove(buf, buf+1, size-1);
// empty or comment
if ((buf[0]==0)||(buf[0]==';')) continue;
len = 0; // look for comment like this one
while (buf[len])
if ((buf[len] == '/') && (buf[len+1] == '/')) buf[len] = 0;
else len++;
if (len && (buf[len-1] == ' ')) {
len--;
buf[len]=0;
};
// in case for comment like this one (in line just a comment)
if (buf[0]==0) continue;
break;
};
return (buf);
};
//AVS
// use string as FIFO queue for lines
static int getline(string&str, char* buf, size_t sz) {
if ( !str.length() ) return 0;
const char * p = strchr(str.c_str(),'\n');
unsigned int len; // Changed to unsigned (Paul Brannan 6/23/98)
if ( p==NULL )
len = str.length();
else
len = p - str.c_str();
len = len<sz?len:sz-1;
strncpy(buf,str.c_str(), len);
buf[len]=0;
// DJGPP also uses erase rather than remove (Paul Brannan 6/23/98)
#ifndef __BORLANDC__
str.erase(0, len + 1);
#else
str.remove(0,len+1);
#endif
return 1;
};
//AVS
// parse \nnn and \Xhh
static int getbyte(const char*str) {
unsigned char retval = 0;
int base = 10;
int readed = 0;
if ( (*str == 'x') || (*str == 'X') ) {
base = 16;
readed++;
};
while (readed != 3 && str[readed]) {
unsigned char ch = toupper(str[readed]);
if ( isdigit(ch) ) {
retval = retval*base + (ch -'0');
} else if (base == 16 && ch >= 'A' && ch <= 'F') {
retval = retval*base + (ch-'A'+10);
} else {
return -1;
};
readed++;
};
// Ioannou: If we discard the 0x00 we can't undefine a key !!!
// if ( retval == 0 ) {
// return -1;
// };
return retval;
};
//AVS
// a little optimization
DWORD Fix_ControlKeyState(char * Next_Token) {
if (stricmp(Next_Token, "RIGHT_ALT" ) == 0) return RIGHT_ALT_PRESSED;
if (stricmp(Next_Token, "LEFT_ALT" ) == 0) return LEFT_ALT_PRESSED;
if (stricmp(Next_Token, "RIGHT_CTRL") == 0) return RIGHT_CTRL_PRESSED;
if (stricmp(Next_Token, "LEFT_CTRL" ) == 0) return LEFT_CTRL_PRESSED;
if (stricmp(Next_Token, "SHIFT" ) == 0) return SHIFT_PRESSED;
if (stricmp(Next_Token, "NUMLOCK" ) == 0) return NUMLOCK_ON;
if (stricmp(Next_Token, "SCROLLLOCK") == 0) return SCROLLLOCK_ON;
if (stricmp(Next_Token, "CAPSLOCK" ) == 0) return CAPSLOCK_ON;
if (stricmp(Next_Token, "ENHANCED" ) == 0) return ENHANCED_KEY;
// Paul Brannan 5/27/98
if (stricmp(Next_Token, "APP_KEY" ) == 0) return APP_KEY;
// Paul Brannan 6/28/98
if (stricmp(Next_Token, "APP2_KEY" ) == 0) return APP2_KEY;
// Paul Brannan 8/28/98
if (stricmp(Next_Token, "APP3_KEY" ) == 0) return APP3_KEY;
// Paul Brannan 12/9/98
if (stricmp(Next_Token, "APP4_KEY" ) == 0) return APP4_KEY;
return 0;
}
// AVS
// rewrited to suppert \xhh notation, a little optimized
char* Fix_Tok(char * tok) {
static char s[256];
int i,j,n;
// setmem is nonstandard; memset is standard (Paul Brannan 5/25/98)
memset(s, 0, 256);
// setmem(s, 256, 0);
i = j = n = 0;
if ( tok != NULL ) {
for ( ; tok[i] != 0; ) {
switch ( tok[i] ) {
case '\\' :
switch ( tok[i+1] ) {
case '\\':
s[j++] = '\\';
i += 2;
break;
default:
n = getbyte(tok+i+1);
if ( n < 0 )
s[j++] = tok[i++];
else {
s[j++]=n;
i += 4;
} ;
break;
};
break;
case '^' :
if ( tok[i+1] >= '@' ) {
s[j++] = tok[i+1] - '@';
i += 2;
break;
}
default :
s[j++] = tok[i++];
}
}
}
return s;
};
// AVS
// perform 'normalization' for lines like [some text], and some checks
// maybe it will be done faster - but no time for it
int normalizeSplitter(string& buf) {
if ( buf.length() <= 2 ) return 0;
if ( buf[0] == '[' && buf[buf.length()-1] == ']' ) {
while ( buf[1] == ' ' )
// DJGPP also uses erase rather than remove (Paul Brannan 6/23/98)
#ifndef __BORLANDC__
buf.erase(1, 1);
#else
buf.remove(1,1);
#endif
while ( buf[buf.length()-2] == ' ' )
// Paul Brannan 6/23/98
#ifndef __BORLANDC__
buf.erase(buf.length()-2,1);
#else
buf.remove(buf.length()-2,1);
#endif
return 1;
}
return 0;
};
// AVS
// looking for part in string array, see Load(..) for more info
int TMapLoader::LookForPart(stringArray& sa, const char* partType, const char* partName) {
if ( !sa.IsEmpty() ) {
string cmpbuf("[");
cmpbuf += partType;
cmpbuf += " ";
cmpbuf += partName;
cmpbuf += "]";
normalizeSplitter(cmpbuf); // if no parttype, [global] for example
int max = sa.GetItemsInContainer();
for ( int i = 0; i<max; i++ )
// I found some strange behavior if strnicmp was used here
if (strnicmp(cmpbuf.c_str(),sa[i].c_str(),cmpbuf.length()) == 0)
return i;
};
return INT_MAX;
};
// AVS
// load globals to 'globals'
// in buf must be a [global] part of input file
int TMapLoader::LoadGlobal(string& buf) {
char wbuf[128];
while ( buf.length() ) {
wbuf[0]=0;
if (!getline(buf,wbuf,sizeof(wbuf))) break;
if ( wbuf[0]==0 ) break;
char* Name = strtok(wbuf, TOKEN_DELIMITERS);
if ( stricmp(Name, "[global]")==0 ) continue;
char* Value = strtok(NULL, TOKEN_DELIMITERS);
if ( Value == NULL ) {
// cerr << "[global] -> no value for " << Name << endl;
printm(0, FALSE, MSG_KEYNOVAL, Name);
continue;
};
int val = atoi(Value);
if ( val > 0 && val <= 0xff ) {
if ( !KeyTrans.AddGlobalDef(val, Name)) return 0;
}
else {
// cerr << "[global] -> bad value for " << Name << endl;
printm(0, FALSE, MSG_KEYBADVAL, Name);
continue;
};
};
return 1;
};
// AVS
// perform parsing of strings like 'VK_CODE shifts text'
// returns text on success
char* TMapLoader::ParseKeyDef(const char* buf, WORD& vk_code, DWORD& control) {
char wbuf[256];
strcpy(wbuf,buf);
char* ptr = strtok(wbuf, TOKEN_DELIMITERS);
if ( ptr == NULL ) return NULL;
int i = KeyTrans.LookOnGlobal(ptr);
if ( i == INT_MAX ) return NULL;
vk_code = KeyTrans.GetGlobalCode(i);
control = 0;
DWORD st;
while (1) {
ptr = strtok(NULL, TOKEN_DELIMITERS);
if ((ptr == NULL) || ((st = Fix_ControlKeyState(ptr)) == 0)) break;
control |= st;
};
if ( ptr == NULL ) return NULL;
return Fix_Tok(ptr);
};
// AVS
// load keymap to current map
// be aware - buf must passed by value, its destroyed
int TMapLoader::LoadKeyMap(string buf) {
char wbuf[128];
WORD vk_code;
DWORD control;
int i;
// Paul Brannan Feb. 22, 1999
strcpy(wbuf, "VK_");
wbuf[4] = 0;
wbuf[3] = ini.get_escape_key();
i = KeyTrans.LookOnGlobal(wbuf);
if (i != INT_MAX) {
KeyTrans.AddKeyDef(KeyTrans.GetGlobalCode(i), RIGHT_ALT_PRESSED, TN_ESCAPE);
KeyTrans.AddKeyDef(KeyTrans.GetGlobalCode(i), LEFT_ALT_PRESSED, TN_ESCAPE);
}
wbuf[3] = ini.get_scrollback_key();
i = KeyTrans.LookOnGlobal(wbuf);
if (i != INT_MAX) {
KeyTrans.AddKeyDef(KeyTrans.GetGlobalCode(i), RIGHT_ALT_PRESSED, TN_SCROLLBACK);
KeyTrans.AddKeyDef(KeyTrans.GetGlobalCode(i), LEFT_ALT_PRESSED, TN_SCROLLBACK);
}
wbuf[3] = ini.get_dial_key();
i = KeyTrans.LookOnGlobal(wbuf);
if (i != INT_MAX) {
KeyTrans.AddKeyDef(KeyTrans.GetGlobalCode(i), RIGHT_ALT_PRESSED, TN_DIAL);
KeyTrans.AddKeyDef(KeyTrans.GetGlobalCode(i), LEFT_ALT_PRESSED, TN_DIAL);
}
KeyTrans.AddKeyDef(VK_INSERT, SHIFT_PRESSED, TN_PASTE);
while ( buf.length() ) {
wbuf[0] = 0;
if (!getline(buf,wbuf,sizeof(wbuf))) break;
if ( wbuf[0]==0 ) break;
if ( strnicmp(wbuf,"[keymap",7)==0 ) continue;
char * keydef = ParseKeyDef(wbuf,vk_code,control);
if ( keydef != NULL ) {
// Check to see if keydef is a "special" code (Paul Brannan 3/29/00)
if(!strnicmp(keydef, "\\tn_escape", strlen("\\tn_escape"))) {
if(!KeyTrans.AddKeyDef(vk_code, control, TN_ESCAPE)) return 0;
} else if(!strnicmp(keydef, "\\tn_scrollback", strlen("\\tn_scrollback"))) {
if(!KeyTrans.AddKeyDef(vk_code, control, TN_SCROLLBACK)) return 0;
} else if(!strnicmp(keydef, "\\tn_dial", strlen("\\tn_dial"))) {
if(!KeyTrans.AddKeyDef(vk_code, control, TN_DIAL)) return 0;
} else if(!strnicmp(keydef, "\\tn_paste", strlen("\\tn_paste"))) {
if(!KeyTrans.AddKeyDef(vk_code, control, TN_PASTE)) return 0;
} else if(!strnicmp(keydef, "\\tn_null", strlen("\\tn_null"))) {
if(!KeyTrans.AddKeyDef(vk_code, control, TN_NULL)) return 0;
} else if(!strnicmp(keydef, "\\tn_cr", strlen("\\tn_cr"))) {
if(!KeyTrans.AddKeyDef(vk_code, control, TN_CR)) return 0;
} else if(!strnicmp(keydef, "\\tn_crlf", strlen("\\tn_crlf"))) {
if(!KeyTrans.AddKeyDef(vk_code, control, TN_CRLF)) return 0;
} else
if(!KeyTrans.AddKeyDef(vk_code,control,keydef)) return 0;
// else DeleteKeyDef() ???? - I'm not sure...
}
};
return 1;
};
// AVS
// load [charmap ...] part to xlat
int TMapLoader::LoadCharMap(string buf) {
char wbuf[128];
char charmapname[128];
charmapname[0] = 0;
// xlat.init(); now it done by KeyTranslator::Load()
while ( buf.length() ) {
wbuf[0]=0;
if (!getline(buf,wbuf,sizeof(wbuf))) break;
if ( wbuf[0]==0 ) break;
if ( strnicmp(wbuf,"[charmap",8)==0 ) {
strcpy(charmapname,wbuf);
continue;
};
char * host = strtok(wbuf, " ");
char * console = strtok(NULL, " ");
int bHost;
int bConsole;
if ( host == NULL || console == NULL ) {
// cerr << charmapname << " -> Bad structure" << endl;
printm(0, FALSE, MSG_KEYBADSTRUCT, charmapname);
return 0;
};
if ( strlen(host) > 1 && host[0] == '\\' )
bHost = getbyte(host+1);
else
bHost = (unsigned char)host[0];
if ( strlen(console) > 1 && console[0] == '\\' )
bConsole = getbyte(console+1);
else
bConsole = (unsigned char)console[0];
if ( bHost <= 0 || bConsole <= 0 ) {
// cerr << charmapname << " -> Bad chars? "
// << host << " -> " << console << endl;
printm(0, FALSE, MSG_KEYBADCHARS, charmapname, host, console);
return 0;
};
// xlat.table[bHost] = bConsole;
Charmap.modmap(bHost, 'B', bConsole);
};
return (Charmap.enabled = 1);
return 1;
};
// AVS
// ignore long comment [comment] ... [end comment]
// recursive!
int getLongComment(istream& is, char* wbuf, size_t sz) {
int bufLen;
while ( is ) {
wbuf[0] = 0;
getline(is, wbuf, sz);
if ( wbuf[0]==0 ) return 1;
bufLen = strlen(wbuf);
if ( wbuf[0] == '[' && wbuf[bufLen-1] == ']' ) {
string temps(wbuf);
if (!normalizeSplitter(temps)) {
// cerr << "Unexpected line '" << temps << "'\n";
printm(0, FALSE, MSG_KEYUNEXPLINE, temps.c_str());
return 0;
};
if ( stricmp(temps.c_str(),"[comment]") == 0 ) {
// do recursive call
if ( !getLongComment(is, wbuf, sz) ) return 0;
continue;
};
if ( stricmp(temps.c_str(),"[end comment]") == 0 ) return 1;
};
};
// we get a warning if we don't put a return here (Paul Brannan 5/25/98)
return 0;
};
// AVS
// completelly rewrited to support new conceptions
int TMapLoader::Load(const char * filename, const char * szActiveEmul) {
char buf[256];
int bufLen;
ifstream inpfile(filename);
KeyTrans.DeleteAllDefs();
Charmap.init();
// it is an array for store [...] ... [end ...] parts from file
stringArray SA(0,0,sizeof(string));
int AllOk = 0;
while ( inpfile ) {
getline(inpfile, buf, 255);
bufLen = strlen(buf);
if ( !bufLen ) continue;
if ( buf[0] == '[' && buf[bufLen-1] == ']' ) {
// is a part splitter [...]
string temps(buf);
if (!normalizeSplitter(temps)) {
printm(0, FALSE, MSG_KEYUNEXPLINE, temps.c_str());
AllOk = 0;
break;
};
// if a comment
if ( stricmp(temps.c_str(),"[comment]") == 0 ) {
#ifdef KEYDEBUG
printit(temps.c_str());
#endif
if ( !getLongComment(inpfile, buf, sizeof(buf)) ) {
printm(0, FALSE, MSG_KEYUNEXPEOF);
break;
};
#ifdef KEYDEBUG
printit("\r \r");
#endif
continue;
};
string back = temps;
// prepare line for make it as [end ...]
// and check it
if ( strnicmp(back.c_str(), "[global]", 8) == 0 ) {} // do nothing
else if ( strnicmp(back.c_str(), "[keymap", 7) == 0 ) {
// DJGPP also uses erase rather than remove (Paul Brannan 6/23/98)
#ifndef __BORLANDC__
back.erase(7);
#else
back.remove(7);
#endif
back += "]";
}
else if ( strnicmp(back.c_str(), "[charmap", 8) == 0 ) {
// Paul Brannan 6/23/98
#ifndef __BORLANDC__
back.erase(8);
#else
back.remove(8);
#endif
back += "]";
}
else if ( strnicmp(back.c_str(), "[config", 7) == 0 ) {
// Paul Brannan 6/23/98
#ifndef __BORLANDC__
back.erase(7);
#else
back.remove(7);
#endif
back += "]";
}
else {
// cerr << "Unexpected token " << back << endl;
printm(0, FALSE, MSG_KEYUNEXPTOK, back.c_str());
break;
};
back.insert(1,"END "); // now it looks like [END ...]
#ifdef KEYDEBUG
printit(temps.c_str());
#endif
int ok = 0;
// fetch it to temps
while ( 1 ) {
getline(inpfile, buf, sizeof(buf));
bufLen = strlen(buf);
if ( !bufLen ) break;
if ( buf[0] == '[' && buf[bufLen-1] == ']' ) {
string t(buf);
if ( !normalizeSplitter(t) ) break;
if ( stricmp(t.c_str(),back.c_str()) == 0 ) {
ok = 1;
break;
};
// AVS 31.12.97 fix [comment] block inside another block
if ( stricmp(t.c_str(),"[comment]") == 0 &&
getLongComment(inpfile, buf, sizeof(buf)) ) continue;
break;
};
temps += "\n";
temps += buf;
};
if ( !ok ) {
// cerr << "Unexpected end of file or token" << endl;
printm(0, FALSE, MSG_KEYUNEXP);
AllOk = 0;
break;
};
#ifdef KEYDEBUG
printit("\r \r");
#endif
AllOk = SA.Add(temps);;
if ( !AllOk ) break;
} else {
// cerr << "Unexpected line '" << buf << "'\n";
printm(0, FALSE, MSG_KEYUNEXPLINE, buf);
AllOk = 0;
break;
};
};
inpfile.close();
if ( !AllOk ) return 0;
// now all file are in SA, comments are stripped
int i = LookForPart(SA, "global", "");
if ( i == INT_MAX ) {
// cerr << "No [GLOBAL] definition!" << endl;
printm(0, FALSE, MSG_KEYNOGLOBAL);
return 0;
};
if ( !LoadGlobal(SA[i]) ) {
return 0;
};
// look for need configuration
i = LookForPart(SA, "config", szActiveEmul);
if ( i == INT_MAX ) {
// cerr << "No [CONFIG " << szActiveEmul << "]\n";
printm(0, FALSE, MSG_KEYNOCONFIG, szActiveEmul);
return 0;
};
// cerr << "use configuration: " << szActiveEmul << endl;
printm(0, FALSE, MSG_KEYUSECONFIG, szActiveEmul);
BOOL hadKeys = FALSE;
string config = SA[i];
// parse it
while ( config.length() ) {
buf[0] = 0;
getline(config,buf,sizeof(buf));
bufLen = strlen(buf);
if ( !bufLen || (buf[0] == '[' && buf[bufLen-1] == ']') ) continue;
if ( strnicmp(buf,"keymap",6) == 0 ) {
string orig(buf);
printit("\t"); printit(buf); printit("\n");
char * mapdef = strtok(buf,":");
char * switchKey = strtok(NULL,"\n");
if ( !KeyTrans.mapArray.IsEmpty() && switchKey == NULL ) {
// cerr << "no switch Key for '" << mapdef
// << "'" << endl;
printm(0, FALSE, MSG_KEYNOSWKEY, mapdef);
break;
};
if ( KeyTrans.mapArray.IsEmpty() ) {
if ( switchKey != NULL ) { // create default keymap
// cerr << "You cannot define switch key for default keymap -> ignored"
// << endl;
printm(0, FALSE, MSG_KEYCANNOTDEF);
};
TKeyDef empty;
KeyTrans.mapArray.Add(KeyMap(string(mapdef)));
KeyTrans.switchMap(empty); // set it as current keymap
KeyTrans.mainKeyMap = KeyTrans.currentKeyMap;
}
else {
string keydef(switchKey);
keydef += " !*!*!*"; // just for check
WORD vk_code;
DWORD control;
switchKey = ParseKeyDef(keydef.c_str(),vk_code,control);
if ( switchKey != NULL ) {
TKeyDef swi(NULL,control,vk_code);
if ( KeyTrans.switchMap(swi) > 0 ) {
// cerr << "Duplicate switching key\n";
printm(0, FALSE, MSG_KEYDUPSWKEY);
break;
};
KeyTrans.mapArray.Add(KeyMap(swi, orig));
KeyTrans.switchMap(swi); // set it as current keymap
}
};
mapdef+=7; // 'keymap '
// now load defined keymaps to current
while ((mapdef != NULL)&&
(mapdef = strtok(mapdef,TOKEN_DELIMITERS)) != NULL ) {
i = LookForPart(SA,"keymap",mapdef);
if ( i == INT_MAX ) {
// cerr << "Unknown KEYMAP " << mapdef << endl;
printm(0, FALSE, MSG_KEYUNKNOWNMAP, mapdef);
} else {
mapdef = strtok(NULL,"\n"); // strtok is used in LoadKeyMap
// so - save pointer!
hadKeys = LoadKeyMap(SA[i]); // load it
};
};
}
else if ( strnicmp(buf,"charmap",7) == 0 ) {
printit("\t"); printit(buf); printit("\n");
char * mapdef = buf + 8;// 'charmap '
int SuccesLoaded = 0;
// now load defined charmaps to current
while ((mapdef != NULL)&&
(mapdef = strtok(mapdef,TOKEN_DELIMITERS)) != NULL ) {
i = LookForPart(SA,"charmap",mapdef);
if ( i == INT_MAX ) {
// cerr << "Unknown KEYMAP " << mapdef << endl;
printm(0, FALSE, MSG_KEYUNKNOWNMAP, mapdef);
} else {
mapdef = strtok(NULL,"\n"); // strtok is used in LoadKeyMap
// so - save pointer!
if (LoadCharMap(SA[i])) // load it
SuccesLoaded++;
};
};
if (!SuccesLoaded) {
// cerr << "No charmaps loaded\n";
printm(0, FALSE, MSG_KEYNOCHARMAPS);
Charmap.init();
};
/* strtok(buf," ");
char* name = strtok(NULL," ");
if ( name == NULL ) {
cerr << "No name for CHARMAP" << endl;
} else {
i = LookForPart(SA,"charmap", name);
if ( i == INT_MAX ) {
cerr << "Unknown CHARMAP " << name << endl;
} else {
LoadCharMap(SA[i]);
};
};
*/
}
else {
// cerr << "unexpected token in " << szActiveEmul << endl;
printm(0, FALSE, MSG_KEYUNEXPTOKIN, szActiveEmul);
}
}
if ( hadKeys) {
TKeyDef empty;
KeyTrans.switchMap(empty); // switch to default
KeyTrans.mainKeyMap = KeyTrans.currentKeyMap; // save it's number
// cerr << "There are " << (KeyTrans.mapArray.GetItemsInContainer()) << " maps\n";
char s[12]; // good enough for a long int (32-bit)
itoa(KeyTrans.mapArray.GetItemsInContainer(), s, 10);
printm(0, FALSE, MSG_KEYNUMMAPS, s);
return 1;
};
return 0;
}
void TMapLoader::Display() {
int max = KeyTrans.mapArray.GetItemsInContainer();
if (max == 0) {
printm(0, FALSE, MSG_KEYNOKEYMAPS);
return;
};
for ( int i = 0; i < max; i++ ) {
char buf[20];
itoa(i,buf,10);
printit("\t");
// Ioannou : we can show the current
if (KeyTrans.currentKeyMap == i)
printit("*");
else
printit(" ");
strcat(buf," ");
printit(buf);
char * msg = new char [KeyTrans.mapArray[i].orig.length()+1];
strcpy(msg,KeyTrans.mapArray[i].orig.c_str());
printit(msg);
delete[] msg;
printit("\n");
};
};
@@ -0,0 +1,105 @@
///////////////////////////////////////////////////////////////////
// //
// File format : //
// //
// Comments with a ; in column 1 //
// Empty Lines ignored //
// The words are separated by a space, a tab, or a plus ("+") //
// //
// First a [GLOBAL] section : //
// [GLOBAL] //
// VK_F1 112 //
// . //
// . //
// [END_GLOBAL] //
// //
// The GLOBAL section defines the names of the keys //
// and the virtual key code they have. //
// If you repeat a name you'll overwrite the code. //
// You can name the keys anything you like //
// The Virtual key nymber must be in Decimal //
// After the number you can put anything : it is ignored //
// Here you must put ALL the keys you'll use in the //
// other sections. //
// //
// Then the emulations sections : //
// //
// [SCO_ANSI] //
// //
// VK_F1 \027[M or //
// VK_F1 ^[[M or //
// VK_F1 SHIFT ^[[W etc //
// . //
// . //
// [SCO_ANSI_END] //
// //
// There are three parts : //
// a) the key name //
// b) the shift state //
// here you put compination of the words : //
// //
// RIGHT_ALT //
// LEFT_ALT //
// RIGHT_CTRL //
// LEFT_CTRL //
// SHIFT //
// NUMLOCK //
// SCROLLLOCK //
// CAPSLOCK //
// ENHANCED //
// APP_KEY //
// c) the assigned string : //
// you can use the ^ for esc (^[ = 0x1b) //
// \ and a three digit decimal number //
// (\027) //
// You can't use the NULL !!! //
// Also (for the moment) you can't use spaces //
// in the string : everything after the 3rd word is //
// ignored - use unsderscore instead. //
// //
// for example : //
// //
// VK_F4 SHIFT+LEFT_ALT \0274m^[[M = 0x1b 4 m 0x1b [ M //
// VK_F1 RIGHT_CTRL This_is_ctrl_f1 //
// //
// You may have as many sections as you like //
// If you repeat any section (even the GLOBAL) you'll overwrite //
// the common parts. //
// //
///////////////////////////////////////////////////////////////////
#ifndef __TLOADMAP_H
#define __TLOADMAP_H
#include "keytrans.h"
#include "tcharmap.h"
// AVS
typedef TArrayAsVector<string> stringArray;
class TMapLoader {
public:
TMapLoader(KeyTranslator &RefKeyTrans, TCharmap &RefCharmap):
KeyTrans(RefKeyTrans), Charmap(RefCharmap) {}
~TMapLoader() {}
// If called more than once the new map replaces the old one.
// load with a different KeysetName to change keysets
// Return 0 on error
int Load(const char * filename, const char * szKeysetName);
void Display();
private:
KeyTranslator &KeyTrans;
TCharmap &Charmap;
int LookForPart(stringArray& sa, const char* partType, const char* partName);
char* ParseKeyDef(const char* buf, WORD& vk_code, DWORD& control);
int LoadGlobal(string& buf);
int LoadKeyMap(string buf);
int LoadCharMap(string buf);
};
#endif
@@ -0,0 +1,210 @@
///////////////////////////////////////////////////////////////////////////////
//Telnet Win32 : an ANSI telnet client.
//Copyright (C) 1998 Paul Brannan
//Copyright (C) 1998 I.Ioannou
//Copyright (C) 1997 Brad Johnson
//
//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., 675 Mass Ave, Cambridge, MA 02139, USA.
//
//I.Ioannou
//[email protected]
//
///////////////////////////////////////////////////////////////////////////
// TMouse.cpp
// A simple class for handling mouse events
// Written by Paul Brannan <[email protected]>
// Last modified August 30, 1998
#include "tmouse.h"
#include "tconsole.h"
TMouse::TMouse(Tnclip &RefClipboard): Clipboard(RefClipboard) {
hConsole = GetStdHandle(STD_INPUT_HANDLE);
hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
}
TMouse::~TMouse() {
}
void TMouse::get_coords(COORD *start_coords, COORD *end_coords,
COORD *first_coords, COORD *last_coords) {
if(end_coords->Y < start_coords->Y ||
(end_coords->Y == start_coords->Y && end_coords->X < start_coords->X))
{
*first_coords = *end_coords;
*last_coords = *start_coords;
} else {
*first_coords = *start_coords;
*last_coords = *end_coords;
}
last_coords->X++;
}
void TMouse::doMouse_init() {
GetConsoleScreenBufferInfo(hStdout, &ConsoleInfo);
chiBuffer = newBuffer();
saveScreen(chiBuffer);
}
void TMouse::doMouse_cleanup() {
restoreScreen(chiBuffer);
delete[] chiBuffer;
}
void TMouse::move_mouse(COORD start_coords, COORD end_coords) {
COORD screen_start = {0, 0};
COORD first_coords, last_coords;
DWORD Result;
FillConsoleOutputAttribute(hStdout, normal,
ConsoleInfo.dwSize.X * ConsoleInfo.dwSize.Y, screen_start, &Result);
get_coords(&start_coords, &end_coords, &first_coords, &last_coords);
FillConsoleOutputAttribute(hStdout, inverse, ConsoleInfo.dwSize.X *
(last_coords.Y - first_coords.Y) + (last_coords.X - first_coords.X),
first_coords, &Result);
}
void TMouse::doClip(COORD start_coords, COORD end_coords) {
// COORD screen_start = {0, 0};
COORD first_coords, last_coords;
DWORD Result;
get_coords(&start_coords, &end_coords, &first_coords, &last_coords);
// Allocate the minimal size buffer
int data_size = 3 + ConsoleInfo.dwSize.X *
(last_coords.Y - first_coords.Y) + (last_coords.X - first_coords.X);
HGLOBAL clipboard_data = GlobalAlloc(GMEM_MOVEABLE + GMEM_DDESHARE,
data_size);
LPVOID mem_ptr = GlobalLock(clipboard_data);
// Reset data_size so we can count the actual data size
data_size = 0;
// Read the console, put carriage returns at the end of each line if
// reading more than one line (Paul Brannan 9/17/98)
for(int j = first_coords.Y; j <= last_coords.Y; j++) {
// Read line at (0,j)
COORD coords;
coords.X = 0;
coords.Y = j;
int length = ConsoleInfo.dwSize.X;
if(j == first_coords.Y) {
coords.X = first_coords.X;
length = ConsoleInfo.dwSize.X - first_coords.X;
} else {
// Add a carriage return to the end of the previous line
*((char *)mem_ptr + data_size++) = '\r';
*((char *)mem_ptr + data_size++) = '\n';
}
if(j == last_coords.Y) {
length -= (ConsoleInfo.dwSize.X - last_coords.X);
}
// Read the next line
ReadConsoleOutputCharacter(hStdout, (LPTSTR)((char *)mem_ptr +
data_size), length, coords, &Result);
data_size += Result;
// Strip the spaces at the end of the line
if((j != last_coords.Y) && (first_coords.Y != last_coords.Y))
while(*((char *)mem_ptr + data_size - 1) == ' ') data_size--;
}
if(first_coords.Y != last_coords.Y) {
// Add a carriage return to the end of the last line
*((char *)mem_ptr + data_size++) = '\r';
*((char *)mem_ptr + data_size++) = '\n';
}
*((char *)mem_ptr + data_size) = 0;
GlobalUnlock(clipboard_data);
Clipboard.Copy(clipboard_data);
}
void TMouse::doMouse() {
INPUT_RECORD InputRecord;
DWORD Result;
InputRecord.EventType = KEY_EVENT; // just in case
while(InputRecord.EventType != MOUSE_EVENT) {
if (!ReadConsoleInput(hConsole, &InputRecord, 1, &Result))
return; // uh oh! we don't know the starting coordinates!
}
if(InputRecord.Event.MouseEvent.dwButtonState == 0) return;
if(!(InputRecord.Event.MouseEvent.dwButtonState &
FROM_LEFT_1ST_BUTTON_PRESSED)) {
Clipboard.Paste();
return;
}
COORD screen_start = {0, 0};
COORD start_coords = InputRecord.Event.MouseEvent.dwMousePosition;
COORD end_coords = start_coords;
BOOL done = FALSE;
// init vars
doMouse_init();
int normal_bg = ini.get_normal_bg();
int normal_fg = ini.get_normal_fg();
if(normal_bg == -1) normal_bg = 0; // FIX ME!! This is just a hack
if(normal_fg == -1) normal_fg = 7;
normal = (normal_bg << 4) | normal_fg;
inverse = (normal_fg << 4) | normal_bg;
// make screen all one attribute
FillConsoleOutputAttribute(hStdout, normal, ConsoleInfo.dwSize.X *
ConsoleInfo.dwSize.Y, screen_start, &Result);
while(!done) {
switch (InputRecord.EventType) {
case MOUSE_EVENT:
switch(InputRecord.Event.MouseEvent.dwEventFlags) {
case 0: // only copy if the mouse button has been released
if(!InputRecord.Event.MouseEvent.dwButtonState) {
doClip(start_coords, end_coords);
done = TRUE;
}
break;
case MOUSE_MOVED:
end_coords = InputRecord.Event.MouseEvent.dwMousePosition;
move_mouse(start_coords, end_coords);
break;
}
break;
// If we are changing focus, we don't want to highlight anything
// (Paul Brannan 9/2/98)
case FOCUS_EVENT:
return;
}
WaitForSingleObject(hConsole, INFINITE);
if (!ReadConsoleInput(hConsole, &InputRecord, 1, &Result))
done = TRUE;
}
doMouse_cleanup();
}
void TMouse::scrollMouse() {
doMouse();
}
@@ -0,0 +1,29 @@
#ifndef __TMOUSE_H
#define __TMOUSE_H
#include "tnclip.h"
#include <windows.h>
class TMouse {
private:
int normal, inverse;
HANDLE hConsole, hStdout;
CHAR_INFO *chiBuffer;
CONSOLE_SCREEN_BUFFER_INFO ConsoleInfo;
Tnclip &Clipboard;
void get_coords(COORD *start_coords, COORD *end_coords,
COORD *first_coords, COORD *last_coords);
void doMouse_init();
void doMouse_cleanup();
void move_mouse(COORD start_coords, COORD end_coords);
void doClip(COORD start_coords, COORD end_coords);
public:
void doMouse();
void scrollMouse();
TMouse(Tnclip &RefClipboard);
~TMouse();
};
#endif
@@ -0,0 +1,398 @@
///////////////////////////////////////////////////////////////////////////////
//Telnet Win32 : an ANSI telnet client.
//Copyright (C) 1998 Paul Brannan
//Copyright (C) 1998 I.Ioannou
//Copyright (C) 1997 Brad Johnson
//
//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., 675 Mass Ave, Cambridge, MA 02139, USA.
//
//I.Ioannou
//[email protected]
//
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
//
// Module: tnclass.cpp
//
// Contents: telnet object definition
//
// Product: telnet
//
// Revisions: August 30, 1998 Paul Brannan <[email protected]>
// July 12, 1998 Paul Brannan
// June 15, 1998 Paul Brannan
// May 14, 1998 Paul Brannan
// 5.April.1997 [email protected]
// 14.Sept.1996 [email protected]
// Version 2.0
//
///////////////////////////////////////////////////////////////////////////////
#include <stdlib.h>
#include <string.h>
#include "tnclass.h"
#include "tnmisc.h"
// Mingw32 needs these (Paul Brannan 9/4/98)
#ifndef ICON_SMALL
#define ICON_SMALL 0
#endif
#ifndef ICON_BIG
#define ICON_BIG 1
#endif
// Ioannou Dec. 8, 1998
#ifdef __BORLANDC__
#ifndef WM_SETICON
#define WM_SETICON STM_SETICON
#endif
#endif
// DoInit() - performs initialization that is common to both the
// constructors (Paul Brannan 6/15/98)
void Telnet::DoInit() {
Socket = INVALID_SOCKET;
bConnected = 0;
bNetPaused = 1;
bNetFinished = 1;
bNetFinish = 0;
hThread = 0; // Sam Robertson 12/7/98
hProcess = 0;
WSADATA WsaData;
// Set the title
telSetConsoleTitle("No Connection");
// Change the icon
hConsoleWindow = TelnetGetConsoleWindow();
iconChange = SetIcon(hConsoleWindow, 0, &oldBIcon, &oldSIcon, ini.get_startdir());
if (WSAStartup(MAKEWORD(1, 1), &WsaData)) {
DWORD dwLastError = GetLastError();
printm(0, FALSE, MSG_ERROR, "WSAStartup()");
printm(0, TRUE, dwLastError);
bWinsockUp = 0;
return;
}
bWinsockUp = 1;
// Get keyfile (Paul Brannan 5/12/98)
const char *keyfile = ini.get_keyfile();
// This should be changed later to use the Tnerror routines
// This has been done (Paul Brannan 6/5/98)
if(LoadKeyMap( keyfile, ini.get_default_config()) != 1)
// printf("Error loading keymap.\n");
printm(0, FALSE, MSG_ERRKEYMAP);
}
Telnet::Telnet():
MapLoader(KeyTrans, Charmap),
Console(GetStdHandle(STD_OUTPUT_HANDLE)),
TelHandler(Network, Console, Parser),
ThreadParams(TelHandler),
Clipboard(TelnetGetConsoleWindow(), Network),
Mouse(Clipboard),
Scroller(Mouse, ini.get_scroll_size()),
Parser(Console, KeyTrans, Scroller, Network, Charmap) {
DoInit();
}
Telnet::Telnet(const char * szHost1, const char *strPort1):
MapLoader(KeyTrans, Charmap),
Console(GetStdHandle(STD_OUTPUT_HANDLE)),
TelHandler(Network, Console, Parser),
ThreadParams(TelHandler),
Clipboard(TelnetGetConsoleWindow(), Network),
Mouse(Clipboard),
Scroller(Mouse, ini.get_scroll_size()),
Parser(Console, KeyTrans, Scroller, Network, Charmap) {
DoInit();
Open( szHost1, strPort1);
}
Telnet::~Telnet(){
if (bWinsockUp){
if(bConnected) Close();
WSACleanup();
}
// Paul Brannan 8/10/98
if(iconChange) {
ResetIcon(hConsoleWindow, oldBIcon, oldSIcon);
}
}
// changed from char * to const char * (Paul Brannan 5/12/98)
int Telnet::LoadKeyMap(const char * file, const char * name){
// printf("Loading %s from %s.\n", name ,file);
printm(0, FALSE, MSG_KEYMAP, name, file);
return MapLoader.Load(file,name);
}
void Telnet::DisplayKeyMap(){ // display available keymaps
MapLoader.Display();
};
int Telnet::SwitchKeyMap(int to) { // switch to selected keymap
int ret = KeyTrans.SwitchTo(to);
switch(ret) {
case -1: printm(0, FALSE, MSG_KEYNOKEYMAPS); break;
case 0: printm(0, FALSE, MSG_KEYBADMAP); break;
case 1: printm(0, FALSE, MSG_KEYMAPSWITCHED); break;
}
return ret;
};
int Telnet::Open(const char *szHost1, const char *strPort1){
if (bWinsockUp && !bConnected){
telSetConsoleTitle(szHost1);
strncpy (szHost,szHost1, 127);
strncpy(strPort, strPort1, sizeof(strPort));
// Determine whether to pipe to an executable or use our own sockets
// (Paul Brannan March 18, 1999)
const char *netpipe;
if(*(netpipe=ini.get_netpipe())) {
PROCESS_INFORMATION pi;
HANDLE hInWrite, hOutRead, hErrRead;
if(!CreateHiddenConsoleProcess(netpipe, &pi, &hInWrite,
&hOutRead, &hErrRead)) {
printm(0, FALSE, MSG_ERRPIPE);
return TNNOCON;
}
Network.SetPipe(hOutRead, hInWrite);
hProcess = pi.hProcess;
} else {
Socket = Connect();
if (Socket == INVALID_SOCKET) {
printm(0, FALSE, GetLastError());
return TNNOCON;
}
Network.SetSocket(Socket);
SetLocalAddress(Socket);
}
bNetFinish = 0;
bConnected = 1;
ThreadParams.p.bNetPaused = &bNetPaused;
ThreadParams.p.bNetFinish = &bNetFinish;
ThreadParams.p.bNetFinished = &bNetFinished;
ThreadParams.p.hExit = CreateEvent(0, TRUE, FALSE, "");
ThreadParams.p.hPause = CreateEvent(0, FALSE, FALSE, "");
ThreadParams.p.hUnPause = CreateEvent(0, FALSE, FALSE, "");
DWORD idThread;
// Disable Ctrl-break (PB 5/14/98);
// Fixed (Thomas Briggs 8/17/98)
if(ini.get_disable_break() || ini.get_control_break_as_c())
SetConsoleCtrlHandler(ControlEventHandler, TRUE);
hThread = CreateThread(0, 0,
telProcessNetwork,
(LPVOID)&ThreadParams, 0, &idThread);
// This helps the display thread a little (Paul Brannan 8/3/98)
SetThreadPriority(hThread, THREAD_PRIORITY_ABOVE_NORMAL);
return Resume();
} else if(bWinsockUp && bConnected) {
printm (0, FALSE, MSG_ALREADYCONNECTED, szHost);
}
return TNNOCON; // cannot do winsock stuff or already connected
}
// There seems to be a bug with MSVC's optimization. This turns them off
// for these two functions.
// (Paul Brannan 5/14/98)
#ifdef _MSC_VER
#pragma optimize("", off)
#endif
int Telnet::Close() {
Console.sync();
switch(Network.get_net_type()) {
case TN_NETSOCKET:
if(Socket != INVALID_SOCKET) closesocket(Socket);
Socket = INVALID_SOCKET;
break;
case TN_NETPIPE:
if(hProcess != 0) {
TerminateProcess(hProcess, 0);
CloseHandle(hProcess);
hProcess = 0;
}
break;
}
// Enable Ctrl-break (PB 5/14/98);
// Ioannou : this must be FALSE
if(ini.get_disable_break()) SetConsoleCtrlHandler(NULL, FALSE);
if (hThread) CloseHandle(hThread); // Paul Brannan 8/11/98
hThread = NULL; // Daniel Straub 11/12/98
SetEvent(ThreadParams.p.hUnPause);
bNetFinish = 1;
while (!bNetFinished)
Sleep (0); // give up our time slice- this lets our connection thread
// finish itself, so we don't hang [email protected]
telSetConsoleTitle("No Connection");
bConnected = 0;
return 1;
}
int Telnet::Resume(){
int i;
if (bConnected) {
Console.sync();
for(;;){
SetEvent(ThreadParams.p.hUnPause);
i = telProcessConsole(&ThreadParams.p, KeyTrans, Console,
Network, Mouse, Clipboard, hThread);
if (i) bConnected = 1;
else bConnected = 0;
ResetEvent(ThreadParams.p.hUnPause);
SetEvent(ThreadParams.p.hPause);
while (!bNetPaused)
Sleep (0); // give up our time slice- this lets our connection thread
// unpause itself, so we don't hang [email protected]
switch (i){
case TNNOCON:
Close();
return TNDONE;
case TNPROMPT:
return TNPROMPT;
case TNSCROLLBACK:
Scroller.ScrollBack();
break;
case TNSPAWN:
NewProcess();
}
}
}
return TNNOCON;
}
// Turn optimization back on (Paul Brannan 5/12/98)
#ifdef _MSC_VER
#pragma optimize("", on)
#endif
// The scrollback functions have been moved to TScroll.cpp
// (Paul Brannan 6/15/98)
SOCKET Telnet::Connect()
{
SOCKET Socket1 = socket(AF_INET, SOCK_STREAM, 0);
SOCKADDR_IN SockAddr;
SockAddr.sin_family = AF_INET;
SockAddr.sin_addr.s_addr = inet_addr(szHost);
// determine the port correctly [email protected] 15/12/98
SERVENT *sp;
sp = getservbyname (strPort, "tcp");
if (sp == NULL) {
if (isdigit (*(strPort)))
SockAddr.sin_port = htons(atoi(strPort));
else {
printm(0, FALSE, MSG_NOSERVICE, strPort);
return INVALID_SOCKET;
}
} else
SockAddr.sin_port = sp->s_port;
///
// Were we given host name?
if (SockAddr.sin_addr.s_addr == INADDR_NONE) {
// Resolve host name to IP address.
printm(0, FALSE, MSG_RESOLVING, szHost);
hostent* pHostEnt = gethostbyname(szHost);
if (!pHostEnt)
return INVALID_SOCKET;
printit("\n");
SockAddr.sin_addr.s_addr = *(DWORD*)pHostEnt->h_addr;
}
// Print a message telling the user the IP we are connecting to
// (Paul Brannan 5/14/98)
char ss_b1[4], ss_b2[4], ss_b3[4], ss_b4[4], ss_b5[12];
itoa(SockAddr.sin_addr.S_un.S_un_b.s_b1, ss_b1, 10);
itoa(SockAddr.sin_addr.S_un.S_un_b.s_b2, ss_b2, 10);
itoa(SockAddr.sin_addr.S_un.S_un_b.s_b3, ss_b3, 10);
itoa(SockAddr.sin_addr.S_un.S_un_b.s_b4, ss_b4, 10);
itoa(ntohs(SockAddr.sin_port), ss_b5, 10);
printm(0, FALSE, MSG_TRYING, ss_b1, ss_b2, ss_b3, ss_b4, ss_b5);
if (connect(Socket1, (sockaddr*)&SockAddr, sizeof(SockAddr)))
return INVALID_SOCKET;
char esc[2];
esc [0] = ini.get_escape_key();
esc [1] = 0;
printm(0, FALSE, MSG_CONNECTED, szHost, esc);
return Socket1;
}
void Telnet::telSetConsoleTitle(const char * szHost1)
{
char szTitle[128] = "Telnet - ";
strcat(szTitle, szHost1);
if(ini.get_set_title()) SetConsoleTitle(szTitle);
}
void Telnet::NewProcess() {
char cmd_line[MAX_PATH*2];
PROCESS_INFORMATION pi;
strcpy(cmd_line, ini.get_startdir());
strcat(cmd_line, ini.get_exename()); // Thomas Briggs 12/7/98
if(!SpawnProcess(cmd_line, &pi)) printm(0, FALSE, MSG_NOSPAWN);
}
void Telnet::SetLocalAddress(SOCKET s) {
SOCKADDR_IN SockAddr;
int size = sizeof(SOCKADDR_IN);
memset(&SockAddr, 0, sizeof(SockAddr));
SockAddr.sin_family = AF_INET;
getsockname(Network.GetSocket(), (sockaddr*)&SockAddr, &size);
char ss_b1[4], ss_b2[4], ss_b3[4], ss_b4[4];
itoa(SockAddr.sin_addr.S_un.S_un_b.s_b1, ss_b1, 10);
itoa(SockAddr.sin_addr.S_un.S_un_b.s_b2, ss_b2, 10);
itoa(SockAddr.sin_addr.S_un.S_un_b.s_b3, ss_b3, 10);
itoa(SockAddr.sin_addr.S_un.S_un_b.s_b4, ss_b4, 10);
char addr[40];
strcpy(addr, ss_b1);
strcat(addr, ".");
strcat(addr, ss_b2);
strcat(addr, ".");
strcat(addr, ss_b3);
strcat(addr, ".");
strcat(addr, ss_b4);
strcat(addr, ":0.0");
Network.SetLocalAddress(addr);
}
@@ -0,0 +1,74 @@
#ifndef __TNCLASS_H_
#define __TNCLASS_H_
#include <windows.h>
#include "tnconfig.h"
#include "ttelhndl.h"
#include "tncon.h"
#include "tnerror.h"
#include "tparams.h"
#include "keytrans.h"
#include "ansiprsr.h"
#include "tcharmap.h"
#include "tnclip.h"
#include "tmouse.h"
#include "tmapldr.h"
class Telnet {
public:
// create a telnet instance
Telnet();
// open a connection return on break/quit
Telnet(const char * szHost1, const char *strPort1);
~Telnet();
// open a connection return on break/quit
int Open(const char *szHost, const char *strPort = "23");
int Close(); // close current connection
int Resume(); // resume current session
// changes to the keymap profile in the file
int LoadKeyMap( const char * file, const char * name);
void DisplayKeyMap(); // display available keymaps
int SwitchKeyMap(int); // switch to selected keymap
private:
SOCKET Connect();
void telSetConsoleTitle(const char * szHost);
void DoInit();
SOCKET Socket;
char strPort[32]; // int iPort;
char szHost[127];
volatile int bConnected;
volatile int bWinsockUp;
volatile int bNetPaused;
volatile int bNetFinished;
volatile int bNetFinish;
// The order of member classes in the class definition MUST come in
// this order! (Paul Brannan 12/4/98)
TNetwork Network;
TCharmap Charmap;
KeyTranslator KeyTrans;
TMapLoader MapLoader;
TConsole Console;
TTelnetHandler TelHandler;
TelThreadParams ThreadParams;
Tnclip Clipboard;
TMouse Mouse;
TScroller Scroller;
TANSIParser Parser;
HWND hConsoleWindow; // Paul Brannan 8/10/98
LPARAM oldBIcon, oldSIcon; // Paul Brannan 8/10/98
bool iconChange;
HANDLE hThread; // Paul Brannan 8/11/98
HANDLE hProcess; // Paul Brannan 7/15/99
void NewProcess(); // Paul Brannan 9/13/98
void SetLocalAddress(SOCKET s);
};
#endif
@@ -0,0 +1,60 @@
///////////////////////////////////////////////////////////////////////////////
//Telnet Win32 : an ANSI telnet client.
//Copyright (C) 1998 Paul Brannan
//Copyright (C) 1998 I.Ioannou
//Copyright (C) 1997 Brad Johnson
//
//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., 675 Mass Ave, Cambridge, MA 02139, USA.
//
//I.Ioannou
//[email protected]
//
///////////////////////////////////////////////////////////////////////////
// TnClip.cpp
// A simple class for handling clipboard functions
// Written by Paul Brannan <[email protected]>
// Last modified 7/12/98
#include <string.h>
#include "tnclip.h"
Tnclip::Tnclip(HWND W, TNetwork &RefNetwork): Network(RefNetwork) {
Window = W;
}
Tnclip::~Tnclip() {
}
void Tnclip::Copy(HGLOBAL clipboard_data) {
if(!OpenClipboard(Window)) return;
if(!EmptyClipboard()) return;
SetClipboardData(CF_TEXT, clipboard_data);
CloseClipboard();
}
void Tnclip::Paste() {
if(!OpenClipboard(Window)) return;
HANDLE clipboard_data = GetClipboardData(CF_TEXT);
LPVOID clipboard_ptr = GlobalLock(clipboard_data);
DWORD size = strlen((const char *)clipboard_data);
Network.WriteString((const char *)clipboard_ptr, size);
GlobalUnlock(clipboard_data);
CloseClipboard();
}
@@ -0,0 +1,20 @@
#ifndef __TNCLIP_H
#define __TNCLIP_H
#include <windows.h>
#include "tnetwork.h"
class Tnclip {
private:
HWND Window;
TNetwork &Network;
public:
Tnclip(HWND Window, TNetwork &RefNetwork);
~Tnclip();
void Copy(HGLOBAL clipboard_data);
void Paste();
};
#endif
@@ -0,0 +1,368 @@
///////////////////////////////////////////////////////////////////////////////
//Telnet Win32 : an ANSI telnet client.
//Copyright (C) 1998-2000 Paul Brannan
//Copyright (C) 1998 I.Ioannou
//Copyright (C) 1997 Brad Johnson
//
//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., 675 Mass Ave, Cambridge, MA 02139, USA.
//
//I.Ioannou
//[email protected]
//
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
//
// Module: tncon.cpp
//
// Contents: telnet console processing
//
// Product: telnet
//
// Revisions: August 30, 1998 Paul Brannan <[email protected]>
// July 29, 1998 Paul Brannan
// June 15, 1998 Paul Brannan
// May 16, 1998 Paul Brannan
// 5.April.1997 [email protected]
// 9.Dec.1996 [email protected]
// Version 2.0
//
// 02.Apr.1995 [email protected]
// Original code
//
///////////////////////////////////////////////////////////////////////////////
#include "tncon.h"
#include "keytrans.h"
#include "ttelhndl.h"
#include "tconsole.h"
#define KEYEVENT InputRecord[i].Event.KeyEvent
// Paul Brannan 6/25/98
// #ifdef __MINGW32__
// #define KEYEVENT_CHAR KEYEVENT.AsciiChar
// #else
#define KEYEVENT_CHAR KEYEVENT.uChar.AsciiChar
// #endif
#define KEYEVENT_PCHAR &KEYEVENT_CHAR
// This is for local echo (Paul Brannan 5/16/98)
inline void DoEcho(const char *p, int l, TConsole &Console,
TNetwork &Network, NetParams *pParams) {
// Pause the console (Paul Brannan 8/24/98)
if(Network.get_local_echo()) {
ResetEvent(pParams->hUnPause);
SetEvent(pParams->hPause);
while (!*pParams->bNetPaused); // Pause
Console.WriteCtrlString(p, l);
SetEvent(pParams->hUnPause); // Unpause
}
}
// This is for line mode (Paul Brannan 12/31/98)
static char buffer[1024];
static unsigned int bufptr = 0;
// Line mode -- currently uses sga/echo to determine when to enter line mode
// (as in RFC 858), but correct behaviour is as described in RFC 1184.
// (Paul Brannan 12/31/98)
// FIX ME!! What to do with unflushed data when we change from line mode
// to character mode?
inline bool DoLineModeSpecial(char keychar, TConsole &Console, TNetwork &Network,
NetParams *pParams) {
if(keychar == VK_BACK) {
if(bufptr) bufptr--;
DoEcho("\b \b", 3, Console, Network, pParams);
return true;
} else if(keychar == VK_RETURN) {
Network.WriteString(buffer, bufptr);
Network.WriteString("\012", 1);
DoEcho("\r\n", 2, Console, Network, pParams);
bufptr = 0;
return true;
}
return false;
}
inline void DoLineMode(const char *p, int p_len, TConsole &Console,
TNetwork &Network) {
if(Network.get_line_mode()) {
if(bufptr < sizeof(buffer) + p_len - 1) {
memcpy(buffer + bufptr, p, p_len);
bufptr += p_len;
} else {
Console.Beep();
}
} else {
Network.WriteString(p, p_len);
}
}
// Paul Brannan 5/27/98
// Fixed this code for use with appliation cursor keys
// This should probably be optimized; it's pretty ugly as it is
// Rewrite #1: now uses ClosestStateKey (Paul Brannan 12/9/98)
const char *ClosestStateKey(WORD keyCode, DWORD keyState,
KeyTranslator &KeyTrans) {
char const *p;
if((p = KeyTrans.TranslateKey(keyCode, keyState))) return p;
// Check numlock and scroll lock (Paul Brannan 9/23/98)
if((p = KeyTrans.TranslateKey(keyCode, keyState & ~NUMLOCK_ON))) return p;
if((p = KeyTrans.TranslateKey(keyCode, keyState & ~ENHANCED_KEY
& ~NUMLOCK_ON))) return p;
if((p = KeyTrans.TranslateKey(keyCode, keyState & ~SCROLLLOCK_ON))) return p;
if((p = KeyTrans.TranslateKey(keyCode, keyState & ~ENHANCED_KEY
& ~SCROLLLOCK_ON))) return p;
// John Ioannou ([email protected])
// Athens 31/03/97 00:25am GMT+2
// fix for win95 CAPSLOCK bug
// first check if the user has keys with capslock and then we filter it
if((p = KeyTrans.TranslateKey(keyCode, keyState & ~ENHANCED_KEY))) return p;
if((p = KeyTrans.TranslateKey(keyCode, keyState & ~CAPSLOCK_ON))) return p;
if((p = KeyTrans.TranslateKey(keyCode, keyState & ~ENHANCED_KEY
& ~CAPSLOCK_ON))) return p;
return 0; // we couldn't find a suitable key translation
}
const char *FindClosestKey(WORD keyCode, DWORD keyState,
KeyTranslator &KeyTrans) {
char const *p;
// Paul Brannan 7/20/98
if(ini.get_alt_erase()) {
if(keyCode == VK_BACK) {
keyCode = VK_DELETE;
keyState |= ENHANCED_KEY;
} else if(keyCode == VK_DELETE && (keyState & ENHANCED_KEY)) {
keyCode = VK_BACK;
keyState &= ~ENHANCED_KEY;
}
}
DWORD ext_mode = KeyTrans.get_ext_mode();
if(ext_mode) {
// Not as fast as an unrolled loop, but certainly more
// compact (Paul Brannan 12/9/98)
for(DWORD j = ext_mode; j >= APP_KEY; j -= APP_KEY) {
if((j | ext_mode) == ext_mode) {
if((p = ClosestStateKey(keyCode, keyState | j,
KeyTrans))) return p;
}
}
}
return ClosestStateKey(keyCode, keyState, KeyTrans);
}
// Paul Brannan Feb. 22, 1999
int do_op(tn_ops op, TNetwork &Network, Tnclip &Clipboard) {
switch(op) {
case TN_ESCAPE:
return TNPROMPT;
case TN_SCROLLBACK:
return TNSCROLLBACK;
case TN_DIAL:
return TNSPAWN;
case TN_PASTE:
if(ini.get_keyboard_paste()) Clipboard.Paste();
else return 0;
break;
case TN_NULL:
Network.WriteString("", 1);
return 0;
case TN_CR:
Network.WriteString("\r", 2); // CR must be followed by NUL
return 0;
case TN_CRLF:
Network.WriteString("\r\n", 2);
return 0;
}
return 0;
}
int telProcessConsole(NetParams *pParams, KeyTranslator &KeyTrans,
TConsole &Console, TNetwork &Network, TMouse &Mouse,
Tnclip &Clipboard, HANDLE hThread)
{
KeyDefType_const keydef;
const char *p;
int p_len;
unsigned int i;
int opval;
HANDLE hConsole = GetStdHandle(STD_INPUT_HANDLE);
SetConsoleMode(hConsole, ini.get_enable_mouse() ? ENABLE_MOUSE_INPUT : 0);
const DWORD nHandle = 2;
HANDLE hHandle[nHandle] = {hConsole, pParams->hExit};
for (;;) {
DWORD dwInput;
switch (WaitForMultipleObjects(nHandle, hHandle, FALSE, INFINITE)) {
case WAIT_OBJECT_0: {
// Paul Brannan 7/29/98
if(ini.get_input_redir()) {
char InputBuffer[10];
// Correction from Joe Manns <[email protected]>
// to fix race conditions (4/13/99)
int bResult;
bResult = ReadFile(hConsole, InputBuffer, 10, &dwInput, 0);
if(bResult && dwInput == 0) return TNNOCON;
// no key translation for redirected input
Network.WriteString(InputBuffer, dwInput);
break;
}
INPUT_RECORD InputRecord[11];
if (!ReadConsoleInput(hConsole, &InputRecord[0], 10, &dwInput))
return TNPROMPT;
for (i = 0; (unsigned)i < dwInput; i++){
switch (InputRecord[i].EventType) {
case KEY_EVENT:{
if (KEYEVENT.bKeyDown) {
WORD keyCode = KEYEVENT.wVirtualKeyCode;
DWORD keyState = KEYEVENT.dwControlKeyState;
// Paul Brannan 5/27/98
// Moved the code that was here to FindClosestKey()
keydef.szKeyDef = FindClosestKey(keyCode,
keyState, KeyTrans);
if(keydef.szKeyDef) {
if(!keydef.op->sendstr)
if((opval = do_op(keydef.op->the_op, Network,
Clipboard)) != 0)
return opval;
}
if(Network.get_line_mode()) {
if(DoLineModeSpecial(KEYEVENT_CHAR, Console, Network, pParams))
continue;
}
p = keydef.szKeyDef;
if (p == NULL) { // if we don't have a translator
if(!KEYEVENT_CHAR) continue;
p_len = 1;
p = KEYEVENT_PCHAR;
} else {
p_len = strlen(p);
}
// Local echo (Paul Brannan 5/16/98)
DoEcho(p, p_len, Console, Network, pParams);
// Line mode (Paul Brannan 12/31/98)
DoLineMode(p, p_len, Console, Network);
}
}
break;
case MOUSE_EVENT:
if(!InputRecord[i].Event.MouseEvent.dwEventFlags) {
ResetEvent(pParams->hUnPause);
SetEvent(pParams->hPause);
while (!*pParams->bNetPaused); // thread paused
// SuspendThread(hThread);
// Put the mouse's X and Y coords back into the
// input buffer
DWORD Result;
WriteConsoleInput(hConsole, &InputRecord[i], 1,
&Result);
Mouse.doMouse();
SetEvent(pParams->hUnPause);
// ResumeThread(hThread);
}
break;
case FOCUS_EVENT:
break;
case WINDOW_BUFFER_SIZE_EVENT:
// FIX ME!! This should take care of the window re-sizing bug
// Unfortunately, it doesn't.
Console.sync();
Network.do_naws(Console.GetWidth(), Console.GetHeight());
break;
}
} // keep going until no more input
break;
}
default:
return TNNOCON;
}
}
}
WORD scrollkeys() {
HANDLE hConsole = GetStdHandle(STD_INPUT_HANDLE);
INPUT_RECORD InputRecord;
BOOL done = FALSE;
while (!done) {
DWORD dwInput;
WaitForSingleObject( hConsole, INFINITE );
if (!ReadConsoleInput(hConsole, &InputRecord, 1, &dwInput)){
done = TRUE;
continue;
}
if (InputRecord.EventType == KEY_EVENT &&
InputRecord.Event.KeyEvent.bKeyDown ) {
// Why not just return the key code? (Paul Brannan 12/5/98)
return InputRecord.Event.KeyEvent.wVirtualKeyCode;
} else if(InputRecord.EventType == MOUSE_EVENT) {
if(!InputRecord.Event.MouseEvent.dwEventFlags) {
// Put the mouse's X and Y coords back into the input buffer
WriteConsoleInput(hConsole, &InputRecord, 1, &dwInput);
return SC_MOUSE;
}
}
}
return SC_ESC;
}
// FIX ME!! This is more evidence that tncon.cpp ought to have class structure
// (Paul Brannan 12/10/98)
// Bryan Montgomery 10/14/98
static TNetwork net;
void setTNetwork(TNetwork tnet) {
net = tnet;
}
// Thomas Briggs 8/17/98
BOOL WINAPI ControlEventHandler(DWORD event) {
switch(event) {
case CTRL_BREAK_EVENT:
// Bryan Montgomery 10/14/98
if(ini.get_control_break_as_c()) net.WriteString("\x3",1);
return TRUE;
default:
return FALSE;
}
}
@@ -0,0 +1,34 @@
#ifndef __TNCON_H
#define __TNCON_H
#include "tparams.h"
#include "tnclip.h"
#include "ttelhndl.h"
enum {
SC_UP,
SC_DOWN,
SC_ESC,
SC_MOUSE
};
enum {
TNNOCON,
TNPROMPT,
TNSCROLLBACK,
TNSPAWN,
TNDONE
};
int telProcessConsole(NetParams *pParams, KeyTranslator &KeyTrans,
TConsole &Console, TNetwork &Network, TMouse &Mouse,
Tnclip &Clipboard, HANDLE hThread);
WORD scrollkeys ();
// Thomas Briggs 8/17/98
BOOL WINAPI ControlEventHandler(DWORD);
// Bryan Montgomery 10/14/98
void setTNetwork(TNetwork);
#endif
@@ -0,0 +1,704 @@
///////////////////////////////////////////////////////////////////////////////
//Telnet Win32 : an ANSI telnet client.
//Copyright (C) 1998-2000 Paul Brannan
//Copyright (C) 1998 I.Ioannou
//Copyright (C) 1997 Brad Johnson
//
//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., 675 Mass Ave, Cambridge, MA 02139, USA.
//
//I.Ioannou
//[email protected]
//
///////////////////////////////////////////////////////////////////////////
// tnconfig.cpp
// Written by Paul Brannan <[email protected]>
// Last modified August 30, 1998
//
// This is a class designed for use with Brad Johnson's Console Telnet
// see the file tnconfig.h for more information
#include <stdlib.h>
#include <string.h>
#include <locale.h>
#include <memory.h>
#include <io.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "tnconfig.h"
// Turn off the "forcing value to bool 'true' or 'false'" warning
#ifdef _MSC_VER
#pragma warning(disable: 4800)
#endif
// This is the ini variable that is used for everybody
TConfig ini;
TConfig::TConfig() {
// set all default values
startdir[0] = '\0';
keyfile[0] = '\0';
inifile[0] = '\0';
dumpfile[0] = '\0';
term[0] = '\0';
default_config[0] = '\0';
strcpy(printer_name, "LPT1");
input_redir = 0;
output_redir = 0;
strip_redir = FALSE;
dstrbksp = FALSE;
eightbit_ansi = FALSE;
vt100_mode = FALSE;
disable_break = FALSE;
speaker_beep = TRUE;
do_beep = TRUE;
preserve_colors = FALSE;
wrapline = TRUE;
lock_linewrap = FALSE;
fast_write = TRUE;
enable_mouse = TRUE;
alt_erase = FALSE;
wide_enable = FALSE;
keyboard_paste = FALSE;
set_title = TRUE;
blink_bg = -1;
blink_fg = 2;
underline_bg = -1;
underline_fg = 3;
ulblink_bg = -1;
ulblink_fg = 1;
normal_bg = -1;
normal_fg = -1;
scroll_bg = 0;
scroll_fg = 7;
status_bg = 1;
status_fg = 15;
buffer_size = 2048;
term_width = -1;
term_height = -1;
window_width = -1;
window_height = -1;
strcpy(escape_key, "]");
strcpy(scrollback_key, "[");
strcpy(dial_key, "\\");
strcpy(default_config, "ANSI");
strcpy(term, "ansi");
strcpy(scroll_mode, "DUMP");
scroll_size=32000;
scroll_enable=TRUE;
host[0] = '\0';
port = "23";
init_varlist();
aliases = NULL;
}
TConfig::~TConfig() {
if(aliases) {
for(int j = 0; j < alias_total; j++) delete[] aliases[j];
delete[] aliases;
}
}
enum ini_data_type {
INI_STRING,
INI_INT,
INI_BOOL
};
enum {
INIFILE,
KEYFILE,
DUMPFILE,
DEFAULT_CONFIG,
TERM,
INPUT_REDIR,
OUTPUT_REDIR,
STRIP_REDIR,
DSTRBKSP,
EIGHTBIT_ANSI,
VT100_MODE,
DISABLE_BREAK,
SPEAKER_BEEP,
DO_BEEP,
PRESERVE_COLORS,
WRAP_LINE,
LOCK_LINEWRAP,
FAST_WRITE,
TERM_WIDTH,
TERM_HEIGHT,
WINDOW_WIDTH,
WINDOW_HEIGHT,
WIDE_ENABLE,
CTRLBREAK_AS_CTRLC,
BUFFER_SIZE,
SET_TITLE,
BLINK_BG,
BLINK_FG,
UNDERLINE_BG,
UNDERLINE_FG,
ULBLINK_BG,
ULBLINK_FG,
NORMAL_BG,
NORMAL_FG,
SCROLL_BG,
SCROLL_FG,
STATUS_BG,
STATUS_FG,
PRINTER_NAME,
ENABLE_MOUSE,
ESCAPE_KEY,
SCROLLBACK_KEY,
DIAL_KEY,
ALT_ERASE,
KEYBOARD_PASTE,
SCROLL_MODE,
SCROLL_SIZE,
SCROLL_ENABLE,
SCRIPTNAME,
SCRIPT_ENABLE,
NETPIPE,
IOPIPE,
MAX_INI_VARS // must be last
};
struct ini_variable {
const char *name; // variable name
const char *section; // name of ini file section the variable is in
enum ini_data_type data_type; // type of data
void *ini_data; // pointer to data
int max_size; // max size if string
};
// Note: default values are set in the constructor, TConfig()
ini_variable ini_varlist[MAX_INI_VARS];
enum {
KEYBOARD,
TERMINAL,
COLORS,
MOUSE,
PRINTER,
SCROLLBACK,
SCRIPTING,
PIPES,
MAX_INI_GROUPS // Must be last
};
char *ini_groups[MAX_INI_GROUPS];
void TConfig::init_varlist() {
static const ini_variable static_ini_varlist[MAX_INI_VARS] = {
{"Inifile", NULL, INI_STRING, &inifile, sizeof(inifile)},
{"Keyfile", "Keyboard", INI_STRING, &keyfile, sizeof(keyfile)},
{"Dumpfile", "Terminal", INI_STRING, &dumpfile, sizeof(dumpfile)},
{"Default_Config","Keyboard", INI_STRING, &default_config, sizeof(default_config)},
{"Term", "Terminal", INI_STRING, &term, sizeof(term)},
{"Input_Redir", "Terminal", INI_INT, &input_redir, 0},
{"Output_Redir","Terminal", INI_INT, &output_redir, 0},
{"Strip_Redir", "Terminal", INI_BOOL, &strip_redir, 0},
{"Destructive_Backspace","Terminal",INI_BOOL, &dstrbksp, 0},
{"EightBit_Ansi","Terminal", INI_BOOL, &eightbit_ansi, 0},
{"VT100_Mode", "Terminal", INI_BOOL, &vt100_mode, 0},
{"Disable_Break","Terminal", INI_BOOL, &disable_break, 0},
{"Speaker_Beep","Terminal", INI_BOOL, &speaker_beep, 0},
{"Beep", "Terminal", INI_BOOL, &do_beep, 0},
{"Preserve_Colors","Terminal", INI_BOOL, &preserve_colors, 0},
{"Wrap_Line", "Terminal", INI_BOOL, &wrapline, 0},
{"Lock_linewrap","Terminal", INI_BOOL, &lock_linewrap, 0},
{"Fast_Write", "Terminal", INI_BOOL, &fast_write, 0},
{"Term_Width", "Terminal", INI_INT, &term_width, 0},
{"Term_Height", "Terminal", INI_INT, &term_height, 0},
{"Window_Width","Terminal", INI_INT, &window_width, 0},
{"Window_Height","Terminal", INI_INT, &window_height, 0},
{"Wide_Enable", "Terminal", INI_BOOL, &wide_enable, 0},
{"Ctrlbreak_as_Ctrlc","Keyboard", INI_BOOL, &ctrlbreak_as_ctrlc, 0},
{"Buffer_Size", "Terminal", INI_INT, &buffer_size, 0},
{"Set_Title", "Terminal", INI_BOOL, &set_title, 0},
{"Blink_bg", "Colors", INI_INT, &blink_bg, 0},
{"Blink_fg", "Colors", INI_INT, &blink_fg, 0},
{"Underline_bg","Colors", INI_INT, &underline_bg, 0},
{"Underline_fg","Colors", INI_INT, &underline_fg, 0},
{"UlBlink_bg", "Colors", INI_INT, &ulblink_bg, 0},
{"UlBlink_fg", "Colors", INI_INT, &ulblink_fg, 0},
{"Normal_bg", "Colors", INI_INT, &normal_bg, 0},
{"Normal_fg", "Colors", INI_INT, &normal_fg, 0},
{"Scroll_bg", "Colors", INI_INT, &scroll_bg, 0},
{"Scroll_fg", "Colors", INI_INT, &scroll_fg, 0},
{"Status_bg", "Colors", INI_INT, &status_bg, 0},
{"Status_fg", "Colors", INI_INT, &status_fg, 0},
{"Enable_Mouse","Mouse", INI_BOOL, &enable_mouse, 0},
{"Printer_Name","Printer", INI_STRING, &printer_name, sizeof(printer_name)},
{"Escape_Key", "Keyboard", INI_STRING, &escape_key, 1},
{"Scrollback_Key","Keyboard", INI_STRING, &scrollback_key, 1},
{"Dial_Key", "Keyboard", INI_STRING, &dial_key, 1},
{"Alt_Erase", "Keyboard", INI_BOOL, &alt_erase, 0},
{"Keyboard_Paste","Keyboard", INI_BOOL, &keyboard_paste, 0},
{"Scroll_Mode", "Scrollback", INI_STRING, &scroll_mode, sizeof(scroll_mode)},
{"Scroll_Size", "Scrollback", INI_INT, &scroll_size, 0},
{"Scroll_Enable","Scrollback", INI_BOOL, &scroll_enable, 0},
{"Scriptname", "Scripting", INI_STRING, &scriptname, sizeof(scriptname)},
{"Script_enable","Scripting", INI_BOOL, &script_enable, 0},
{"Netpipe", "Pipes", INI_STRING, &netpipe, sizeof(netpipe)},
{"Iopipe", "Pipes", INI_STRING, &iopipe, sizeof(iopipe)}
};
static const char *static_ini_groups[MAX_INI_GROUPS] = {
"Keyboard",
"Terminal",
"Colors",
"Mouse",
"Printer",
"Scrollback",
"Scripting",
"Pipes"
};
memcpy(ini_varlist, static_ini_varlist, sizeof(ini_varlist));
memcpy(ini_groups, static_ini_groups, sizeof(ini_groups));
}
void TConfig::init(char *dirname, char *execname) {
// Copy temporary dirname to permanent startdir
strncpy(startdir, dirname, sizeof(startdir));
startdir[sizeof(startdir) - 1] = 0;
// Copy temp execname to permanent exename (Thomas Briggs 12/7/98)
strncpy(exename, execname, sizeof(exename));
exename[sizeof(exename) - 1] = 0;
// Initialize INI file
inifile_init();
// Initialize redir
// Note that this must be done early, so error messages will be printed
// properly
redir_init();
// Initialize aliases (Paul Brannan 1/1/99)
init_aliases();
// Make sure the file that we're trying to work with exists
int iResult = access(inifile, 04);
// Thomas Briggs 9/14/98
if( iResult == 0 )
// Tell the user what file we are reading
// We cannot print any messages before initializing telnet_redir
printm(0, FALSE, MSG_CONFIG, inifile);
else
// Tell the user that the file doesn't exist, but later read the
// file anyway simply to populate the defaults
printm(0, FALSE, MSG_NOINI, inifile);
init_vars(); // Initialize misc. vars
keyfile_init(); // Initialize keyfile
}
// Alias support (Paul Brannan 1/1/99)
void TConfig::init_aliases() {
char *buffer;
alias_total = 0;
// Find the correct buffer size
// FIX ME!! some implementations of Mingw32 don't have a
// GetPrivateProfileSecionNames function. What do we do about this?
#ifndef __MINGW32__
{
int size=1024, Result = 0;
for(;;) {
buffer = new char[size];
Result = GetPrivateProfileSectionNames(buffer, size, inifile);
if(Result < size - 2) break;
size *= 2;
delete[] buffer;
}
}
#else
return;
#endif
// Find the maximum number of aliases
int max = 0;
char *tmp;
for(tmp = buffer; *tmp != 0; tmp += strlen(tmp) + 1)
max++;
aliases = new char*[max];
// Load the aliases into an array
for(tmp = buffer; *tmp != 0; tmp += strlen(tmp) + 1) {
int flag = 0;
for(int j = 0; j < MAX_INI_GROUPS; j++) {
if(!stricmp(ini_groups[j], tmp)) flag = 1;
}
if(!flag) {
aliases[alias_total] = new char[strlen(tmp)+1];
strcpy(aliases[alias_total], tmp);
alias_total++;
}
}
delete[] buffer;
}
void TConfig::print_aliases() {
for(int j = 0; j < alias_total; j++) {
char alias_name[20];
set_string(alias_name, aliases[j], sizeof(alias_name));
for(unsigned int i = strlen(alias_name); i < sizeof(alias_name) - 1; i++)
alias_name[i] = ' ';
alias_name[sizeof(alias_name) - 1] = 0;
printit(alias_name);
if((j % 4) == 3) printit("\n");
}
printit("\n");
}
bool find_alias(const char *alias_name) {
return false;
}
void TConfig::print_vars() {
int j;
for(j = 0; j < MAX_INI_VARS; j++) {
if(print_value(ini_varlist[j].name) > 40) printit("\n");
else if(j % 2) printit("\n");
else printit("\t");
}
if(j % 2) printit("\n");
}
// Paul Brannan 9/3/98
void TConfig::print_vars(char *s) {
if(!strnicmp(s, "all", 3)) { // Print out all vars
print_vars();
return;
}
// See if the group exists
int j, flag;
for(j = 0, flag = 0; j < MAX_INI_GROUPS; j++)
if(!stricmp(ini_groups[j], s)) break;
// If not, print out the value of the variable by that name
if(j == MAX_INI_GROUPS) {
print_value(s);
printit("\n");
return;
}
// Print out the vars in the given group
int count = 0;
for(j = 0; j < MAX_INI_VARS; j++) {
if(ini_varlist[j].section == NULL) continue;
if(!stricmp(ini_varlist[j].section, s)) {
if(print_value(ini_varlist[j].name) > 40) printit("\n");
else if(count % 2) printit("\n");
else printit("\t");
count++;
}
}
if(count % 2) printit("\n");
}
// Paul Brannan 9/3/98
void TConfig::print_groups() {
for(int j = 0; j < MAX_INI_GROUPS; j++) {
char group_name[20];
set_string(group_name, ini_groups[j], sizeof(group_name));
for(unsigned int i = strlen(group_name); i < sizeof(group_name) - 1; i++)
group_name[i] = ' ';
group_name[sizeof(group_name) - 1] = 0;
printit(group_name);
if((j % 4) == 3) printit("\n");
}
printit("\n");
}
// Ioannou : The index in the while causes segfaults if there is no match
// changes to for(), and strcmp to stricmp (prompt gives rong names)
bool TConfig::set_value(const char *var, const char *value) {
//int j = 0;
//while(strcmp(var, ini_varlist[j].name) && j < MAX_INI_VARS) j++;
for (int j = 0; j < MAX_INI_VARS; j++)
{
if (stricmp(var, ini_varlist[j].name) == 0)
{
switch(ini_varlist[j].data_type) {
case INI_STRING:
set_string((char *)ini_varlist[j].ini_data, value,
ini_varlist[j].max_size);
break;
case INI_INT:
*(int *)ini_varlist[j].ini_data = atoi(value);
break;
case INI_BOOL:
set_bool((bool *)ini_varlist[j].ini_data, value);
break;
}
// j = MAX_INI_VARS;
return TRUE;
}
}
return FALSE;
}
int TConfig::print_value(const char *var) {
//int j = 0;
//while(strcmp(var, ini_varlist[j].name) && j < MAX_INI_VARS) j++;
int Result = 0;
for (int j = 0; j < MAX_INI_VARS; j++)
{
if (stricmp(var, ini_varlist[j].name) == 0)
{
char var_name[25];
set_string(var_name, var, sizeof(var_name));
for(unsigned int i = strlen(var_name); i < sizeof(var_name) - 1; i++)
var_name[i] = ' ';
var_name[sizeof(var_name) - 1] = 0;
Result = sizeof(var_name);
printit(var_name);
printit("\t");
Result = Result / 8 + 8;
switch(ini_varlist[j].data_type) {
case INI_STRING:
printit((char *)ini_varlist[j].ini_data);
Result += strlen((char *)ini_varlist[j].ini_data);
break;
case INI_INT:
char buffer[20]; // this may not be safe
// Ioannou : Paul this was _itoa, but Borland needs itoa !!
itoa(*(int *)ini_varlist[j].ini_data, buffer, 10);
printit(buffer);
Result += strlen(buffer);
break;
case INI_BOOL:
if(*(bool *)ini_varlist[j].ini_data == true) {
printit("on");
Result += 2;
} else {
printit("off");
Result += 3;
}
}
// printit("\n");
j = MAX_INI_VARS;
}
}
return Result;
}
void TConfig::init_vars() {
char buffer[4096];
for(int j = 0; j < MAX_INI_VARS; j++) {
if(ini_varlist[j].section != NULL) {
GetPrivateProfileString(ini_varlist[j].section, ini_varlist[j].name, "",
buffer, sizeof(buffer), inifile);
if(*buffer != 0) set_value(ini_varlist[j].name, buffer);
}
}
}
void TConfig::inifile_init() {
// B. K. Oxley 9/16/98
char* env_telnet_ini = getenv (ENV_TELNET_INI);
if (env_telnet_ini && *env_telnet_ini) {
strncpy (inifile, env_telnet_ini, sizeof(inifile));
return;
}
strcpy(inifile, startdir);
if (sizeof(inifile) >= strlen(inifile)+strlen("telnet.ini")) {
strcat(inifile,"telnet.ini"); // add the default filename to the path
} else {
// if there is not enough room set the path to nothing
strcpy(inifile,"");
}
}
void TConfig::keyfile_init() {
// check to see if there is a key config file environment variable.
char *k;
if ((k = getenv(ENV_TELNET_CFG)) == NULL){
// if there is no environment variable
GetPrivateProfileString("Keyboard", "Keyfile", "", keyfile,
sizeof(keyfile), inifile);
if(keyfile == 0 || *keyfile == 0) {
// and there is no profile string
strcpy(keyfile, startdir);
if (sizeof(keyfile) >= strlen(keyfile)+strlen("telnet.cfg")) {
struct stat buf;
strcat(keyfile,"telnet.cfg"); // add the default filename to the path
if(stat(keyfile, &buf) != 0) {
char *s = keyfile + strlen(keyfile) - strlen("telnet.cfg");
strcpy(s, "keys.cfg");
}
} else {
// if there is not enough room set the path to nothing
strcpy(keyfile,"");
}
// Vassili Bourdo ([email protected])
} else {
// check that keyfile really exists
if( access(keyfile,04) == -1 ) {
//it does not...
char pathbuf[MAX_PATH], *fn;
//substitute keyfile path with startdir path
if((fn = strrchr(keyfile,'\\'))) strcpy(keyfile,fn);
strcat(strcpy(pathbuf,startdir),keyfile);
//check that startdir\keyfile does exist
if( access(pathbuf,04) == -1 ) {
//it does not...
//so, look for it in all paths
_searchenv(keyfile, "PATH", pathbuf);
if( *pathbuf == 0 ) //no luck - revert it to INI file value
GetPrivateProfileString("Keyboard", "Keyfile", "",
keyfile, sizeof(keyfile), inifile);
} else {
strcpy(keyfile, pathbuf);
}
}
}
////
} else {
// set the keyfile to the value of the environment variable
strncpy(keyfile, k, sizeof(keyfile));
}
}
void TConfig::redir_init() {
// check to see if the environment variable 'TELNET_REDIR' is not 0;
char* p = getenv(ENV_TELNET_REDIR);
if (p) {
input_redir = output_redir = atoi(p);
if((p = getenv(ENV_INPUT_REDIR))) input_redir = atoi(p);
if((p = getenv(ENV_OUTPUT_REDIR))) output_redir = atoi(p);
} else {
input_redir = output_redir = GetPrivateProfileInt("Terminal",
"Telnet_Redir", 0, inifile);
input_redir = GetPrivateProfileInt("Terminal",
"Input_Redir", input_redir, inifile);
output_redir = GetPrivateProfileInt("Terminal",
"Output_Redir", output_redir, inifile);
}
if ((input_redir > 1) || (output_redir > 1))
setlocale(LC_CTYPE,"");
// tell isprint() to not ignore local characters, if the environment
// variable "LANG" has a valid value (e.g. LANG=de for german characters)
// and the file LOCALE.BLL is installed somewhere along the PATH.
}
// Modified not to use getopt() by Paul Brannan 12/17/98
bool TConfig::Process_Params(int argc, char *argv[]) {
int optind = 1;
char *optarg = argv[optind];
char c;
while(optind < argc) {
if(argv[optind][0] != '-') break;
// getopt
c = argv[optind][1];
if(argv[optind][2] == 0)
optarg = argv[++optind];
else
optarg = &argv[optind][2];
optind++;
switch(c) {
case 'd':
set_string(dumpfile, optarg, sizeof(dumpfile));
printm(0, FALSE, MSG_DUMPFILE, dumpfile);
break;
// added support for setting options on the command-line
// (Paul Brannan 7/31/98)
case '-':
{
int j;
for(j = 0; optarg[j] != ' ' && optarg[j] != '=' && optarg[j] != 0; j++);
if(optarg == 0) {
printm(0, FALSE, MSG_USAGE); // print a usage message
printm(0, FALSE, MSG_USAGE_1);
return FALSE;
}
optarg[j] = 0;
if(!set_value(optarg, &optarg[j+1]))
printm(0, FALSE, MSG_BADVAL, optarg);
}
break;
default:
printm(0, FALSE, MSG_USAGE); // print a usage message
printm(0, FALSE, MSG_USAGE_1);
return FALSE;
}
}
if(optind < argc)
set_string(host, argv[optind++], sizeof(host)-1);
if(!strnicmp(host, "telnet://", 9)) {
// we have a URL to parse
char *s, *t;
for(s = host+9, t = host; *s != 0; *(t++) = *(s++));
*t = 0;
for(s = host; *s != ':' && *s != 0; s++);
if(*s != 0) {
*(s++) = 0;
port = s;
}
}
if(optind < argc)
port = argv[optind++];
return TRUE;
}
void TConfig::set_string(char *dest, const char *src, const int length) {
int l = length;
strncpy(dest, src, l);
// dest[length-1] = '\0';
// Ioannou : this messes strings - is this really needed ?
// The target string, dest, might not be null-terminated
// if the length of src is length or more.
// it should be dest[length] = '\0' for strings with length 1
// (Escape_string etc), but doesn't work with others (like host).
// dest is long enough to avoid this in all the tested cases
}
// Ioannou : ignore case for true or on
void TConfig::set_bool(bool *boolval, const char *str) {
if(!stricmp(str, "true")) *boolval = true;
else if(!stricmp(str, "on")) *boolval = true;
else *boolval = (bool)atoi(str);
}
@@ -0,0 +1,211 @@
// Tnconfig.h
// Written by Paul Brannan <[email protected]>
//
// This is a class designed for use with Brad Johnson's Console Telnet
// It reads an ini file and keeps the settings for later retrieval.
// It does not store any information about the current settings, only default
// or recommended settings.
#ifndef __TNCONFIG_H
#define __TNCONFIG_H
// Ioannou 2 June 98: Borland needs them - quick hack
#ifdef __BORLANDC__
#define bool BOOL
#define true TRUE
#define false FALSE
#endif // __BORLANDC__
#include "tnerror.h"
#define ENV_TELNET_CFG "TELNET_CFG"
#define ENV_TELNET_REDIR "TELNET_REDIR"
#define ENV_INPUT_REDIR "TELNET_INPUT_REDIR"
#define ENV_OUTPUT_REDIR "TENLET_OUTPUT_REDIR"
#define ENV_TELNET_INI "TELNET_INI"
class TConfig {
public:
TConfig();
~TConfig();
// Miscellaneous strings
const char *get_startdir() const {return startdir;}
const char *get_exename() const {return exename;}
const char *get_keyfile() const {return keyfile;}
const char *get_inifile() const {return inifile;}
const char *get_dumpfile() const {return dumpfile;}
const char *get_term() const {return term;}
const char *get_printer_name() const {return printer_name;}
const char *get_default_config() const {return default_config;}
// Terminal settings
int get_input_redir() const {return input_redir;}
int get_output_redir() const {return output_redir;}
bool get_strip_redir() const {return strip_redir;}
bool get_dstrbksp() const {return dstrbksp;}
bool get_eightbit_ansi() const {return eightbit_ansi;}
bool get_vt100_mode() const {return vt100_mode;}
bool get_disable_break() const {return disable_break;}
bool get_speaker_beep() const {return speaker_beep;}
bool get_do_beep() const {return do_beep;}
bool get_preserve_colors() const {return preserve_colors;}
bool get_wrapline() const {return wrapline;}
bool get_fast_write() const {return fast_write;}
bool get_lock_linewrap() const {return lock_linewrap;}
bool get_set_title() const { return set_title;}
int get_term_width() const {return term_width;}
int get_term_height() const {return term_height;}
int get_window_width() const {return window_width;}
int get_window_height() const {return window_height;}
bool get_wide_enable() const {return wide_enable;}
bool get_control_break_as_c() const {return ctrlbreak_as_ctrlc;}
int get_buffer_size() const {return buffer_size;}
// Colors
int get_blink_bg() const {return blink_bg;}
int get_blink_fg() const {return blink_fg;}
int get_underline_bg() const {return underline_bg;}
int get_underline_fg() const {return underline_fg;}
int get_ulblink_bg() const {return ulblink_bg;}
int get_ulblink_fg() const {return ulblink_fg;}
int get_normal_bg() const {return normal_bg;}
int get_normal_fg() const {return normal_fg;}
int get_scroll_bg() const {return scroll_bg;}
int get_scroll_fg() const {return scroll_fg;}
int get_status_bg() const {return status_bg;}
int get_status_fg() const {return status_fg;}
// Mouse
bool get_enable_mouse() const {return enable_mouse;}
// Keyboard
char get_escape_key() const {return escape_key[0];}
char get_scrollback_key() const {return scrollback_key[0];}
char get_dial_key() const {return dial_key[0];}
bool get_alt_erase() const {return alt_erase;}
bool get_keyboard_paste() const {return keyboard_paste;}
// Scrollback
const char *get_scroll_mode() const {return scroll_mode;}
bool get_scroll_enable() const {return scroll_enable;}
int get_scroll_size() const {return scroll_size;}
// Scripting
const char *get_scriptname() const {return scriptname;}
bool get_script_enable() const {return script_enable;}
// Pipes
const char *get_netpipe() const {return netpipe;}
const char *get_iopipe() const {return iopipe;}
// Host configuration
const char *get_host() const {return host;}
const char *get_port() const {return port;}
// Initialization
void init(char *dirname, char *exename);
bool Process_Params(int argc, char *argv[]);
// Ini variables
void print_vars();
void print_vars(char *s);
void print_groups();
bool set_value(const char *var, const char *value);
int print_value(const char *var);
// Aliases
void print_aliases();
bool find_alias(const char *alias_name);
private:
void inifile_init();
void keyfile_init();
void redir_init();
void init_varlist();
void init_vars();
void init_aliases();
void set_string(char *dest, const char *src, const int length);
void set_bool(bool *boolval, const char *str);
// Miscellaneous strings
char startdir[MAX_PATH];
char exename[MAX_PATH];
char keyfile[MAX_PATH*2];
char inifile[MAX_PATH*2];
char dumpfile[MAX_PATH*2];
char printer_name[MAX_PATH*2];
char term[128];
char default_config[128];
// Terminal
int input_redir, output_redir;
bool strip_redir;
bool dstrbksp;
bool eightbit_ansi;
bool vt100_mode;
bool disable_break;
bool speaker_beep;
bool do_beep;
bool preserve_colors;
bool wrapline;
bool lock_linewrap;
bool fast_write;
bool set_title;
int term_width, term_height;
int window_width, window_height;
bool wide_enable;
bool ctrlbreak_as_ctrlc;
int buffer_size;
// Colors
int blink_bg;
int blink_fg;
int underline_bg;
int underline_fg;
int ulblink_bg;
int ulblink_fg;
int normal_bg;
int normal_fg;
int scroll_bg;
int scroll_fg;
int status_bg;
int status_fg;
// Mouse
bool enable_mouse;
// Keyboard
char escape_key[2];
char scrollback_key[2];
char dial_key[2];
bool alt_erase;
bool keyboard_paste;
// Scrollback
char scroll_mode[8];
bool scroll_enable;
int scroll_size;
// Scripting
char scriptname[MAX_PATH*2];
bool script_enable;
// Pipes
char netpipe[MAX_PATH*2];
char iopipe[MAX_PATH*2];
// Host configration
char host[128];
const char *port;
// Aliases
char **aliases;
int alias_total;
};
extern TConfig ini;
#endif
@@ -0,0 +1,220 @@
///////////////////////////////////////////////////////////////////////////////
//Telnet Win32 : an ANSI telnet client.
//Copyright (C) 1998-2000 Paul Brannan
//Copyright (C) 1998 I.Ioannou
//Copyright (C) 1997 Brad Johnson
//
//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., 675 Mass Ave, Cambridge, MA 02139, USA.
//
//I.Ioannou
//[email protected]
//
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
//
// Module: tnerror.cpp
//
// Contents: error reporting
//
// Product: telnet
//
// Revisions: June 15, 1998 Paul Brannan <[email protected]>
// May 15, 1998 Paul Brannan
// 5.April.1997 [email protected]
// 5.Dec.1996 [email protected]
// Version 2.0
//
// 02.Apr.1995 [email protected]
// Original code
//
///////////////////////////////////////////////////////////////////////////////
#include "tnerror.h"
#include "ttelhndl.h" // Paul Brannan 5/25/98
#include "tnconfig.h" // Paul Brannan 5/25/98
#include <time.h>
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#ifndef LANG_USER_DEFAULT
#define LANG_USER_DEFAULT 400
#endif
// This has been moved to tnconfig.cpp
// int Telnet_Redir = 0;
// Telnet_Redir is set to the value of the environment variable TELNET_REDIR
// in main.
int printit(const char * it){
DWORD numwritten;
if (!ini.get_output_redir()) {
if (!WriteConsole(
GetStdHandle(STD_OUTPUT_HANDLE), // handle of a console screen buffer
it, // address of buffer to write from
strlen(it), // number of characters to write
&numwritten, // address of number of characters written
0 // reserved
)) return -1;
// FIX ME!!! We need to tell the console that the cursor has moved.
// Does this mean making Console global?
// Paul Brannan 6/14/98
// Console.sync();
}else{
if (!WriteFile(
GetStdHandle(STD_OUTPUT_HANDLE), // handle of a console screen buffer
it, // address of buffer to write from
strlen(it), // number of characters to write
&numwritten, // address of number of characters written
NULL // no overlapped I/O
)) return -1;
}
return 0;
}
int printm(LPTSTR szModule, BOOL fSystem, DWORD dwMessageId, ...)
{
int Result = 0;
HMODULE hModule = 0;
if (szModule)
hModule = LoadLibrary(szModule);
va_list Ellipsis;
va_start(Ellipsis, dwMessageId);
LPTSTR pszMessage = 0;
DWORD dwMessage = 0;
if(fSystem) {
dwMessage = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM, hModule, dwMessageId,
LANG_USER_DEFAULT, (LPTSTR)&pszMessage, 128, &Ellipsis);
} else {
// we will use a string table.
char szString[256];
if(LoadString(0, dwMessageId, szString, sizeof(szString)))
dwMessage = FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_STRING, szString, dwMessageId,
LANG_USER_DEFAULT, (LPTSTR)&pszMessage, 256, &Ellipsis);
}
va_end(Ellipsis);
if (szModule)
FreeLibrary(hModule);
if (dwMessage) {
Result = printit(pszMessage);
LocalFree(pszMessage);
}
return Result;
}
void LogErrorConsole(LPTSTR szError)
{
DWORD dwLastError = GetLastError();
const int cbLastError = 1024;
TCHAR szLastError[cbLastError];
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0, dwLastError, LANG_USER_DEFAULT,
szLastError, cbLastError, 0);
LPTSTR lpszStrings[2];
lpszStrings[0] = szError;
lpszStrings[1] = szLastError;
const int cbErrorString = 1024;
TCHAR szErrorString[cbErrorString];
FormatMessage(FORMAT_MESSAGE_FROM_HMODULE| FORMAT_MESSAGE_ARGUMENT_ARRAY,
0, MSG_ERROR, LANG_USER_DEFAULT,
szErrorString, cbErrorString, (va_list*)lpszStrings);
time_t dwTime;
time(&dwTime);
char* szTime = ctime(&dwTime);
szTime[19] = 0;
// printf("E %s %s", szTime + 11, szErrorString);
char * buf;
buf = new char [ 3 + strlen(szTime) - 11 + strlen(szErrorString) + 5 ];
sprintf( buf,"E %s %s", szTime + 11, szErrorString);
printit(buf);
delete [] buf;
}
void LogWarningConsole(DWORD dwEvent, LPTSTR szWarning)
{
DWORD dwLastError = GetLastError();
const int cbLastError = 1024;
TCHAR szLastError[cbLastError];
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0, dwLastError, LANG_USER_DEFAULT,
szLastError, cbLastError, 0);
LPTSTR lpszStrings[2];
lpszStrings[0] = szWarning;
lpszStrings[1] = szLastError;
const int cbWarningString = 1024;
TCHAR szWarningString[cbWarningString];
FormatMessage(FORMAT_MESSAGE_FROM_HMODULE| FORMAT_MESSAGE_ARGUMENT_ARRAY,
0, dwEvent, LANG_USER_DEFAULT,
szWarningString, cbWarningString, (va_list*)lpszStrings);
time_t dwTime;
time(&dwTime);
char* szTime = ctime(&dwTime);
szTime[19] = 0;
// printf("W %s %s", szTime + 11, szWarningString);
char * buf;
buf = new char [ 3 + strlen(szTime) - 11 + strlen(szWarningString) + 5 ];
sprintf(buf ,"W %s %s", szTime + 11, szWarningString);
printit(buf);
delete [] buf;
}
void LogInfoConsole(DWORD dwEvent, LPTSTR szInformation)
{
LPTSTR lpszStrings[1];
lpszStrings[0] = szInformation;
const int cbInfoString = 1024;
TCHAR szInfoString[cbInfoString];
FormatMessage(FORMAT_MESSAGE_FROM_HMODULE| FORMAT_MESSAGE_ARGUMENT_ARRAY,
0, dwEvent, LANG_USER_DEFAULT,
szInfoString, cbInfoString, (va_list*)lpszStrings);
time_t dwTime;
time(&dwTime);
char* szTime = ctime(&dwTime);
szTime[19] = 0;
// printf("I %s %s", szTime + 11, szInfoString);
char * buf;
buf = new char [ 3 + strlen(szTime) - 11 + strlen(szInfoString) + 5 ];
sprintf(buf,"I %s %s", szTime + 11, szInfoString);
printit(buf);
delete [] buf;
}
@@ -0,0 +1,16 @@
#ifndef __TNERROR_H
#define __TNERROR_H
#ifndef __WINDOWS_H
#include <windows.h>
#endif
#include "tnmsg.h"
extern int Telnet_Redir;
int printm(LPTSTR szModule, BOOL fSystem, DWORD dwMessageId, ...);
void LogErrorConsole(LPTSTR szError);
int printit(const char * it);
#endif
@@ -0,0 +1,92 @@
///////////////////////////////////////////////////////////////////////////////
//Telnet Win32 : an ANSI telnet client.
//Copyright (C) 1998-2000 Paul Brannan
//Copyright (C) 1998 I.Ioannou
//Copyright (C) 1997 Brad Johnson
//
//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., 675 Mass Ave, Cambridge, MA 02139, USA.
//
//I.Ioannou
//[email protected]
//
///////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
//
// Module: tnetwork.cpp
//
// Contents: telnet network module
//
// Product: telnet
//
// Revisions: March 18, 1999 Paul Brannan ([email protected])
//
///////////////////////////////////////////////////////////////////////////////
#include "tnetwork.h"
void TNetwork::SetSocket(SOCKET s) {
socket = s;
net_type = TN_NETSOCKET;
local_echo = line_mode = 1;
}
void TNetwork::SetPipe(HANDLE pIn, HANDLE pOut) {
pipeIn = pIn;
pipeOut = pOut;
net_type = TN_NETPIPE;
local_echo = line_mode = 0;
}
int TNetwork::WriteString(const char *str, const int length) {
switch(net_type) {
case TN_NETSOCKET:
return send(socket, str, length, 0);
case TN_NETPIPE:
{
DWORD dwWritten;
if(!WriteFile(pipeOut, str, length, &dwWritten, (LPOVERLAPPED)NULL)) return -1;
return dwWritten;
}
}
return 0;
}
int TNetwork::ReadString (char *str, const int length) {
switch(net_type) {
case TN_NETSOCKET:
return recv(socket, str, length, 0);
case TN_NETPIPE:
{
DWORD dwRead;
if(!ReadFile(pipeIn, str, length, &dwRead, (LPOVERLAPPED)NULL)) return -1;
return dwRead;
}
}
return 0;
}
void TNetwork::do_naws(int width, int height) {
if(!naws_func) return;
char buf[100];
int len = (*naws_func)(buf, width, height);
WriteString(buf, len);
}
void TNetwork::SetLocalAddress(char *buf) {
local_address = new char[strlen(buf) + 1];
strcpy(local_address, buf);
}
@@ -0,0 +1,50 @@
// This is a simple class to handle socket connections
// (Paul Brannan 6/15/98)
#ifndef __TNETWORK_H
#define __TNETWORK_H
#include <windows.h>
enum NetworkType {TN_NETSOCKET, TN_NETPIPE};
typedef int(*Naws_func_t)(char *, int, int);
class TNetwork {
private:
SOCKET socket;
BOOL local_echo; // Paul Brannan 8/25/98
BOOL line_mode; // Paul Brannan 12/31/98
NetworkType net_type; // Paul Brannan 3/18/99
HANDLE pipeIn, pipeOut; // Paul Brannan 3/18/99
Naws_func_t naws_func;
char *local_address;
public:
TNetwork(SOCKET s = 0): socket(s), local_echo(1), line_mode(1),
net_type(TN_NETSOCKET), naws_func((Naws_func_t)NULL),
local_address((char *)NULL) {}
~TNetwork() {if(local_address) delete local_address;}
void SetSocket(SOCKET s);
SOCKET GetSocket() {return socket;}
void SetPipe(HANDLE pIn, HANDLE pOut);
void SetNawsFunc(Naws_func_t func) {naws_func = func;}
void SetLocalAddress(char *buf);
const char* GetLocalAddress() {return local_address;}
NetworkType get_net_type() {return net_type;}
int WriteString(const char *str, const int length);
int ReadString (char *str, const int length);
BOOL get_local_echo() {return local_echo;}
void set_local_echo(BOOL b) {local_echo = b;}
BOOL get_line_mode() {return line_mode;}
void set_line_mode(BOOL b) {line_mode = b;}
void do_naws(int width, int height);
};
#endif

Some files were not shown because too many files have changed in this diff Show More