#include "tclWinInt.h"
#define CHANNEL_NAME_SIZE 64
static char channelName[CHANNEL_NAME_SIZE+1];
static int initialized = 0;
#define FILE_PENDING (1<<0)
#define FILE_ASYNC (1<<1)
#define FILE_APPEND (1<<2)
typedef struct FileInfo {
Tcl_Channel channel;
int validMask;
int watchMask;
int flags;
HANDLE handle;
struct FileInfo *nextPtr;
} FileInfo;
static FileInfo *firstFilePtr;
typedef struct FileEvent {
Tcl_Event header;
FileInfo *infoPtr;
} FileEvent;
static int ComGetOptionProc _ANSI_ARGS_((ClientData instanceData,
Tcl_Interp *interp, char *optionName,
Tcl_DString *dsPtr));
static int ComInputProc _ANSI_ARGS_((ClientData instanceData,
char *buf, int toRead, int *errorCode));
static int ComSetOptionProc _ANSI_ARGS_((ClientData instanceData,
Tcl_Interp *interp, char *optionName,
char *value));
static int FileBlockProc _ANSI_ARGS_((ClientData instanceData,
int mode));
static void FileChannelExitHandler _ANSI_ARGS_((
ClientData clientData));
static void FileCheckProc _ANSI_ARGS_((ClientData clientData,
int flags));
static int FileCloseProc _ANSI_ARGS_((ClientData instanceData,
Tcl_Interp *interp));
static int FileEventProc _ANSI_ARGS_((Tcl_Event *evPtr,
int flags));
static int FileGetHandleProc _ANSI_ARGS_((ClientData instanceData,
int direction, ClientData *handlePtr));
static void FileInit _ANSI_ARGS_((void));
static int FileInputProc _ANSI_ARGS_((ClientData instanceData,
char *buf, int toRead, int *errorCode));
static int FileOutputProc _ANSI_ARGS_((ClientData instanceData,
char *buf, int toWrite, int *errorCode));
static int FileSeekProc _ANSI_ARGS_((ClientData instanceData,
long offset, int mode, int *errorCode));
static void FileSetupProc _ANSI_ARGS_((ClientData clientData,
int flags));
static void FileWatchProc _ANSI_ARGS_((ClientData instanceData,
int mask));
static Tcl_ChannelType fileChannelType = {
"file",
FileBlockProc,
FileCloseProc,
FileInputProc,
FileOutputProc,
FileSeekProc,
NULL,
NULL,
FileWatchProc,
FileGetHandleProc,
};
static Tcl_ChannelType comChannelType = {
"com",
FileBlockProc,
FileCloseProc,
ComInputProc,
FileOutputProc,
NULL,
ComSetOptionProc,
ComGetOptionProc,
FileWatchProc,
FileGetHandleProc
};
static void
FileInit()
{
initialized = 1;
firstFilePtr = NULL;
Tcl_CreateEventSource(FileSetupProc, FileCheckProc, NULL);
Tcl_CreateExitHandler(FileChannelExitHandler, NULL);
}
static void
FileChannelExitHandler(clientData)
ClientData clientData;
{
Tcl_DeleteEventSource(FileSetupProc, FileCheckProc, NULL);
initialized = 0;
}
void
FileSetupProc(data, flags)
ClientData data;
int flags;
{
FileInfo *infoPtr;
Tcl_Time blockTime = { 0, 0 };
if (!(flags & TCL_FILE_EVENTS)) {
return;
}
for (infoPtr = firstFilePtr; infoPtr != NULL; infoPtr = infoPtr->nextPtr) {
if (infoPtr->watchMask) {
Tcl_SetMaxBlockTime(&blockTime);
break;
}
}
}
static void
FileCheckProc(data, flags)
ClientData data;
int flags;
{
FileEvent *evPtr;
FileInfo *infoPtr;
if (!(flags & TCL_FILE_EVENTS)) {
return;
}
for (infoPtr = firstFilePtr; infoPtr != NULL; infoPtr = infoPtr->nextPtr) {
if (infoPtr->watchMask && !(infoPtr->flags & FILE_PENDING)) {
infoPtr->flags |= FILE_PENDING;
evPtr = (FileEvent *) ckalloc(sizeof(FileEvent));
evPtr->header.proc = FileEventProc;
evPtr->infoPtr = infoPtr;
Tcl_QueueEvent((Tcl_Event *) evPtr, TCL_QUEUE_TAIL);
}
}
}
static int
FileEventProc(evPtr, flags)
Tcl_Event *evPtr;
int flags;
{
FileEvent *fileEvPtr = (FileEvent *)evPtr;
FileInfo *infoPtr;
if (!(flags & TCL_FILE_EVENTS)) {
return 0;
}
for (infoPtr = firstFilePtr; infoPtr != NULL; infoPtr = infoPtr->nextPtr) {
if (fileEvPtr->infoPtr == infoPtr) {
infoPtr->flags &= ~(FILE_PENDING);
Tcl_NotifyChannel(infoPtr->channel, infoPtr->watchMask);
break;
}
}
return 1;
}
static int
FileBlockProc(instanceData, mode)
ClientData instanceData;
int mode;
{
FileInfo *infoPtr = (FileInfo *) instanceData;
if (mode == TCL_MODE_NONBLOCKING) {
infoPtr->flags |= FILE_ASYNC;
} else {
infoPtr->flags &= ~(FILE_ASYNC);
}
return 0;
}
static int
FileCloseProc(instanceData, interp)
ClientData instanceData;
Tcl_Interp *interp;
{
FileInfo *fileInfoPtr = (FileInfo *) instanceData;
FileInfo **nextPtrPtr;
int errorCode = 0;
FileWatchProc(instanceData, 0);
if (CloseHandle(fileInfoPtr->handle) == FALSE) {
TclWinConvertError(GetLastError());
errorCode = errno;
}
for (nextPtrPtr = &firstFilePtr; (*nextPtrPtr) != NULL;
nextPtrPtr = &((*nextPtrPtr)->nextPtr)) {
if ((*nextPtrPtr) == fileInfoPtr) {
(*nextPtrPtr) = fileInfoPtr->nextPtr;
break;
}
}
ckfree((char *)fileInfoPtr);
return errorCode;
}
static int
FileSeekProc(instanceData, offset, mode, errorCodePtr)
ClientData instanceData;
long offset;
int mode;
int *errorCodePtr;
{
FileInfo *infoPtr = (FileInfo *) instanceData;
DWORD moveMethod;
DWORD newPos;
*errorCodePtr = 0;
if (mode == SEEK_SET) {
moveMethod = FILE_BEGIN;
} else if (mode == SEEK_CUR) {
moveMethod = FILE_CURRENT;
} else {
moveMethod = FILE_END;
}
newPos = SetFilePointer(infoPtr->handle, offset, NULL, moveMethod);
if (newPos == 0xFFFFFFFF) {
TclWinConvertError(GetLastError());
return -1;
}
return newPos;
}
static int
FileInputProc(instanceData, buf, bufSize, errorCode)
ClientData instanceData;
char *buf;
int bufSize;
int *errorCode;
{
FileInfo *infoPtr;
DWORD bytesRead;
*errorCode = 0;
infoPtr = (FileInfo *) instanceData;
if (ReadFile(infoPtr->handle, (LPVOID) buf, (DWORD) bufSize, &bytesRead,
(LPOVERLAPPED) NULL) != FALSE) {
return bytesRead;
}
TclWinConvertError(GetLastError());
*errorCode = errno;
if (errno == EPIPE) {
return 0;
}
return -1;
}
static int
FileOutputProc(instanceData, buf, toWrite, errorCode)
ClientData instanceData;
char *buf;
int toWrite;
int *errorCode;
{
FileInfo *infoPtr = (FileInfo *) instanceData;
DWORD bytesWritten;
*errorCode = 0;
if (infoPtr->flags & FILE_APPEND) {
SetFilePointer(infoPtr->handle, 0, NULL, FILE_END);
}
if (WriteFile(infoPtr->handle, (LPVOID) buf, (DWORD) toWrite, &bytesWritten,
(LPOVERLAPPED) NULL) == FALSE) {
TclWinConvertError(GetLastError());
*errorCode = errno;
return -1;
}
FlushFileBuffers(infoPtr->handle);
return bytesWritten;
}
static void
FileWatchProc(instanceData, mask)
ClientData instanceData;
int mask;
{
FileInfo *infoPtr = (FileInfo *) instanceData;
Tcl_Time blockTime = { 0, 0 };
infoPtr->watchMask = mask & infoPtr->validMask;
if (infoPtr->watchMask) {
Tcl_SetMaxBlockTime(&blockTime);
}
}
static int
FileGetHandleProc(instanceData, direction, handlePtr)
ClientData instanceData;
int direction;
ClientData *handlePtr;
{
FileInfo *infoPtr = (FileInfo *) instanceData;
if (direction & infoPtr->validMask) {
*handlePtr = (ClientData) infoPtr->handle;
return TCL_OK;
} else {
return TCL_ERROR;
}
}
static int
ComInputProc(instanceData, buf, bufSize, errorCode)
ClientData instanceData;
char *buf;
int bufSize;
int *errorCode;
{
FileInfo *infoPtr;
DWORD bytesRead;
DWORD dw;
COMSTAT cs;
*errorCode = 0;
infoPtr = (FileInfo *) instanceData;
if (ClearCommError(infoPtr->handle, &dw, &cs)) {
if (dw != 0) {
*errorCode = EIO;
return -1;
}
if (cs.cbInQue != 0) {
if ((DWORD) bufSize > cs.cbInQue) {
bufSize = cs.cbInQue;
}
} else {
if (infoPtr->flags & FILE_ASYNC) {
errno = *errorCode = EAGAIN;
return -1;
} else {
bufSize = 1;
}
}
}
if (ReadFile(infoPtr->handle, (LPVOID) buf, (DWORD) bufSize, &bytesRead,
(LPOVERLAPPED) NULL) == FALSE) {
TclWinConvertError(GetLastError());
*errorCode = errno;
return -1;
}
return bytesRead;
}
static int
ComSetOptionProc(instanceData, interp, optionName, value)
ClientData instanceData;
Tcl_Interp *interp;
char *optionName;
char *value;
{
FileInfo *infoPtr;
DCB dcb;
int len;
infoPtr = (FileInfo *) instanceData;
len = strlen(optionName);
if ((len > 1) && (strncmp(optionName, "-mode", len) == 0)) {
if (GetCommState(infoPtr->handle, &dcb)) {
if ((BuildCommDCB(value, &dcb) == FALSE) ||
(SetCommState(infoPtr->handle, &dcb) == FALSE)) {
if (interp) {
Tcl_AppendResult(interp, "bad value for -mode: should be ",
"baud,parity,data,stop", NULL);
}
return TCL_ERROR;
} else {
return TCL_OK;
}
} else {
if (interp) {
Tcl_AppendResult(interp, "can't get comm state", NULL);
}
return TCL_ERROR;
}
} else {
return Tcl_BadChannelOption(interp, optionName, "mode");
}
}
static int
ComGetOptionProc(instanceData, interp, optionName, dsPtr)
ClientData instanceData;
Tcl_Interp *interp;
char *optionName;
Tcl_DString *dsPtr;
{
FileInfo *infoPtr;
DCB dcb;
int len;
infoPtr = (FileInfo *) instanceData;
if (optionName == NULL) {
Tcl_DStringAppendElement(dsPtr, "-mode");
len = 0;
} else {
len = strlen(optionName);
}
if ((len == 0) ||
((len > 1) && (strncmp(optionName, "-mode", len) == 0))) {
if (GetCommState(infoPtr->handle, &dcb) == 0) {
Tcl_DStringAppendElement(dsPtr, "");
} else {
char parity;
char *stop;
char buf[32];
parity = 'n';
if (dcb.Parity < 4) {
parity = "noems"[dcb.Parity];
}
stop = (dcb.StopBits == ONESTOPBIT) ? "1" :
(dcb.StopBits == ONE5STOPBITS) ? "1.5" : "2";
wsprintf(buf, "%d,%c,%d,%s", dcb.BaudRate, parity, dcb.ByteSize,
stop);
Tcl_DStringAppendElement(dsPtr, buf);
}
return TCL_OK;
} else {
return Tcl_BadChannelOption(interp, optionName, "mode");
}
}
Tcl_Channel
TclpOpenFileChannel(interp, fileName, modeString, permissions)
Tcl_Interp *interp;
char *fileName;
char *modeString;
int permissions;
{
FileInfo *infoPtr;
int seekFlag, mode, channelPermissions;
DWORD accessMode, createMode, shareMode, flags;
char *nativeName;
Tcl_DString buffer;
DCB dcb;
Tcl_ChannelType *channelTypePtr;
HANDLE handle;
if (!initialized) {
FileInit();
}
mode = TclGetOpenMode(interp, modeString, &seekFlag);
if (mode == -1) {
return NULL;
}
nativeName = Tcl_TranslateFileName(interp, fileName, &buffer);
if (nativeName == NULL) {
return NULL;
}
switch (mode & (O_RDONLY | O_WRONLY | O_RDWR)) {
case O_RDONLY:
accessMode = GENERIC_READ;
channelPermissions = TCL_READABLE;
break;
case O_WRONLY:
accessMode = GENERIC_WRITE;
channelPermissions = TCL_WRITABLE;
break;
case O_RDWR:
accessMode = (GENERIC_READ | GENERIC_WRITE);
channelPermissions = (TCL_READABLE | TCL_WRITABLE);
break;
default:
panic("TclpOpenFileChannel: invalid mode value");
break;
}
switch (mode & (O_CREAT | O_EXCL | O_TRUNC)) {
case (O_CREAT | O_EXCL):
case (O_CREAT | O_EXCL | O_TRUNC):
createMode = CREATE_NEW;
break;
case (O_CREAT | O_TRUNC):
createMode = CREATE_ALWAYS;
break;
case O_CREAT:
createMode = OPEN_ALWAYS;
break;
case O_TRUNC:
case (O_TRUNC | O_EXCL):
createMode = TRUNCATE_EXISTING;
break;
default:
createMode = OPEN_EXISTING;
break;
}
if (mode & O_CREAT) {
if (permissions & S_IWRITE) {
flags = FILE_ATTRIBUTE_NORMAL;
} else {
flags = FILE_ATTRIBUTE_READONLY;
}
} else {
flags = GetFileAttributes(nativeName);
if (flags == 0xFFFFFFFF) {
flags = 0;
}
}
shareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
handle = CreateFile(nativeName, accessMode, shareMode, NULL, createMode,
flags, (HANDLE) NULL);
if (handle == INVALID_HANDLE_VALUE) {
DWORD err;
openerr:
err = GetLastError();
if ((err & 0xffffL) == ERROR_OPEN_FAILED) {
err = (mode & O_CREAT) ? ERROR_FILE_EXISTS : ERROR_FILE_NOT_FOUND;
}
TclWinConvertError(err);
if (interp != (Tcl_Interp *) NULL) {
Tcl_AppendResult(interp, "couldn't open \"", fileName, "\": ",
Tcl_PosixError(interp), (char *) NULL);
}
Tcl_DStringFree(&buffer);
return NULL;
}
if (GetFileType(handle) == FILE_TYPE_CHAR) {
dcb.DCBlength = sizeof( DCB ) ;
if (GetCommState(handle, &dcb)) {
COMMTIMEOUTS cto;
CloseHandle(handle);
handle = CreateFile(nativeName, accessMode, 0, NULL, OPEN_EXISTING,
flags, NULL);
if (handle == INVALID_HANDLE_VALUE) {
goto openerr;
}
SetCommMask(handle, EV_RXCHAR);
SetupComm(handle, 4096, 4096);
PurgeComm(handle, PURGE_TXABORT | PURGE_RXABORT | PURGE_TXCLEAR
| PURGE_RXCLEAR);
cto.ReadIntervalTimeout = MAXDWORD;
cto.ReadTotalTimeoutMultiplier = 0;
cto.ReadTotalTimeoutConstant = 0;
cto.WriteTotalTimeoutMultiplier = 0;
cto.WriteTotalTimeoutConstant = 0;
SetCommTimeouts(handle, &cto);
GetCommState(handle, &dcb);
SetCommState(handle, &dcb);
channelTypePtr = &comChannelType;
} else {
channelTypePtr = &fileChannelType;
}
} else {
channelTypePtr = &fileChannelType;
}
Tcl_DStringFree(&buffer);
infoPtr = (FileInfo *) ckalloc((unsigned) sizeof(FileInfo));
infoPtr->nextPtr = firstFilePtr;
firstFilePtr = infoPtr;
infoPtr->validMask = channelPermissions;
infoPtr->watchMask = 0;
infoPtr->flags = (mode & O_APPEND) ? FILE_APPEND : 0;
infoPtr->handle = handle;
sprintf(channelName, "file%d", (int) handle);
infoPtr->channel = Tcl_CreateChannel(channelTypePtr, channelName,
(ClientData) infoPtr, channelPermissions);
if (seekFlag) {
if (Tcl_Seek(infoPtr->channel, 0, SEEK_END) < 0) {
if (interp != (Tcl_Interp *) NULL) {
Tcl_AppendResult(interp, "could not seek to end of file on \"",
channelName, "\": ", Tcl_PosixError(interp),
(char *) NULL);
}
Tcl_Close(NULL, infoPtr->channel);
return NULL;
}
}
Tcl_SetChannelOption(NULL, infoPtr->channel, "-translation", "auto");
Tcl_SetChannelOption(NULL, infoPtr->channel, "-eofchar", "\032 {}");
return infoPtr->channel;
}
Tcl_Channel
Tcl_MakeFileChannel(handle, mode)
ClientData handle;
int mode;
{
char channelName[20];
FileInfo *infoPtr;
if (!initialized) {
FileInit();
}
if (mode == 0) {
return NULL;
}
sprintf(channelName, "file%d", (int) handle);
for (infoPtr = firstFilePtr; infoPtr != NULL; infoPtr = infoPtr->nextPtr) {
if (infoPtr->handle == (HANDLE) handle) {
return (mode == infoPtr->validMask) ? infoPtr->channel : NULL;
}
}
infoPtr = (FileInfo *) ckalloc((unsigned) sizeof(FileInfo));
infoPtr->nextPtr = firstFilePtr;
firstFilePtr = infoPtr;
infoPtr->validMask = mode;
infoPtr->watchMask = 0;
infoPtr->flags = 0;
infoPtr->handle = (HANDLE) handle;
infoPtr->channel = Tcl_CreateChannel(&fileChannelType, channelName,
(ClientData) infoPtr, mode);
Tcl_SetChannelOption(NULL, infoPtr->channel, "-translation", "auto");
Tcl_SetChannelOption(NULL, infoPtr->channel, "-eofchar", "\032 {}");
return infoPtr->channel;
}
Tcl_Channel
TclGetDefaultStdChannel(type)
int type;
{
Tcl_Channel channel;
HANDLE handle;
int mode;
char *bufMode;
DWORD handleId;
switch (type) {
case TCL_STDIN:
handleId = STD_INPUT_HANDLE;
mode = TCL_READABLE;
bufMode = "line";
break;
case TCL_STDOUT:
handleId = STD_OUTPUT_HANDLE;
mode = TCL_WRITABLE;
bufMode = "line";
break;
case TCL_STDERR:
handleId = STD_ERROR_HANDLE;
mode = TCL_WRITABLE;
bufMode = "none";
break;
default:
panic("TclGetDefaultStdChannel: Unexpected channel type");
break;
}
handle = GetStdHandle(handleId);
if ((handle == INVALID_HANDLE_VALUE) || (handle == 0)) {
return NULL;
}
channel = Tcl_MakeFileChannel(handle, mode);
if ((Tcl_SetChannelOption((Tcl_Interp *) NULL, channel, "-translation",
"auto") == TCL_ERROR)
|| (Tcl_SetChannelOption((Tcl_Interp *) NULL, channel, "-eofchar",
"\032 {}") == TCL_ERROR)
|| (Tcl_SetChannelOption((Tcl_Interp *) NULL, channel,
"-buffering", bufMode) == TCL_ERROR)) {
Tcl_Close((Tcl_Interp *) NULL, channel);
return (Tcl_Channel) NULL;
}
return channel;
}