/* locktest.c - file locking test utility for Windows (c) 3APA3A <3APA3A@security.nnov.ru> */ #include #include #include #include #include char* progname; void usage(void){ printf("Usage:\n %s accessmode sharemode filename\n Where accessmode is one of READ, WRITE, READWRITE, NONE\n sharemode is one of READ, WRITE, READWRITE and NONE\n", progname); exit(-1); } void showresult(void){ char buffer[256]; DWORD n=GetLastError(); if(!n)printf("PASSED\n"); else { printf("FAILED:%d\n",(int)n); FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, 0, n, 0, buffer, 256, 0); CharToOem(buffer,buffer); printf("System error text: %s\n", buffer); } SetLastError(0); } int main (int argc, char * argv[]){ DWORD accessmode, sharemode; HANDLE file; char buffer[64]; DWORD nbytes; progname=argv[0]; if(argc!=4)usage(); if(!strcmp(argv[1], "READ"))accessmode=GENERIC_READ; else if(!strcmp(argv[1], "WRITE"))accessmode=GENERIC_WRITE; else if(!strcmp(argv[1], "READWRITE"))accessmode=GENERIC_WRITE|GENERIC_READ; else if(!strcmp(argv[1], "NONE"))accessmode=0; else {printf("!accessmode\n");usage();} if(!strcmp(argv[2], "READ"))sharemode=FILE_SHARE_READ; else if(!strcmp(argv[2], "WRITE"))sharemode=FILE_SHARE_WRITE; else if(!strcmp(argv[2], "NONE"))sharemode=0; else if(!strcmp(argv[2], "READWRITE"))sharemode=GENERIC_WRITE|GENERIC_READ; else usage(); printf("Openining %s for %s with %s share...", argv[3], argv[1], argv[2]); file=CreateFile(argv[3], accessmode, sharemode, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); showresult(); if(file!=INVALID_HANDLE_VALUE){ if(accessmode&GENERIC_READ){ printf("Testing for reading..."); ReadFile(file, buffer, 16, &nbytes, 0); buffer[nbytes]=0; showresult(); printf("Red %d of max 16 bytes:%s\n", (int)nbytes, buffer); } if(accessmode&GENERIC_WRITE){ printf("Testing for writing..."); WriteFile(file, "0123456789abcdef", 16, &nbytes, 0); buffer[nbytes]=0; showresult(); printf("Written %d of 16 bytes\n", (int)nbytes); } printf("Press any key...\n"); getch(); printf("Closing file..."); CloseHandle(file); showresult(); } else printf("Invalid file handle"); return 0; }