├── lock.h ├── debug.h ├── Makefile ├── lock.c ├── history.txt ├── fs.h ├── README.TXT ├── fs.c └── ethersrv.c /lock.h: -------------------------------------------------------------------------------- 1 | /* 2 | * part of ethersrv 3 | * 4 | * Copyright (C) 2017 Mateusz Viste 5 | */ 6 | 7 | #ifndef LOCK_H_SENTINEL 8 | #define LOCK_H_SENTINEL 9 | 10 | /* acquire the lock file */ 11 | int lockme(char *lockfile); 12 | 13 | /* release the lock file */ 14 | void unlockme(char *lockfile); 15 | 16 | #endif 17 | -------------------------------------------------------------------------------- /debug.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Part of ethersrv 3 | */ 4 | 5 | /* set to 1 to enable debug */ 6 | #define DEBUG 0 7 | 8 | /* set to 1 for frame loss simulation (for tests only!) */ 9 | #define SIMLOSS 0 10 | 11 | /* do not modify the magic below */ 12 | 13 | #if DEBUG > 0 14 | 15 | #define DBG printf 16 | 17 | #else 18 | 19 | #define DBG(...) 20 | 21 | #endif 22 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # 2 | # ethersrv makefile for FreeBSD and Linux (GCC and Clang) 3 | # http://etherdfs.sourceforge.net 4 | # 5 | # Copyright (C) 2017, 2018 Mateusz Viste 6 | # Copyright (C) 2020 Michael Ortmann 7 | # Copyright (C) 2023-2025 E. Voirin (oerg866) 8 | # 9 | 10 | CFLAGS := -DDEBUG=1 -O2 -Wall -std=gnu89 -pedantic -Wextra -s -Wno-long-long -Wno-variadic-macros -Wformat-security -D_FORTIFY_SOURCE=1 11 | 12 | CC ?= gcc 13 | 14 | ethersrv: ethersrv.c fs.c fs.h lock.c lock.h debug.h 15 | $(CC) ethersrv.c fs.c lock.c -o ethersrv $(CFLAGS) 16 | 17 | clean: 18 | rm -f ethersrv *.o 19 | -------------------------------------------------------------------------------- /lock.c: -------------------------------------------------------------------------------- 1 | /* 2 | * part of ethersrv 3 | * http://etherdfs.sourceforge.net 4 | * 5 | * Copyright (C) 2017 Mateusz Viste 6 | */ 7 | 8 | #include 9 | #include 10 | 11 | #include "lock.h" 12 | 13 | /* acquire the lock file */ 14 | int lockme(char *lockfile) { 15 | FILE *fd; 16 | /* does the file exist? */ 17 | fd = fopen(lockfile, "rb"); 18 | if (fd != NULL) { 19 | fclose(fd); 20 | return(-1); 21 | } 22 | /* file doesn't seem to exist - create it then */ 23 | fd = fopen(lockfile, "wb"); 24 | if (fd == NULL) return(-1); 25 | fclose(fd); 26 | return(0); 27 | } 28 | 29 | /* release the lock file */ 30 | void unlockme(char *lockfile) { 31 | unlink(lockfile); 32 | } 33 | -------------------------------------------------------------------------------- /history.txt: -------------------------------------------------------------------------------- 1 | History file of ethersrv-866 2 | 3 | 20250325: 4 | - Fixed a bunch of more problems with host<->client file/path name handling 5 | - Incorporated FreeBSD port, fixes and additions from Michael Ortmann 6 | 7 | 20230802: 8 | - fixed spaces being included in truncated FCB names 9 | - made longer file names accessible through truncated names 10 | - file and directory accesses are no longer broken by case sensitivity 11 | 12 | 20180203m 13 | - renamed from ethersrv-linux to ethersrv 14 | - ported to musl / Alpine Linux 15 | - ported to FreeBSD 16 | - enhanced CC and CFLAGS handling 17 | 18 | 20180203: 19 | - fixed file truncation when writing to offset 0 (patch by Peter De Wachter), 20 | - added the '-f' option (patch by Philip Linde), 21 | - dummy support for lock/unlock operations: always answers with success, 22 | - debug output prints FCB filenames without trailing garbage. 23 | 24 | 20170415: 25 | - added support for EtherDFS frames with embedded length information. 26 | 27 | 20170406: 28 | - added support for EtherDFS frames with embedded cksum. 29 | 30 | 20170401: 31 | - FindFirst listings are cached so FindNext always iterates correctly even 32 | if the application deletes files at the same time, 33 | - if trying to open file in directory that doesn't exist, returns 'path not 34 | found' (err 3) instead of 'file not found' (err 2), 35 | - purging old entries from cache if not used for more than one hour, 36 | - ethersrv-linux turns itself into a daemon at start time, 37 | - returns 'access denied' (err 5) when trying to delete a read-only file. 38 | 39 | 20170304: 40 | - ability to expose multiple drives (up to 24, i.e. from C: to Z:), 41 | - return '.' and '..' in file searches (expected by MS-DOS 'tree'), 42 | - support for wildcard file removals (as in 'del *.txt'), 43 | - fixed DISKSPACE calls so MS-DOS is able to understand disk space correctly, 44 | - forcing all file and directory names to lower case to avoid troubles when 45 | running over a case-sensitive file system, 46 | - added support for 'seek from end' (SKFMEND), 47 | - RENAME aborts if destination already exists (was overwriting it), 48 | - a failing FFirst call returns err 12h (no more files) instead of 02h (file 49 | not found) - this mimics MS-DOS 5/6/7 and is required by LapLink 5, 50 | - ethersrv uses a lock file to avoid being launched twice. 51 | 52 | 20170211: 53 | - added support for 'enhanced open' (SPOPNFIL) - used by COPY in MS-DOS, 54 | - changed FFirst/FNext so FNext doesn't need to know the directory each time. 55 | 56 | 20170207: 57 | - implemented a lost-frames-recovery algorithm to avoid corrupting data on 58 | congested networks (thanks to Ulrich Hansen for extensive testing), 59 | - fixed attributes matching on FindFirst/FindNext, 60 | - fixed writing to files at arbitrary offset (different than zero and end). 61 | 62 | 20170205: 63 | - added support for 'CLOSE FILE', 'RENAME FILE' and 'SET ATTRIBS' actions, 64 | - fixed a file descriptor leak while fetching file attributes. 65 | 66 | 20170202: 67 | - fixed a crash due to realpath() being called on an undersized char array. 68 | 69 | 20170131: 70 | - first public release. 71 | -------------------------------------------------------------------------------- /fs.h: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | */ 4 | 5 | #ifndef FS_H_SENTINEL 6 | #define FS_H_SENTINEL 7 | 8 | struct fileprops { 9 | char fcbname[12]; /* FCB-style file name (FILE0001TXT) */ 10 | unsigned long fsize; 11 | unsigned long ftime; 12 | unsigned char fattr; 13 | }; 14 | 15 | /* DOS/FAT attribs: 1=RO 2=HID 4=SYS 8=VOL 16=DIR 32=ARCH 64=DEVICE */ 16 | #define FAT_RO 1 17 | #define FAT_HID 2 18 | #define FAT_SYS 4 19 | #define FAT_VOL 8 20 | #define FAT_DIR 16 21 | #define FAT_ARC 32 22 | #define FAT_DEV 64 23 | 24 | /* flags used with findfile() calls */ 25 | #define FFILE_ISROOT 1 26 | #define FFILE_ISFAT 2 27 | 28 | #define DIR_MAX 512 29 | 30 | /* returns the "start sector" of a filesystem item (file or directory). 31 | * returns 0xffff on error */ 32 | unsigned short getitemss(char *f); 33 | 34 | char *sstoitem(unsigned short ss); 35 | 36 | /* turns a character c into its upper-case variant */ 37 | char upchar(char c); 38 | 39 | /* translates a filename string into a fcb-style block ("FILE0001TXT") */ 40 | void filename2fcb(char *d, char *s); 41 | 42 | /* provides DOS-like attributes for item i, as well as size, filling fprops 43 | * accordingly. returns item's attributes or 0xff on error. 44 | * DOS attr flags: 1=RO 2=HID 4=SYS 8=VOL 16=DIR 32=ARCH 64=DEVICE */ 45 | unsigned char getitemattr(char *i, struct fileprops *fprops, unsigned char isfat); 46 | 47 | /* set attributes fattr on file i. returns 0 on success, non-zero otherwise. */ 48 | int setitemattr(char *i, unsigned char fattr); 49 | 50 | /* searches for file matching template tmpl in directory dss (dss is the starting sector of the directory, as obtained via getitemss) with attribute attr, fills 'out' with the nth match. returns 0 on success, non-zero otherwise. */ 51 | int findfile(struct fileprops *f, unsigned short dss, char *tmpl, unsigned char attr, unsigned short *fpos, int flags); 52 | 53 | /* creates or truncates a file f in directory d with attributes attr. returns 0 on success (and f filled), non-zero otherwise. */ 54 | int createfile(struct fileprops *f, char *d, char *fn, unsigned char attr, unsigned char fatflag); 55 | 56 | /* returns disks total size, in bytes, or 0 on error. also sets dfree to the 57 | * amount of available bytes */ 58 | unsigned long long diskinfo(char *path, unsigned long long *dfree); 59 | 60 | /* try to create directory, return 0 on success, non-zero otherwise */ 61 | int makedir(char *d); 62 | 63 | /* try to remove directory, return 0 on success, non-zero otherwise */ 64 | int remdir(char *d); 65 | 66 | /* change to directory d, return 0 if worked, non-zero otherwise (used 67 | * essentially to check whether the directory exists or not) */ 68 | int changedir(char *d); 69 | 70 | /* reads len bytes from file fname starting offset, writes to buff. returns 71 | * amount of bytes read or a negative value on error. */ 72 | long readfile(unsigned char *buff, unsigned short fss, unsigned long offset, unsigned short len); 73 | 74 | /* writes len bytes from buff to file fname, starting at offset. returns 75 | * amount of bytes written or a negative value on error. */ 76 | long writefile(unsigned char *buff, unsigned short fss, unsigned long offset, unsigned short len); 77 | 78 | /* remove all files matching the pattern, returns the number of removed files if any found, 79 | * or -1 on error or if no matching file found */ 80 | int delfiles(char *pattern); 81 | 82 | /* rename fn1 into fn2 */ 83 | int renfile(char *fn1, char *fn2); 84 | 85 | /* checks if a path resides on a FAT filesystem, returns 0 if so, non-zero otherwise */ 86 | int isfat(char *d); 87 | 88 | /* returns the size of an open file (or -1 on error) */ 89 | long getfopsize(unsigned short fss); 90 | 91 | /* Converts a path full of lowercase 8.3 names to the host name, provided it exists */ 92 | int shorttolong(char *dst, char *src, const char *root); 93 | 94 | #endif 95 | -------------------------------------------------------------------------------- /README.TXT: -------------------------------------------------------------------------------- 1 | 2 | ethersrv-866 3 | Copyright (C) 2017-2025 Mateusz Viste, Michael Ortmann, E.Voirin (oerg866) 4 | 5 | Based on ethersrv-linux, hosted at: http://etherdfs.sourceforge.net 6 | 7 | MUSL, FreeBSD port by Michael Ortmann 8 | Long file name and other modifications by Eric Voirin (oerg866@googlemail.com) 9 | 10 | ethersrv is an implementation of EtherSRV for FreeBSD/Linux. It allows a 11 | computer to share its drive over Ethernet with multiple DOS clients running 12 | EtherDFS. 13 | 14 | Requirements: 15 | ethersrv-866 requires a fairly recent FreeBSD/Linux OS to run, and gcc to 16 | compile. 17 | 18 | How to build: 19 | just type 'make', then an 'ethersrv' binary should appear (unless things 20 | go wrong). 21 | 22 | How to run: 23 | ethersrv [options] iface directory [directory2] ... [directoryN] 24 | 25 | Note that, in order to be able to operate on ethernet sockets, ethersrv-linux 26 | needs to have the CAP_NEW_RAW system capability. Usually this means that you 27 | have to run it as root. 28 | 29 | where: 30 | 'iface' is the name of the network interface you wish to hook ethersrv to 31 | (for example eth0) 32 | 'directory' is the directory in your filesystem you wish to share (for 33 | example /mnt/dosfs). You can mention several directories (up to 34 | 24), the first one will always be mapped to a virtual "C:" drive, 35 | the second to "D:", etc. 36 | 37 | available options: 38 | -f do not daemonize the process (stay in foreground) 39 | 40 | 41 | Notes: 42 | * it is HIGHLY recommended to run ethersrv-linux over a FAT filesystem. 43 | Other file systems might work, too, but FAT attributes will be unavailable 44 | and DOS might get puzzled with upper/lower case filenames. The presence 45 | and/or order of '.' and '..' directory entries might also end up being 46 | unusual, possibly confusing applications that rely on the assumption that 47 | both these entries are first in non-root directories. 48 | * some Linux distributions treat FAT volumes in a case-sensitive way by 49 | default. Such behavior leads to troubles when used by DOS (through 50 | EtherDFS). I tested two Linux modules for FAT support: 'msdos' and 'vfat'. 51 | The 'msdos' module worked consistently for me at all times. The 'vfat' 52 | module, on the other hand, is known to interpret file names as UTF-8 on 53 | some distributions, which makes the file system case-sensitive. To avoid 54 | this, either use the 'msdos' module, or mount your vfat volume with an 55 | explicit iocharset. Examples: 56 | # mount /dev/sda2 /mnt/fat -t msdos 57 | # mount /dev/sda2 /mnt/fat -t vfat -o iocharset=cp437 58 | You can also create a FAT disk image and mount that. Example: 59 | # fallocate -l 1024M fat.img 60 | # mkfs.msdos fat.img 61 | # mount -o loop fat.img /mnt/fat 62 | 63 | 64 | IMPORTANT: 65 | 66 | While longer file names and files with different capitalization can be 67 | accessed in this fork, it will only pick the first file it finds that matches 68 | to acces, meaning that in case of naming conflicts you may end up accessing 69 | the wrong file or directory. 70 | 71 | ===[ License ]================================================================ 72 | 73 | ethersrv is distributed under the terms of the MIT License, as listed below. 74 | 75 | Copyright (C) 2017, 2018 Mateusz Viste 76 | Copyright (C) 2020, Michael Ortmann 77 | Copyright (C) 2023-2025 E. Voirin (oerg866) 78 | 79 | Permission is hereby granted, free of charge, to any person obtaining a copy 80 | of this software and associated documentation files (the "Software"), to deal 81 | in the Software without restriction, including without limitation the rights 82 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 83 | copies of the Software, and to permit persons to whom the Software is 84 | furnished to do so, subject to the following conditions: 85 | 86 | The above copyright notice and this permission notice shall be included in all 87 | copies or substantial portions of the Software. 88 | 89 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 90 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 91 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 92 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 93 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 94 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 95 | SOFTWARE. 96 | -------------------------------------------------------------------------------- /fs.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of the ethersrv project 3 | * Copyright (C) 2017 Mateusz Viste 4 | * Copyright (C) 2020 Michael Ortmann 5 | * Copyright (C) 2023-2025 E. Voirin (oerg866) 6 | */ 7 | 8 | #include 9 | #include 10 | #include 11 | #include 12 | #include 13 | #include /* statvfs() for diskfree calls */ 14 | #include /* stat() */ 15 | #include 16 | #include 17 | #include 18 | #include /* free() */ 19 | #include 20 | #include /* time_t, struct tm... */ 21 | #include 22 | #ifdef __FreeBSD__ 23 | #include /* statfs() */ 24 | #else 25 | #include 26 | #include /* struct statfs */ 27 | #endif 28 | #include 29 | #include 30 | 31 | #include "debug.h" 32 | #include "fs.h" /* include self for control */ 33 | 34 | /* database containing file/dir identifiers and their names - this is used 35 | * whenever ethersrv needs to provide etherdfs with a 16bit identifier that 36 | * etherdfs will subsequently use to refer to this file or dir (typically used 37 | * during FindFirst+FindNext steps and Open/Create+Write/Read. 38 | * the struct may also contain an entire directory listing computed by FFirst 39 | * (and used then by FNext) */ 40 | static struct sfsdb { 41 | char *name; 42 | time_t lastused; 43 | struct sdirlist { /* pointer to dir listing, if dir and if generated by FFirst */ 44 | struct fileprops fprops; 45 | struct sdirlist *next; 46 | } *dirlist; 47 | } fsdb[65536]; 48 | 49 | /* frees a sdirlist linked list */ 50 | static void freedirlist(struct sdirlist *d) { 51 | while (d != NULL) { 52 | struct sdirlist *victim = d; 53 | d = d->next; 54 | free(victim); 55 | } 56 | } 57 | 58 | /* returns the "start sector" of a filesystem item (file or directory). 59 | * it registers the item into the file cache and returns its id or 0xffff on 60 | * error */ 61 | unsigned short getitemss(char *f) { 62 | unsigned short i, firstfree = 0xffffu, oldest = 0; 63 | time_t now = time(NULL); 64 | /* see if not already in cache */ 65 | for (i = 0; i < 0xffffu; i++) { 66 | /* is it what I am looking after? */ 67 | if ((fsdb[i].name != NULL) && (strcmp(fsdb[i].name, f) == 0)) { 68 | fsdb[i].lastused = now; 69 | return(i); 70 | } 71 | /* if the entry is not what I was looking for, check its last usage and remove if older than one hour */ 72 | if ((now - fsdb[i].lastused) > 3600) { 73 | free(fsdb[i].name); 74 | freedirlist(fsdb[i].dirlist); 75 | memset(&(fsdb[i]), 0, sizeof(struct sfsdb)); 76 | } 77 | /* if slot free, remember it, perhaps we'll use it */ 78 | if ((firstfree == 0xffffu) && (fsdb[i].name == NULL)) { 79 | firstfree = i; 80 | } else if (fsdb[oldest].lastused > fsdb[i].lastused) { /* otherwise see if it's the oldest entry (I might remove it later if no choice) */ 81 | oldest = i; 82 | } 83 | } 84 | /* not found - if no free slot available, pick the oldest one and replace it */ 85 | if (firstfree == 0xffffu) { 86 | firstfree = oldest; 87 | free(fsdb[oldest].name); 88 | freedirlist(fsdb[oldest].dirlist); 89 | memset(&(fsdb[oldest]), 0, sizeof(struct sfsdb)); 90 | } 91 | /* register it */ 92 | fsdb[firstfree].name = strdup(f); 93 | 94 | if (fsdb[firstfree].name == NULL) { 95 | fprintf(stderr, "ERROR: OUT OF MEM!\n"); 96 | return(0xffffu); 97 | } 98 | fsdb[firstfree].lastused = now; 99 | return(firstfree); 100 | } 101 | 102 | char *sstoitem(unsigned short ss) { 103 | return(fsdb[ss].name); 104 | } 105 | 106 | /* turns a character c into its upper-case variant */ 107 | char upchar(char c) { 108 | if ((c >= 'a') && (c <= 'z')) c -= ('a' - 'A'); 109 | return(c); 110 | } 111 | 112 | /* turns a string into all-upper-case characters, up to n chars max */ 113 | static void upstring(char *s, int n) { 114 | while ((n-- != 0) && (*s != 0)) { 115 | *s = upchar(*s); 116 | s++; 117 | } 118 | } 119 | 120 | /* translates a filename string into a fcb-style block ("FILE0001TXT") */ 121 | void filename2fcb(char *d, char *s) { 122 | int i; 123 | int j; 124 | /* fill the FCB block with spaces */ 125 | for (i = 0; i < 11; i++) d[i] = ' '; 126 | 127 | /* cover '.' and '..' entries */ 128 | for (i = 0; i < 8; i++) { 129 | if (s[i] != '.') break; 130 | d[i] = '.'; 131 | } 132 | 133 | /* fill in the filename, up to 8 chars or first dot, whichever comes first */ 134 | j = i; 135 | 136 | for (; i < 8; i++) { 137 | if ((s[j] == '.') || (s[j] == 0)) break; 138 | while ((s[j]) == ' ') { 139 | j++; 140 | } 141 | d[i] = upchar(s[j]); 142 | j++; 143 | } 144 | 145 | s += i; 146 | /* fast forward to either the first dot or NULL-terminator */ 147 | for (; ((*s != '.') && (*s != 0)); s++); 148 | if (*s == 0) return; 149 | s++; /* skip the dot */ 150 | /* fill in the extension */ 151 | d += 8; 152 | for (j = 0; j < 3; j++) { 153 | if ((s[j] == '.') || (s[j] == 0) || (s[j] == ' ')) break; 154 | *d = upchar(s[j]); 155 | d++; 156 | } 157 | } 158 | 159 | /* converts a time_t into a DWORD with DOS (FAT-style) timestamp bits 160 | 24 16 8 0 161 | +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+ 162 | |Y|Y|Y|Y|Y|Y|Y|M| |M|M|M|D|D|D|D|D| |h|h|h|h|h|m|m|m| |m|m|m|s|s|s|s|s| 163 | +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+ 164 | \___________/\________/\_________/ \________/\____________/\_________/ 165 | year month day hour minute seconds */ 166 | static unsigned long time2dos(time_t t) { 167 | unsigned long res; 168 | struct tm *ltime; 169 | ltime = localtime(&t); 170 | res = ltime->tm_year - 80; /* tm_year is years from 1900, while FAT needs years from 1980 */ 171 | res <<= 4; 172 | res |= ltime->tm_mon + 1; /* tm_mon is in range 0..11 while FAT expects 1..12 */ 173 | res <<= 5; 174 | res |= ltime->tm_mday; 175 | res <<= 5; 176 | res |= ltime->tm_hour; 177 | res <<= 6; 178 | res |= ltime->tm_min; 179 | res <<= 5; 180 | res |= (ltime->tm_sec >> 1); /* DOS stores seconds divided by two */ 181 | return(res); 182 | } 183 | 184 | /* match FCB-style filename to a FCB-style mask ("FILE0001???"), returns 0 if 185 | * matching, non-zero otherwise - a FCB block is *exactly* 11 bytes long */ 186 | static int matchfile2mask(char *msk, char *fil) { 187 | int i; 188 | /* compare filename to mask */ 189 | for (i = 0; i < 11; i++) { 190 | if ((upchar(fil[i]) != upchar(msk[i])) && (msk[i] != '?')) return(-1); 191 | } 192 | return(0); 193 | } 194 | 195 | 196 | /* provides DOS-like attributes for item i, as well as size, filling fprops 197 | * accordingly. returns item's attributes or 0xff on error. 198 | * DOS attr flags: 1=RO 2=HID 4=SYS 8=VOL 16=DIR 32=ARCH 64=DEVICE */ 199 | unsigned char getitemattr(char *i, struct fileprops *fprops, unsigned char fatflag) { 200 | uint32_t attr; 201 | #ifndef __FreeBSD__ 202 | int fd; 203 | #endif 204 | struct stat statbuf; 205 | if (stat(i, &statbuf) != 0) return(0xff); /* error (probably doesn't exist) */ 206 | /* zero out fprops and fill it out */ 207 | if (fprops != NULL) { 208 | char *fname = i; 209 | char *ptr; 210 | /* set fname to the file part of i */ 211 | for (ptr = i; *ptr != 0; ptr++) { 212 | if (((*ptr == '/') || (*ptr == '\\')) && (*(ptr+1) != 0)) fname = ptr + 1; 213 | } 214 | /* zero out struct and set timestamp & fcbname */ 215 | memset(fprops, 0, sizeof(struct fileprops)); 216 | fprops->ftime = time2dos(statbuf.st_mtime); 217 | filename2fcb(fprops->fcbname, fname); 218 | } 219 | /* is this is a directory? */ 220 | if (S_ISDIR(statbuf.st_mode)) { 221 | if (fprops != NULL) fprops->fattr = 16; /* ATTR_DIR */ 222 | return(16); 223 | } 224 | /* not a directory, set size */ 225 | if (fprops != NULL) fprops->fsize = statbuf.st_size; 226 | /* if not a FAT drive, return a fake attribute of 0x20 (archive) */ 227 | if (fatflag == 0) return(0x20); 228 | #ifdef __FreeBSD__ 229 | { 230 | /* map FreeBSD to Linux */ 231 | attr = 0; 232 | if (statbuf.st_flags & UF_READONLY) 233 | attr |= 1; /* ATTR_RO */ 234 | if (statbuf.st_flags & UF_HIDDEN) 235 | attr |= 2; /* ATTR_HIDDEN */ 236 | if (statbuf.st_flags & UF_SYSTEM) 237 | attr |= 4; /* ATTR_SYS */ 238 | if (statbuf.st_flags & UF_ARCHIVE) 239 | attr |= 32; /* ATTR_ARCH */ 240 | #else 241 | /* try to fetch DOS attributes by calling the FAT IOCTL API */ 242 | fd = open(i, O_RDONLY); 243 | if (fd == -1) return(0xff); 244 | if (ioctl(fd, FAT_IOCTL_GET_ATTRIBUTES, &attr) < 0) { 245 | fprintf(stderr, "Failed to fetch attributes of '%s'\n", i); 246 | close(fd); 247 | return(0); 248 | } else { 249 | close(fd); 250 | #endif 251 | if (fprops != NULL) fprops->fattr = attr; 252 | return(attr); 253 | } 254 | } 255 | 256 | /* set attributes fattr on file i. returns 0 on success, non-zero otherwise. */ 257 | int setitemattr(char *i, unsigned char fattr) { 258 | int res; 259 | #ifdef __FreeBSD__ 260 | /* map Linux to FreeBSD */ 261 | unsigned long flags = 0; 262 | if (fattr & 1) /* ATTR_RO */ 263 | flags |= UF_READONLY; 264 | if (fattr & 2) /* ATTR_HIDDEN */ 265 | flags |= UF_HIDDEN; 266 | if (fattr & 4) /* ATTR_SYS */ 267 | flags |= UF_SYSTEM; 268 | if (fattr & 32) /* ATTR_ARCH */ 269 | flags |= UF_ARCHIVE; 270 | res = chflags(i, flags); 271 | #else 272 | int fd = open(i, O_RDONLY); 273 | if (fd == -1) return(-1); 274 | res = ioctl(fd, FAT_IOCTL_SET_ATTRIBUTES, &fattr); 275 | close(fd); 276 | #endif 277 | if (res < 0) return(-1); 278 | return(0); 279 | } 280 | 281 | /* generates a directory listing for *root and returns the number of file 282 | * system entries, or a negative value on error */ 283 | static long gendirlist(struct sfsdb *root, unsigned char fatflag) { 284 | char fullpath[1024]; 285 | int fullpathoffset; 286 | struct dirent *diridx; 287 | DIR *dp; 288 | struct sdirlist *lastnode = NULL, *newnode; 289 | long res = 0; 290 | freedirlist(root->dirlist); 291 | dp = opendir(root->name); 292 | if (dp == NULL) return(-1); 293 | fullpathoffset = sprintf(fullpath, "%s/", root->name); 294 | for (;;) { 295 | diridx = readdir(dp); 296 | if (diridx == NULL) break; 297 | newnode = calloc(1, sizeof(struct sdirlist)); 298 | if (newnode == NULL) { 299 | fprintf(stderr, "ERROR: out of mem!"); 300 | break; 301 | } 302 | sprintf(fullpath + fullpathoffset, "%s", diridx->d_name); 303 | getitemattr(fullpath, &(newnode->fprops), fatflag); 304 | /* add new node to linked list */ 305 | if (lastnode == NULL) { 306 | root->dirlist = newnode; 307 | } else { 308 | lastnode->next = newnode; 309 | } 310 | lastnode = newnode; 311 | res++; 312 | } 313 | closedir(dp); 314 | return(res); 315 | } 316 | 317 | /* searches for file matching the FCB-style template fcbtmpl in directory dss (dss is the starting sector of the directory, as obtained via getitemss) with AT MOST attributes attr, fills 'out' with the nth match. returns 0 on success, non-zero otherwise. *nth is updated with the nth id of the file that matched */ 318 | int findfile(struct fileprops *f, unsigned short dss, char *fcbtmpl, unsigned char attr, unsigned short *nth, int flags) { 319 | int n = 0; 320 | struct sdirlist *dirlist; 321 | /* recompute the dir listing if operation is FFirst (nth == 0) or if no 322 | * cache found */ 323 | if ((*nth == 0) || (fsdb[dss].dirlist == NULL)) { 324 | long count = gendirlist(&(fsdb[dss]), flags & FFILE_ISFAT); 325 | if (count < 0) { 326 | fprintf(stderr, "Error: failed to scan dir '%s'\n", fsdb[dss].name); 327 | return(-1); 328 | #ifdef DEBUG 329 | } else { 330 | DBG("scanned dir '%s' and found %ld items\n", fsdb[dss].name, count); 331 | for (dirlist = fsdb[dss].dirlist; dirlist != NULL; dirlist = dirlist->next) { 332 | DBG(" '%s' attr %02Xh (%ld bytes)\n", dirlist->fprops.fcbname, dirlist->fprops.fattr, dirlist->fprops.fsize); 333 | } 334 | #endif 335 | } 336 | } 337 | /* */ 338 | for (dirlist = fsdb[dss].dirlist; dirlist != NULL; dirlist = dirlist->next) { 339 | /* forward to where we need to start listing */ 340 | n++; 341 | if (n <= *nth) continue; 342 | /* skip '.' and '..' items if directory is root */ 343 | if ((dirlist->fprops.fcbname[0] == '.') && (flags & FFILE_ISROOT)) continue; 344 | 345 | /* if no match, continue */ 346 | if (matchfile2mask(fcbtmpl, dirlist->fprops.fcbname) != 0) continue; 347 | /* do attributes match? (return only items with AT MOST the specified combination of hidden, system, and directory attributes if no VOL bit set, otherwise look for VOL only. 348 | DOS attribs: 1=RO 2=HID 4=SYS 8=VOL 16=DIR 32=ARCH 64=DEV */ 349 | if (attr == 0x08) { /* I want VOL */ 350 | if ((dirlist->fprops.fattr & 0x08) == 0) continue; 351 | } else { /* else return any file with at most the specified attributes */ 352 | if ((attr | (dirlist->fprops.fattr & 0x16)) != attr) continue; 353 | } 354 | break; 355 | } 356 | if (dirlist != NULL) { 357 | *nth = n; 358 | memcpy(f, &(dirlist->fprops), sizeof(struct sdirlist)); 359 | return(0); 360 | } 361 | return(-1); 362 | } 363 | 364 | 365 | /* creates or truncates a file f in directory d with attributes attr. returns 0 on success (and f filled), non-zero otherwise. */ 366 | int createfile(struct fileprops *f, char *d, char *fn, unsigned char attr, unsigned char fatflag) { 367 | char fullpath[512]; 368 | FILE *fd; 369 | sprintf(fullpath, "%s/%s", d, fn); 370 | /* try to create/truncate the file */ 371 | fd = fopen(fullpath, "wb"); 372 | if (fd == NULL) return(-1); 373 | fclose(fd); 374 | /* set attribs (only if FAT drive) */ 375 | if (fatflag != 0) { 376 | if (setitemattr(fullpath, attr) != 0) fprintf(stderr, "Error: failed to set attribute %02Xh to '%s'\n", attr, fullpath); 377 | } 378 | /* collect and set attributes */ 379 | getitemattr(fullpath, f, fatflag); 380 | return(0); 381 | } 382 | 383 | 384 | /* returns disks total size, in bytes, or 0 on error. also sets dfree to the 385 | * amount of available bytes */ 386 | unsigned long long diskinfo(char *path, unsigned long long *dfree) { 387 | struct statvfs buf; 388 | unsigned long long res; 389 | if (statvfs(path, &buf) != 0) return(0); 390 | res = buf.f_blocks; 391 | res *= buf.f_frsize; 392 | *dfree = buf.f_bfree; 393 | *dfree *= buf.f_bsize; 394 | return(res); 395 | } 396 | 397 | /* try to create directory, return 0 on success, non-zero otherwise */ 398 | int makedir(char *d) { 399 | return(mkdir(d, 0)); 400 | } 401 | 402 | /* try to remove directory, return 0 on success, non-zero otherwise */ 403 | int remdir(char *d) { 404 | return(rmdir(d)); 405 | } 406 | 407 | /* change to directory d, return 0 if worked, non-zero otherwise (used 408 | * essentially to check whether the directory exists or not) */ 409 | int changedir(char *d) { 410 | return(chdir(d)); 411 | } 412 | 413 | /* reads len bytes from file starting at sector fss, from offset, writes to 414 | * buff. returns amount of bytes read or a negative value on error. */ 415 | long readfile(unsigned char *buff, unsigned short fss, unsigned long offset, unsigned short len) { 416 | long res; 417 | char *fname; 418 | FILE *fd; 419 | fname = fsdb[fss].name; 420 | if (fname == NULL) return(-1); 421 | fd = fopen(fname, "rb"); 422 | if (fd == NULL) return(-1); 423 | if (fseek(fd, offset, SEEK_SET) != 0) { 424 | fclose(fd); 425 | return(-1); 426 | } 427 | res = fread(buff, 1, len, fd); 428 | fclose(fd); 429 | return(res); 430 | } 431 | 432 | 433 | /* writes len bytes from buff to file starting at sect fss, starting at 434 | * offset. returns amount of bytes written or a negative value on error. */ 435 | long writefile(unsigned char *buff, unsigned short fss, unsigned long offset, unsigned short len) { 436 | long res; 437 | char *fname; 438 | FILE *fd; 439 | fname = fsdb[fss].name; 440 | if (fname == NULL) return(-1); 441 | /* if len is 0, then it means "truncate" or "extend" ! */ 442 | if (len == 0) { 443 | DBG("truncate '%s' to %lu bytes\n", fname, offset); 444 | if (truncate(fname, offset) != 0) fprintf(stderr, "Error: truncate() failed\n"); 445 | return(0); 446 | } 447 | /* otherwise do a regular write */ 448 | DBG("write %u bytes into file '%s' at offset %lu\n", len, fname, offset); 449 | fd = fopen(fname, "r+b"); 450 | if (fd == NULL) return(-1); 451 | if (fseek(fd, offset, SEEK_SET) != 0) { 452 | DBG("fseek() to %lu failed!\n", offset); 453 | fclose(fd); 454 | return(-1); 455 | } 456 | res = fwrite(buff, 1, len, fd); 457 | fclose(fd); 458 | return(res); 459 | } 460 | 461 | 462 | /* remove all files matching the pattern, returns the number of removed files if any found, 463 | * or -1 on error or if no matching file found */ 464 | int delfiles(char *pattern) { 465 | unsigned int i, fileoffset = 0; 466 | int ispattern = 0; 467 | char patterncopy[512]; 468 | char dirnamefcb[12]; 469 | char *dir, *fil; 470 | char filfcb[12]; 471 | struct dirent *diridx; 472 | DIR *dp; 473 | /* scan the pattern for '?' characters, and find where the file part starts, also copy the pattern to patterncopy[] */ 474 | for (i = 0; pattern[i] != 0; i++) { 475 | if (pattern[i] == '?') ispattern = 1; 476 | if (pattern[i] == '/') fileoffset = i; 477 | patterncopy[i] = pattern[i]; 478 | } 479 | patterncopy[i] = 0; 480 | /* if regular file, delete it right away*/ 481 | if (ispattern == 0) { 482 | if (unlink(pattern) != 0) { 483 | DBG("Error: failure to delete file '%s' (%s)\n", pattern, strerror(errno)); 484 | return(-1); 485 | } 486 | return(1); 487 | } 488 | /* if pattern, get dir and fil parts and iterate over all directory */ 489 | dir = patterncopy; 490 | patterncopy[fileoffset] = 0; 491 | fil = patterncopy + fileoffset + 1; 492 | filename2fcb(filfcb, fil); 493 | /* iterate over the directory and delete whatever is matching the pattern */ 494 | dp = opendir(dir); 495 | if (dp == NULL) return(-1); 496 | for (;;) { 497 | diridx = readdir(dp); 498 | if (diridx == NULL) break; 499 | /* skip directories */ 500 | if (diridx->d_type == DT_DIR) continue; 501 | /* if match, delete the file and continue */ 502 | filename2fcb(dirnamefcb, diridx->d_name); 503 | if (matchfile2mask(filfcb, dirnamefcb) == 0) { 504 | char fname[512]; 505 | sprintf(fname, "%s/%s", dir, diridx->d_name); 506 | if (unlink(fname) != 0) fprintf(stderr, "failed to delete '%s'\n", fname); 507 | } 508 | } 509 | closedir(dp); 510 | 511 | return(0); 512 | } 513 | 514 | /* rename fn1 into fn2 */ 515 | int renfile(char *fn1, char *fn2) { 516 | return(rename(fn1, fn2)); 517 | } 518 | 519 | /* checks if a path resides on a FAT filesystem, returns 0 if so, non-zero otherwise */ 520 | int isfat(char *d) { 521 | struct statfs buf; 522 | if (statfs(d, &buf) < 0) { 523 | DBG("Error: statfs(): %s\n", strerror(errno)); 524 | return(-1); 525 | } 526 | #ifdef __FreeBSD__ 527 | if (strcmp(buf.f_fstypename, "msdosfs")) 528 | #else 529 | if (buf.f_type != MSDOS_SUPER_MAGIC) 530 | #endif 531 | return(-1); 532 | return(0); 533 | } 534 | 535 | /* returns the size of an open file (or -1 on error) */ 536 | long getfopsize(unsigned short fss) { 537 | struct fileprops fprops; 538 | char *fname = fsdb[fss].name; 539 | if (fname == NULL) return(-1); 540 | if (getitemattr(fname, &fprops, 0) == 0xff) return(-1); 541 | return(fprops.fsize); 542 | } 543 | 544 | 545 | /**/ 546 | int shorttolong(char *dst, char *src, const char *root) { 547 | int found = 0; 548 | 549 | char *writeptr = dst; 550 | char *tmpdir = NULL; 551 | char *tmpdir_next = NULL; 552 | char to_find_fcb [12]; 553 | char tmp_fcb [12]; 554 | 555 | struct dirent *entry; 556 | DIR *dir; 557 | 558 | size_t root_len = strlen(root); 559 | 560 | to_find_fcb[11] = 0; /* null terminate these */ 561 | tmp_fcb[11] = 0; 562 | 563 | assert(strncmp(root, src, strlen(root)) == 0); 564 | 565 | src += root_len; 566 | writeptr += sprintf(dst, "%s/", root); 567 | 568 | printf("shorttolong: %s %s %s\n", dst, src, root); 569 | 570 | if (src[0] != '/') { 571 | DBG("ERROR: invalid string for shorttolong encountered: '%s'\n", src); 572 | return -1; 573 | } 574 | 575 | src++; 576 | 577 | /* get the first token */ 578 | tmpdir = strtok(src, "/"); 579 | 580 | /* walk through other tokens */ 581 | while (tmpdir != NULL) { 582 | 583 | tmpdir_next = strtok(NULL, "/"); 584 | 585 | /* Turn this back into an FCB string */ 586 | filename2fcb(to_find_fcb, tmpdir); 587 | 588 | /* Walk the current directory depicted by destination */ 589 | 590 | dir = opendir(dst); 591 | 592 | if (dir == NULL) { 593 | DBG("ERROR: Failed to open directory %s", dst); 594 | return -1; 595 | } 596 | 597 | found = 0; 598 | 599 | while (!found && (entry = readdir(dir)) != NULL) { 600 | if ((strcmp(entry->d_name, ".") == 0) || (strcmp(entry->d_name, "..") == 0)) 601 | continue; 602 | 603 | /* get FCB name for this */ 604 | filename2fcb(tmp_fcb, entry->d_name); 605 | 606 | /*if if its fcb name matches what we are trying to find, this may be our destination. */ 607 | 608 | if (strcmp(tmp_fcb, to_find_fcb) == 0) { 609 | /*if we're not in the last section of the input path, this must be a directory*/ 610 | 611 | if ((tmpdir_next != NULL) && (entry->d_type != DT_DIR)) { 612 | DBG("The name matched but isnt a directory.\n"); 613 | continue; 614 | } 615 | 616 | writeptr += sprintf(writeptr, "%s", entry->d_name); 617 | 618 | /* it is a directory, so we must append a / to our destination */ 619 | if (tmpdir_next != NULL) { 620 | writeptr += sprintf(writeptr, "/"); 621 | } 622 | 623 | found = 1; 624 | 625 | } 626 | 627 | } 628 | 629 | closedir(dir); 630 | 631 | if (!found) { 632 | /* Print the raw version as is to the destination string. Is useful for mkdir. */ 633 | writeptr += sprintf(writeptr, "%s", tmpdir); 634 | 635 | DBG("Part of the path was not found - ergo it does not exist.\n"); 636 | return -1; 637 | } 638 | 639 | tmpdir = tmpdir_next; 640 | } 641 | 642 | DBG("shorttolong RESULT: %s\n", dst); 643 | 644 | return 0; 645 | } 646 | -------------------------------------------------------------------------------- /ethersrv.c: -------------------------------------------------------------------------------- 1 | /* 2 | * ethersrv is serving files through the EtherDFS protocol. Runs on FreeBSD 3 | * and Linux. 4 | * 5 | * http://etherdfs.sourceforge.net 6 | * 7 | * ethersrv is distributed under the terms of the MIT License, as listed below. 8 | * 9 | * Copyright (C) 2017, 2018 Mateusz Viste 10 | * Copyright (c) 2020 Michael Ortmann 11 | * Copyright (c) 2023-2025 E. Voirin (oerg866) 12 | * 13 | * Permission is hereby granted, free of charge, to any person obtaining a 14 | * copy of this software and associated documentation files (the "Software"), 15 | * to deal in the Software without restriction, including without limitation 16 | * the rights to use, copy, modify, merge, publish, distribute, sublicense, 17 | * and/or sell copies of the Software, and to permit persons to whom the 18 | * Software is furnished to do so, subject to the following conditions: 19 | * 20 | * The above copyright notice and this permission notice shall be included in 21 | * all copies or substantial portions of the Software. 22 | * 23 | * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 24 | * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 25 | * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 26 | * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 27 | * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 28 | * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 29 | * DEALINGS IN THE SOFTWARE. 30 | */ 31 | 32 | #include /* htons() */ 33 | #include 34 | #include /* fcntl(), open() */ 35 | #ifdef __FreeBSD__ 36 | #include /* u_int32_t */ 37 | #include /* BIOCSETIF */ 38 | #include /* ETHER_ADDR_LEN */ 39 | #include /* LLADDR */ 40 | #include 41 | #include 42 | #else 43 | #include /* le16toh(), le32toh() */ 44 | #include 45 | #include /* sockaddr_ll */ 46 | #endif 47 | #include /* PATH_MAX and such */ 48 | #include 49 | #include 50 | #include 51 | #include 52 | #include /* mempcy() */ 53 | #include 54 | #include 55 | #include /* uint16_t, uint32_t */ 56 | #include /* realpath() */ 57 | #include /* time() */ 58 | #include /* close(), getopt(), optind */ 59 | 60 | #include "debug.h" 61 | #include "fs.h" 62 | #include "lock.h" 63 | 64 | /* program version */ 65 | #define PVER "20250324" 66 | 67 | #define ETHERTYPE_DFS 0xEDF5 68 | 69 | /* protocol version (single byte, must be in sync with etherdfs) */ 70 | #define PROTOVER 2 71 | 72 | 73 | /* answer cache - last answers sent to clients - used if said client didn't 74 | * receive my answer, and re-sends his requests so I don't process this 75 | * request again (which might be dangerous in case of write requests, like 76 | * write to file, delete file, rename file, etc. For every client that ever 77 | * sent me a query, there is exactly one entry in the cache. */ 78 | #define ANSWCACHESZ 16 79 | static struct struct_answcache { 80 | unsigned char frame[1520]; /* entire frame that was sent (first 6 bytes is the client's mac) */ 81 | time_t timestamp; /* time of answer (so if cache full I can drop oldest) */ 82 | unsigned short len; /* frame's length */ 83 | } answcache[ANSWCACHESZ]; 84 | 85 | #define BUFF_LEN 2048 86 | 87 | /* all the calls I support are in the range AL=0..2Eh - the list below serves 88 | * as a convenience to compare AL (subfunction) values */ 89 | enum AL_SUBFUNCTIONS { 90 | AL_INSTALLCHK = 0x00, 91 | AL_RMDIR = 0x01, 92 | AL_MKDIR = 0x03, 93 | AL_CHDIR = 0x05, 94 | AL_CLSFIL = 0x06, 95 | AL_CMMTFIL = 0x07, 96 | AL_READFIL = 0x08, 97 | AL_WRITEFIL = 0x09, 98 | AL_LOCKFIL = 0x0A, 99 | AL_UNLOCKFIL = 0x0B, 100 | AL_DISKSPACE = 0x0C, 101 | AL_SETATTR = 0x0E, 102 | AL_GETATTR = 0x0F, 103 | AL_RENAME = 0x11, 104 | AL_DELETE = 0x13, 105 | AL_OPEN = 0x16, 106 | AL_CREATE = 0x17, 107 | AL_FINDFIRST = 0x1B, 108 | AL_FINDNEXT = 0x1C, 109 | AL_SKFMEND = 0x21, 110 | AL_UNKNOWN_2D = 0x2D, 111 | AL_SPOPNFIL = 0x2E, 112 | AL_UNKNOWN = 0xFF 113 | }; 114 | 115 | 116 | /* an array with flags indicating whether given drive is FAT-based or not */ 117 | static unsigned char drivesfat[26]; /* 0 if not, non-zero otherwise */ 118 | 119 | /* the flag is set when ethersrv is expected to terminate */ 120 | static sig_atomic_t volatile terminationflag = 0; 121 | 122 | static void sigcatcher(int sig) { 123 | switch (sig) { 124 | case SIGTERM: 125 | case SIGQUIT: 126 | case SIGINT: 127 | terminationflag = 1; 128 | break; 129 | default: 130 | break; 131 | } 132 | } 133 | 134 | /* returns a printable version of a FCB block (ie. with added null terminator), this is used only by debug routines */ 135 | #if DEBUG > 0 136 | static char *pfcb(char *s) { 137 | static char r[12] = "FILENAMEEXT"; 138 | memcpy(r, s, 11); 139 | return(r); 140 | } 141 | #endif 142 | 143 | /* turns a character c into its low-case variant */ 144 | static char lochar(char c) { 145 | if ((c >= 'A') && (c <= 'Z')) c += ('a' - 'A'); 146 | return(c); 147 | } 148 | 149 | /* turns a string into all-lower-case characters, up to n chars max */ 150 | static void lostring(char *s, int n) { 151 | while ((n-- != 0) && (*s != 0)) { 152 | *s = lochar(*s); 153 | s++; 154 | } 155 | } 156 | 157 | /* finds the cache entry related to given client */ 158 | static struct struct_answcache *findcacheentry(unsigned char *clientmac) { 159 | int i, oldest = 0; 160 | /* iterate through cache entries until matching mac is found */ 161 | for (i = 0; i < ANSWCACHESZ; i++) { 162 | if (memcmp(answcache[i].frame, clientmac, 6) == 0) { 163 | return(&(answcache[i])); /* found! */ 164 | } 165 | /* is this the oldest entry? remember it. */ 166 | if (answcache[i].timestamp < answcache[oldest].timestamp) oldest = i; 167 | } 168 | /* if nothing found, over-write the oldest entry */ 169 | return(&(answcache[oldest])); 170 | } 171 | 172 | 173 | /* checks whether dir is belonging to the root directory. returns 0 if so, 1 174 | * otherwise */ 175 | static int isroot(char *root, char *dir) { 176 | /* fast-forward to the 'virtual directory' part */ 177 | while ((*root != 0) && (*dir != 0)) { 178 | root++; 179 | dir++; 180 | } 181 | /* skip any leading / */ 182 | while (*dir == '/') dir++; 183 | /* is there any subsequent '/' ? if so, then it's not root */ 184 | while (*dir != 0) { 185 | if (*dir == '/') return(0); 186 | dir++; 187 | } 188 | /* otherwise it's root */ 189 | return(1); 190 | } 191 | 192 | 193 | /* explode a full X:\DIR\FILE????.??? search path into directory and mask */ 194 | static void explodepath(char *dir, char *file, char *source, int sourcelen) { 195 | int i, lastbackslash; 196 | /* if drive present, skip it */ 197 | if (source[1] == ':') { 198 | source += 2; 199 | sourcelen -= 2; 200 | } 201 | /* find last slash or backslash and copy source into dir up to this last backslash */ 202 | lastbackslash = 0; 203 | for (i = 0; i < sourcelen; i++) { 204 | if ((source[i] == '\\') || (source[i] == '/')) lastbackslash = i; 205 | } 206 | memcpy(dir, source, lastbackslash + 1); 207 | dir[lastbackslash + 1] = 0; 208 | /* copy file/mask into file */ 209 | memcpy(file, source+lastbackslash+1, sourcelen - (lastbackslash + 1)); 210 | file[sourcelen - (lastbackslash + 1)] = 0; 211 | } 212 | 213 | 214 | /* replaces all rep chars in string s by repby */ 215 | static void charreplace(char *s, char rep, char repby) { 216 | while (*s != 0) { 217 | if (*s == rep) *s = repby; 218 | s++; 219 | } 220 | } 221 | 222 | /* copies everything after last slash into dst */ 223 | static void copy_after_last_slash(char *dst, const char *src) { 224 | const char *last_slash = strrchr(src, '/'); 225 | 226 | if (last_slash) 227 | strcpy(dst, last_slash + 1); 228 | } 229 | 230 | 231 | 232 | static int process(struct struct_answcache *answer, unsigned char *reqbuff, int reqbufflen, unsigned char *mymac, char **rootarray) { 233 | int query, reqdrv, reqflags; 234 | int reslen = 0; 235 | unsigned short *ax; /* pointer to store the value of AX after the query */ 236 | unsigned char *answ; /* convenience pointer to answer->frame */ 237 | unsigned short *wreqbuff; /* same as query, but word-based (16 bits) */ 238 | unsigned short *wansw; /* same as answer->frame, but word-based (16 bits) */ 239 | char *root; 240 | answ = answer->frame; 241 | /* must be at least 60 bytes long */ 242 | if (reqbufflen < 60) return(-1); 243 | /* does it match the cache entry (same seq and same mac and len > 0)? if so, just re-send it again */ 244 | if ((answ[57] == reqbuff[57]) && (memcmp(answ, reqbuff + 6, 6) == 0) && (answer->len > 0)) { 245 | #if SIMLOSS > 0 246 | fprintf(stderr, "Cache HIT (seq %u)\n", answ[57]); 247 | #endif 248 | return(answer->len); 249 | } 250 | 251 | /* copy all headers as-is */ 252 | memcpy(answ, reqbuff, 60); 253 | 254 | /* switch src and dst addresses so the reply header is ready */ 255 | memcpy(answ, answ + 6, 6); /* copy source mac into dst field */ 256 | memcpy(answ + 6, mymac, 6); /* copy my mac into source field */ 257 | /* remember the pointer to the AX result, and fetch reqdrv and AL query */ 258 | ax = (uint16_t *)answ + 29; 259 | reqdrv = reqbuff[58] & 31; /* 5 lowest -> drive */ 260 | reqflags = reqbuff[58] >> 5; /* 3 highest bits -> flags */ 261 | reqflags = reqflags; /* just so the compiler won't complain (I don't use flags yet) */ 262 | query = reqbuff[59]; 263 | /* skip eth headers now, as well as padding, seq, reqdrv and AL */ 264 | reqbuff += 60; 265 | answ += 60; 266 | reqbufflen -= 60; 267 | reslen = 0; 268 | /* set up wansw and wreqbuff */ 269 | wansw = (uint16_t *)answ; 270 | wreqbuff = (uint16_t *)reqbuff; 271 | 272 | /* is the drive valid? (C: - Z:) */ 273 | if ((reqdrv < 2) || (reqdrv > 25)) { /* 0=A, 1=B, 2=C, etc */ 274 | fprintf(stderr, "invalid drive value: 0x%02Xh\n", reqdrv); 275 | return(-3); 276 | } 277 | /* do I know this drive? */ 278 | root = rootarray[reqdrv]; 279 | if (root == NULL) { 280 | fprintf(stderr, "unknown drive: %c: (%02Xh)\n", 'A' + reqdrv, reqdrv); 281 | return(-3); 282 | } 283 | /* assume success (hence AX == 0 most of the time) */ 284 | *ax = 0; 285 | /* let's look at the exact query */ 286 | DBG("Got query: %02Xh [%02X %02X %02X %02X]\n", query, reqbuff[0], reqbuff[1], reqbuff[2], reqbuff[3]); 287 | if (query == AL_DISKSPACE) { 288 | unsigned long long diskspace, freespace; 289 | DBG("DISKSPACE for drive '%c:'\n", 'A' + reqdrv); 290 | diskspace = diskinfo(root, &freespace); 291 | /* limit results to slightly under 2 GiB (otherwise MS-DOS is confused) */ 292 | if (diskspace >= 2lu*1024*1024*1024) diskspace = 2lu*1024*1024*1024 - 1; 293 | if (freespace >= 2lu*1024*1024*1024) freespace = 2lu*1024*1024*1024 - 1; 294 | DBG("TOTAL: %llu KiB ; FREE: %llu KiB\n", diskspace >> 10, freespace >> 10); 295 | *ax = 1; /* AX: media id (8 bits) | sectors per cluster (8 bits) -- MSDOS tolerates only 1 here! */ 296 | wansw[1] = htole16(32768); /* CX: bytes per sector */ 297 | diskspace >>= 15; /* space to number of 32K clusters */ 298 | freespace >>= 15; /* space to number of 32K clusters */ 299 | wansw[0] = htole16(diskspace); /* BX: total clusters */ 300 | wansw[2] = htole16(freespace); /* DX: available clusters */ 301 | reslen += 6; 302 | } else if ((query == AL_READFIL) && (reqbufflen == 8)) { /* AL=08h */ 303 | uint16_t len, fileid; 304 | uint32_t offset; 305 | long readlen; 306 | offset = le32toh(((uint32_t *)reqbuff)[0]); 307 | fileid = le16toh(wreqbuff[2]); 308 | len = le16toh(wreqbuff[3]); 309 | DBG("Asking for %u bytes of the file #%u, starting offset %u\n", len, fileid, offset); 310 | readlen = readfile(answ, fileid, offset, len); 311 | if (readlen < 0) { 312 | fprintf(stderr, "ERROR: invalid handle\n"); 313 | *ax = 5; /* "access denied" */ 314 | } else { 315 | reslen += readlen; 316 | } 317 | } else if ((query == AL_WRITEFIL) && (reqbufflen >= 6)) { /* AL=09h */ 318 | uint16_t fileid; 319 | uint32_t offset; 320 | long writelen; 321 | offset = le32toh(((uint32_t *)reqbuff)[0]); 322 | fileid = le16toh(wreqbuff[2]); 323 | DBG("Writing %u bytes into file #%u, starting offset %u\n", reqbufflen - 6, fileid, offset); 324 | writelen = writefile(reqbuff + 6, fileid, offset, reqbufflen - 6); 325 | if (writelen < 0) { 326 | fprintf(stderr, "ERROR: Access denied"); 327 | *ax = 5; /* "access denied" */ 328 | } else { 329 | wansw[0] = htole16(writelen); 330 | reslen += 2; 331 | } 332 | } else if ((query == AL_LOCKFIL) || (query == AL_UNLOCKFIL)) { /* 0x0A / 0x0B */ 333 | /* I do nothing, except lying that lock/unlock succeeded */ 334 | } else if (query == AL_FINDFIRST) { /* 0x1B */ 335 | struct fileprops fprops; 336 | char directory[DIR_MAX]; 337 | char host_directory[DIR_MAX]; 338 | unsigned short dirss; 339 | char filemask[16], filemaskfcb[12]; 340 | int offset; 341 | unsigned fattr; 342 | unsigned short fpos = 0; 343 | int flags; 344 | fattr = reqbuff[0]; 345 | offset = sprintf(directory, "%s/", root); 346 | /* */ 347 | /* explode the full "\DIR\FILE????.???" search path into directory and mask */ 348 | explodepath(directory + offset, filemask, (char *)reqbuff + 1, reqbufflen - 1); 349 | lostring(directory + offset, -1); 350 | lostring(filemask, -1); 351 | charreplace(directory, '\\', '/'); 352 | /* */ 353 | filename2fcb(filemaskfcb, filemask); 354 | DBG("FindFirst in '%s'\nfilemask: '%s' (FCB '%s')\nattribs: 0x%2X\n", directory, filemask, pfcb(filemaskfcb), fattr); 355 | flags = 0; 356 | if (isroot(root, directory) != 0) flags |= FFILE_ISROOT; 357 | if (drivesfat[reqdrv] != 0) flags |= FFILE_ISFAT; 358 | 359 | /* try to get the host name for this string */ 360 | if (shorttolong(host_directory, directory, root) != 0) { 361 | fprintf(stderr, "FINDFIRST Error (%s): Cannot obtain host path for directory.", directory); 362 | /* let the rest of the code path deal with error handling, whatever... */ 363 | } 364 | 365 | dirss = getitemss(host_directory); 366 | if ((dirss == 0xffffu) || (findfile(&fprops, dirss, filemaskfcb, fattr, &fpos, flags) != 0)) { 367 | DBG("No matching file found\n"); 368 | *ax = 0x12; /* 0x12 is "no more files" -- one would assume 0x02 "file not found" would be better, but that's not what MS-DOS 5.x does, some applications rely on a failing FFirst to return 0x12 (for example LapLink 5) */ 369 | } else { /* found a file */ 370 | DBG("found file: FCB '%s' (attr %02Xh)\n", pfcb(fprops.fcbname), fprops.fattr); 371 | answ[0] = fprops.fattr; /* fattr (1=RO 2=HID 4=SYS 8=VOL 16=DIR 32=ARCH 64=DEVICE) */ 372 | memcpy(answ + 1, fprops.fcbname, 11); 373 | answ[12] = fprops.ftime & 0xff; 374 | answ[13] = (fprops.ftime >> 8) & 0xff; 375 | answ[14] = (fprops.ftime >> 16) & 0xff; 376 | answ[15] = (fprops.ftime >> 24) & 0xff; 377 | answ[16] = fprops.fsize & 0xff; /* fsize */ 378 | answ[17] = (fprops.fsize >> 8) & 0xff; /* fsize */ 379 | answ[18] = (fprops.fsize >> 16) & 0xff; /* fsize */ 380 | answ[19] = (fprops.fsize >> 24) & 0xff; /* fsize */ 381 | wansw[10] = htole16(dirss); /* dir id */ 382 | wansw[11] = htole16(fpos); /* file position in dir */ 383 | reslen = 24; 384 | } 385 | } else if (query == AL_FINDNEXT) { /* 0x1C */ 386 | unsigned short fpos; 387 | struct fileprops fprops; 388 | char *fcbmask; 389 | unsigned char fattr; 390 | unsigned short dirss; 391 | int flags; 392 | dirss = le16toh(wreqbuff[0]); 393 | fpos = le16toh(wreqbuff[1]); 394 | fattr = reqbuff[4]; 395 | fcbmask = (char *)reqbuff + 5; 396 | /* */ 397 | DBG("FindNext looks for nth file %u in dir #%u\nfcbmask: '%s'\nattribs: 0x%2X\n", fpos, dirss, pfcb(fcbmask), fattr); 398 | flags = 0; 399 | if (isroot(root, sstoitem(dirss)) != 0) flags |= FFILE_ISROOT; 400 | if (drivesfat[reqdrv] != 0) flags |= FFILE_ISFAT; 401 | if (findfile(&fprops, dirss, fcbmask, fattr, &fpos, flags)) { 402 | DBG("No more matching files found\n"); 403 | *ax = 0x12; /* "no more files" */ 404 | } else { /* found a file */ 405 | DBG("found file: FCB '%s' (attr %02Xh)\n", pfcb(fprops.fcbname), fprops.fattr); 406 | answ[0] = fprops.fattr; /* fattr (1=RO 2=HID 4=SYS 8=VOL 16=DIR 32=ARCH 64=DEVICE) */ 407 | memcpy(answ + 1, fprops.fcbname, 11); 408 | answ[12] = fprops.ftime & 0xff; 409 | answ[13] = (fprops.ftime >> 8) & 0xff; 410 | answ[14] = (fprops.ftime >> 16) & 0xff; 411 | answ[15] = (fprops.ftime >> 24) & 0xff; 412 | answ[16] = fprops.fsize & 0xff; /* fsize */ 413 | answ[17] = (fprops.fsize >> 8) & 0xff; /* fsize */ 414 | answ[18] = (fprops.fsize >> 16) & 0xff; /* fsize */ 415 | answ[19] = (fprops.fsize >> 24) & 0xff; /* fsize */ 416 | wansw[10] = htole16(dirss); /* dir id */ 417 | wansw[11] = htole16(fpos); /* file position in dir */ 418 | reslen = 24; 419 | } 420 | } else if ((query == AL_MKDIR) || (query == AL_RMDIR)) { /* MKDIR or RMDIR */ 421 | char directory[DIR_MAX]; 422 | char host_directory[DIR_MAX]; 423 | int offset; 424 | offset = sprintf(directory, "%s/", root); 425 | /* explode the full "\DIR\FILE????.???" search path into directory and mask */ 426 | memcpy(directory + offset, (char *)reqbuff, reqbufflen); 427 | directory[offset + reqbufflen] = 0; 428 | lostring(directory + offset, -1); 429 | charreplace(directory, '\\', '/'); 430 | 431 | /* try to get the host name for this string */ 432 | /* HACK: so we expect this to fail because, but shorttolong *does* append the last section of the requested path as is, so we just try with that */ 433 | if (shorttolong(host_directory, directory, root) == 0) { 434 | fprintf(stderr, "MKDIR Error (%s): A file exists that matches this name pattern.\n", directory); 435 | } 436 | 437 | if (query == AL_MKDIR) { 438 | DBG("MKDIR '%s'\n", host_directory); 439 | if (makedir(host_directory) != 0) { 440 | *ax = 29; 441 | fprintf(stderr, "MKDIR Error: %s\n", strerror(errno)); 442 | } 443 | } else { 444 | DBG("RMDIR '%s'\n", host_directory); 445 | if (remdir(host_directory) != 0) { 446 | *ax = 29; 447 | fprintf(stderr, "RMDIR Error: %s\n", strerror(errno)); 448 | } 449 | } 450 | } else if (query == AL_CHDIR) { /* check if dir exist, return ax=0 if so, ax=3 otherwise */ 451 | char directory[DIR_MAX]; 452 | char host_directory[DIR_MAX]; 453 | int offset; 454 | offset = sprintf(directory, "%s/", root); 455 | memcpy(directory + offset, (char *)reqbuff, reqbufflen); 456 | directory[offset + reqbufflen] = 0; 457 | lostring(directory + offset, -1); 458 | charreplace(directory, '\\', '/'); 459 | DBG("CHDIR '%s'\n", directory); 460 | 461 | /* try to get the host name for this string */ 462 | if (shorttolong(host_directory, directory, root) != 0) { 463 | fprintf(stderr, "CHDIR Error (%s): Cannot obtain host path for directory.\n", directory); 464 | *ax = 3; 465 | } else if (changedir(host_directory) != 0) { 466 | fprintf(stderr, "CHDIR Error (%s): %s\n", host_directory, strerror(errno)); 467 | *ax = 3; 468 | } 469 | } else if (query == AL_CLSFIL) { /* AL_CLSFIL (0x06) */ 470 | /* I do nothing, since I do not keep any open files around anyway. 471 | * just say 'ok' by sending back AX=0 */ 472 | DBG("CLOSE FILE\n"); 473 | *ax = 0; 474 | } else if ((query == AL_SETATTR) && (reqbufflen > 1)) { /* AL_SETATTR (0x0E) */ 475 | char fullpathname[DIR_MAX]; 476 | char host_fullpathname[DIR_MAX]; 477 | int offset; 478 | unsigned char fattr; 479 | fattr = reqbuff[0]; 480 | /* get full file path */ 481 | offset = sprintf(fullpathname, "%s/", root); 482 | memcpy(fullpathname + offset, (char *)reqbuff + 1, reqbufflen - 1); 483 | fullpathname[offset + reqbufflen - 1] = 0; 484 | lostring(fullpathname + offset, -1); 485 | charreplace(fullpathname, '\\', '/'); 486 | 487 | DBG("SETATTR [file: '%s', attr: 0x%02X]\n", fullpathname, fattr); 488 | 489 | /* try to get the host name for this string */ 490 | if (shorttolong(host_fullpathname, fullpathname, root) != 0) { 491 | fprintf(stderr, "SETATTR Error (%s): Cannot obtain host path for directory.\n", fullpathname); 492 | *ax = 2; 493 | } else if (drivesfat[reqdrv] != 0) { 494 | /* set attr, but only if drive is FAT */ 495 | if (setitemattr(host_fullpathname, fattr) != 0) *ax = 2; 496 | } 497 | } else if ((query == AL_GETATTR) && (reqbufflen > 0)) { /* AL_GETATTR (0x0F) */ 498 | char fullpathname[DIR_MAX]; 499 | char host_fullpathname[DIR_MAX]; 500 | int offset; 501 | struct fileprops fprops; 502 | /* get full file path */ 503 | offset = sprintf(fullpathname, "%s/", root); 504 | memcpy(fullpathname + offset, (char *)reqbuff, reqbufflen); 505 | fullpathname[offset + reqbufflen] = 0; 506 | lostring(fullpathname + offset, -1); 507 | charreplace(fullpathname, '\\', '/'); 508 | 509 | DBG("GETATTR on file: '%s' (fatflag=%d)\n", fullpathname, drivesfat[reqdrv]); 510 | 511 | /* try to get the host name for this string */ 512 | if (shorttolong(host_fullpathname, fullpathname, root) != 0) { 513 | fprintf(stderr, "GETATTR Error (%s): Cannot obtain host path for directory.\n", fullpathname); 514 | *ax = 2; 515 | } else if (getitemattr(host_fullpathname, &fprops, drivesfat[reqdrv]) == 0xFF) { 516 | DBG("no file found\n"); 517 | *ax = 2; 518 | } else { 519 | DBG("found it (%lu bytes, attr 0x%02X)\n", fprops.fsize, fprops.fattr); 520 | answ[reslen++] = fprops.ftime & 0xff; 521 | answ[reslen++] = (fprops.ftime >> 8) & 0xff; 522 | answ[reslen++] = (fprops.ftime >> 16) & 0xff; 523 | answ[reslen++] = (fprops.ftime >> 24) & 0xff; 524 | answ[reslen++] = fprops.fsize & 0xff; 525 | answ[reslen++] = (fprops.fsize >> 8) & 0xff; 526 | answ[reslen++] = (fprops.fsize >> 16) & 0xff; 527 | answ[reslen++] = (fprops.fsize >> 24) & 0xff; 528 | answ[reslen++] = fprops.fattr; 529 | } 530 | } else if ((query == AL_RENAME) && (reqbufflen > 2)) { /* AL_RENAME (0x11) */ 531 | /* query is LSSS...DDD... */ 532 | char fn1[1024], fn2[1024]; 533 | char host_fn1[1024]; 534 | int fn1len, fn2len, offset; 535 | offset = sprintf(fn1, "%s/", root); 536 | sprintf(fn2, "%s/", root); 537 | fn1len = reqbuff[0]; 538 | fn2len = reqbufflen - (1 + fn1len); 539 | if (reqbufflen > fn1len) { 540 | memcpy(fn1 + offset, reqbuff + 1, fn1len); 541 | fn1[fn1len + offset] = 0; 542 | lostring(fn1 + offset, -1); 543 | charreplace(fn1, '\\', '/'); 544 | memcpy(fn2 + offset, reqbuff + 1 + fn1len, fn2len); 545 | fn2[fn2len + offset] = 0; 546 | lostring(fn2 + offset, -1); 547 | charreplace(fn2, '\\', '/'); 548 | 549 | DBG("RENAME src='%s' dst='%s'\n", fn1, fn2); 550 | 551 | /* try to get the host name for this string */ 552 | if (shorttolong(host_fn1, fn1, root) != 0) { 553 | fprintf(stderr, "RENAME Error (%s): Cannot obtain host path for directory.\n", fn1); 554 | } else { 555 | if (getitemattr(fn2, NULL, 0) != 0xff) { 556 | /* if fn2 destination exists, abort with errcode=5 (as does MS-DOS 5) */ 557 | DBG("ERROR: '%s' exists already\n", fn2); 558 | *ax = 5; 559 | } else { 560 | DBG("'%s' doesn't exist -> proceed with renaming\n", fn2); 561 | if (renfile(host_fn1, fn2) != 0) *ax = 5; 562 | } 563 | } 564 | } else { 565 | *ax = 2; 566 | } 567 | } else if (query == AL_DELETE) { 568 | char fullpathname[DIR_MAX]; 569 | char host_fullpathname[DIR_MAX]; 570 | int offset; 571 | /* compute full path/file first */ 572 | offset = sprintf(fullpathname, "%s/", root); 573 | memcpy(fullpathname + offset, reqbuff, reqbufflen); 574 | fullpathname[reqbufflen + offset] = 0; 575 | lostring(fullpathname + offset, -1); 576 | charreplace(fullpathname, '\\', '/'); 577 | DBG("DELETE '%s'\n", fullpathname); 578 | 579 | 580 | /* try to get the host name for this string */ 581 | if (shorttolong(host_fullpathname, fullpathname, root) != 0) { 582 | fprintf(stderr, "DELETE Error (%s): Cannot obtain host path for directory.\n", fullpathname); 583 | *ax = 2; 584 | } else if (getitemattr(host_fullpathname, NULL, drivesfat[reqdrv]) & 1) { /* is it read-only? */ 585 | *ax = 5; /* "access denied" */ 586 | } else if (delfiles(host_fullpathname) < 0) { 587 | *ax = 2; 588 | } 589 | } else if ((query == AL_OPEN) || (query == AL_CREATE) || (query == AL_SPOPNFIL)) { /* OPEN is only about "does this file exist", and CREATE "please create or truncate this file", while SPOPNFIL is a combination of both with extra flags */ 590 | struct fileprops fprops; 591 | char directory[DIR_MAX]; 592 | char host_directory[DIR_MAX]; 593 | char fname[DIR_MAX]; 594 | char fnamefcb[12]; 595 | char fullpathname[DIR_MAX]; 596 | char host_fullpathname[DIR_MAX*2+1]; 597 | int offset; 598 | int fileres; 599 | unsigned short stackattr, actioncode, spopen_openmode, spopres = 0; 600 | unsigned char resopenmode; 601 | /* fetch args */ 602 | stackattr = le16toh(wreqbuff[0]); 603 | actioncode = le16toh(wreqbuff[1]); 604 | spopen_openmode = le16toh(wreqbuff[2]); 605 | /* compute full path/file */ 606 | offset = sprintf(fullpathname, "%s/", root); 607 | memcpy(fullpathname + offset, reqbuff + 6, reqbufflen - 6); 608 | fullpathname[reqbufflen + offset - 6] = 0; 609 | lostring(fullpathname + offset, -1); 610 | charreplace(fullpathname, '\\', '/'); 611 | /* compute directory and 'search mask' */ 612 | offset = sprintf(directory, "%s/", root); 613 | explodepath(directory + offset, fname, (char *)reqbuff+6, reqbufflen-6); 614 | 615 | lostring(directory + offset, -1); 616 | charreplace(directory, '\\', '/'); 617 | 618 | /* does the directory exist? */ 619 | if ((shorttolong(host_directory, directory, root) != 0) || (changedir(host_directory) != 0)) { 620 | DBG("open/create/spop failed because directory does not exist\n"); 621 | *ax = 3; /* "path not found" */ 622 | } else { 623 | /* Directory exists, attempt to get host version of the full path name, hoping it exists. */ 624 | if (shorttolong(host_fullpathname, fullpathname, root) == 0) { 625 | /* if it does, copy its filename to host_fname.*/ 626 | DBG("Exists, pre: fname '%s' host_fullpathname '%s'\n", fname, host_fullpathname); 627 | copy_after_last_slash(fname, host_fullpathname); 628 | DBG("Exists, post: fname '%s' host_fullpathname '%s'\n", fname, host_fullpathname); 629 | } else { 630 | /* if it doesn't exist, make file name lowercase and then craft the host full path name */ 631 | sprintf(host_fullpathname, "%s/%s", host_directory, fname); 632 | } 633 | 634 | /* compute a FCB-style version of the filename */ 635 | filename2fcb(fnamefcb, fname); 636 | /* */ 637 | DBG("stack word: %04X\n", stackattr); 638 | DBG("looking for file '%s' (FCB '%s') in '%s'\n", fname, pfcb(fnamefcb), directory); 639 | /* open or create file, depending on exact subfunction */ 640 | if (query == AL_CREATE) { 641 | DBG("CREATEFIL / stackattr (attribs)=%04Xh / fn='%s'\n", stackattr, fullpathname); 642 | fileres = createfile(&fprops, host_directory, fname, stackattr & 0xff, drivesfat[reqdrv]); 643 | resopenmode = 2; /* read/write */ 644 | } else if (query == AL_SPOPNFIL) { 645 | /* actioncode contains instructions about how to behave... 646 | * high nibble = action if file does NOT exist: 647 | * 0000 fail 648 | * 0001 create 649 | * low nibble = action if file DOES exist 650 | * 0000 fail 651 | * 0001 open 652 | * 0010 replace/open */ 653 | int attr; 654 | DBG("SPOPNFIL / stackattr=%04Xh / action=%04Xh / openmode=%04Xh / fn='%s'\n", stackattr, actioncode, spopen_openmode, fullpathname); 655 | /* see if file exists (and is a file) */ 656 | attr = getitemattr(host_fullpathname, &fprops, drivesfat[reqdrv]); 657 | resopenmode = spopen_openmode & 0x7f; /* that's what PHANTOM.C does */ 658 | if (attr == 0xff) { /* file not found - look at high nibble of action code */ 659 | DBG("file doesn't exist -> "); 660 | if ((actioncode & 0xf0) == 16) { /* create */ 661 | DBG("create file host_fullpathname='%s' fname='%s'\n", host_fullpathname, fname); 662 | fileres = createfile(&fprops, host_directory, fname, stackattr & 0xff, drivesfat[reqdrv]); 663 | if (fileres == 0) spopres = 2; /* spopres == 2 means 'file created' */ 664 | } else { /* fail */ 665 | DBG("fail\n"); 666 | fileres = 1; 667 | } 668 | } else if ((attr & (FAT_VOL | FAT_DIR)) != 0) { /* item is a DIR or a VOL */ 669 | DBG("fail: item '%s' is either a DIR or a VOL\n", fullpathname); 670 | fileres = 1; 671 | } else { /* file found (not a VOL, not a dir) - look at low nibble of action code */ 672 | DBG("file exists already (attr %02Xh) -> ", attr); 673 | if ((actioncode & 0x0f) == 1) { /* open */ 674 | DBG("open file\n"); 675 | fileres = 0; 676 | spopres = 1; /* spopres == 1 means 'file opened' */ 677 | } else if ((actioncode & 0x0f) == 2) { /* truncate */ 678 | DBG("truncate file host_fullpathname='%s' fname='%s'\n", host_fullpathname, fname); 679 | fileres = createfile(&fprops, host_directory, fname, stackattr & 0xff, drivesfat[reqdrv]); 680 | if (fileres == 0) spopres = 3; /* spopres == 3 means 'file truncated' */ 681 | } else { /* fail */ 682 | DBG("fail\n"); 683 | fileres = 1; 684 | } 685 | } 686 | } else { /* simple 'OPEN' */ 687 | int attr; 688 | DBG("OPENFIL / stackattr (open modes)=%04Xh / fn='%s'\n", stackattr, fullpathname); 689 | resopenmode = stackattr & 0xff; 690 | attr = getitemattr(host_fullpathname, &fprops, drivesfat[reqdrv]); 691 | /* check that item exists, and is neither a volume nor a directory */ 692 | if ((attr != 0xff) && ((attr & (FAT_VOL | FAT_DIR)) == 0)) { 693 | fileres = 0; 694 | } else { 695 | fileres = 1; 696 | } 697 | } 698 | if (fileres != 0) { 699 | DBG("open/create/spop failed with fileres = %d\n", fileres); 700 | *ax = 2; 701 | } else { /* success (found a file, created it or truncated it) */ 702 | unsigned short fileid; 703 | fileid = getitemss(host_fullpathname); 704 | DBG("found file: '%s' FCB '%s' (id %04X)\n", host_fullpathname, pfcb(fprops.fcbname), fileid); 705 | DBG(" fsize: %lu\n", fprops.fsize); 706 | DBG(" fattr: %02Xh\n", fprops.fattr); 707 | DBG(" ftime: %04lX\n", fprops.ftime); 708 | if (fileid == 0xffffu) { 709 | fprintf(stderr, "ERROR: failed to get a proper fileid!\n"); 710 | return(-1); 711 | } 712 | answ[reslen++] = fprops.fattr; /* fattr (1=RO 2=HID 4=SYS 8=VOL 16=DIR 32=ARCH 64=DEVICE) */ 713 | memcpy(answ + reslen, fprops.fcbname, 11); 714 | reslen += 11; 715 | answ[reslen++] = fprops.ftime & 0xff; /* time: YYYYYYYM MMMDDDDD hhhhhmmm mmmsssss */ 716 | answ[reslen++] = (fprops.ftime >> 8) & 0xff; 717 | answ[reslen++] = (fprops.ftime >> 16) & 0xff; 718 | answ[reslen++] = (fprops.ftime >> 24) & 0xff; 719 | answ[reslen++] = fprops.fsize & 0xff; /* fsize */ 720 | answ[reslen++] = (fprops.fsize >> 8) & 0xff; /* fsize */ 721 | answ[reslen++] = (fprops.fsize >> 16) & 0xff; /* fsize */ 722 | answ[reslen++] = (fprops.fsize >> 24) & 0xff; /* fsize */ 723 | answ[reslen++] = fileid & 0xff; 724 | answ[reslen++] = fileid >> 8; 725 | /* CX result (only relevant for SPOPNFIL) */ 726 | answ[reslen++] = spopres & 0xff; 727 | answ[reslen++] = spopres >> 8; 728 | answ[reslen++] = resopenmode; 729 | } 730 | } 731 | } else if ((query == AL_SKFMEND) && (reqbufflen == 6)) { /* SKFMEND (0x21) */ 732 | /* translate a 'seek from end' offset into an 'seek from start' offset */ 733 | int32_t offs = le32toh(((uint32_t *)reqbuff)[0]); 734 | long fsize; 735 | unsigned short fss = le16toh(((unsigned short *)reqbuff)[2]); 736 | DBG("SKFMEND on file #%u at offset %d\n", fss, offs); 737 | /* if arg is positive, zero it out */ 738 | if (offs > 0) offs = 0; 739 | /* */ 740 | fsize = getfopsize(fss); 741 | if (fsize < 0) { 742 | DBG("ERROR: file not found or other error\n"); 743 | *ax = 2; 744 | } else { /* compute new offset and send it back */ 745 | DBG("file #%u is %lu bytes long\n", fss, fsize); 746 | offs += fsize; 747 | if (offs < 0) offs = 0; 748 | DBG("new offset: %d\n", offs); 749 | ((uint32_t *)answ)[0] = htole32(offs); 750 | reslen = 4; 751 | } 752 | } else { /* unknown query - ignore */ 753 | return(-1); 754 | } 755 | return(reslen + 60); 756 | } 757 | 758 | 759 | static int raw_sock(const char *const interface, void *const hwaddr) { 760 | struct ifreq iface; 761 | int socketfd, fl; 762 | #ifdef __FreeBSD__ 763 | #define PATH_BPF "/dev/bpf" 764 | int i = 0; 765 | char filename[sizeof PATH_BPF "-9223372036854775808"]; /* 29 */ 766 | int immediate = 1; 767 | static struct bpf_insn bf_insn[] = { 768 | /* Make sure this is an ETHERTYPE_DFS packet... */ 769 | BPF_STMT(BPF_LD + BPF_H + BPF_ABS, 12), 770 | BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, ETHERTYPE_DFS, 0, 1), 771 | /* If we passed all the tests, ask for the whole packet. */ 772 | BPF_STMT(BPF_RET+BPF_K, (u_int)-1), 773 | /* Otherwise, drop it. */ 774 | BPF_STMT(BPF_RET+BPF_K, 0), 775 | }; 776 | struct bpf_program bf_program = { 777 | sizeof (bf_insn) / (sizeof bf_insn[0]), 778 | bf_insn 779 | }; 780 | int mib[] = {CTL_NET, AF_ROUTE, 0, 0, NET_RT_IFLIST, 0}; 781 | size_t len; 782 | char *buf; 783 | struct if_msghdr *ifm; 784 | struct sockaddr_dl *sdl; 785 | #else 786 | struct sockaddr_ll addr; 787 | int result; 788 | int ifindex; 789 | #endif 790 | 791 | if ((interface == NULL) || (*interface == 0)) { 792 | errno = EINVAL; 793 | return(-1); 794 | } 795 | 796 | #ifdef __FreeBSD__ 797 | do { 798 | snprintf(filename, sizeof(filename), PATH_BPF "%i", i++); 799 | socketfd = open(filename, O_RDWR); 800 | } while ((socketfd < 0) && (errno == EBUSY)); 801 | #else 802 | socketfd = socket(AF_PACKET, SOCK_RAW, htons(ETHERTYPE_DFS)); 803 | #endif 804 | 805 | if (socketfd == -1) return(-1); 806 | 807 | do { 808 | memset(&iface, 0, sizeof iface); 809 | strncpy(iface.ifr_name, interface, sizeof iface.ifr_name - 1); 810 | #ifdef __FreeBSD__ 811 | if (ioctl(socketfd, BIOCSETIF, &iface) < 0) { 812 | DBG("ERROR: could not bind %s to %s: %s\n", filename, iface.ifr_name, strerror(errno)); 813 | break; 814 | } 815 | if (ioctl(socketfd, BIOCIMMEDIATE, &immediate) < 0) { 816 | DBG("ERROR1: could not enable \"immediate mode\": %s\n", strerror(errno)); 817 | break; 818 | } 819 | if (ioctl(socketfd, BIOCSETF, &bf_program) < 0) { 820 | DBG("ERROR: could not set the bpf program: %s\n", strerror(errno)); 821 | break; 822 | } 823 | if ((mib[5] = if_nametoindex(interface)) == 0) { 824 | DBG("ERROR: if_nametoindex(): %s\n", strerror(errno)); 825 | break; 826 | } 827 | if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) { 828 | DBG("ERROR: sysctl(): %s\n", strerror(errno)); 829 | break; 830 | } 831 | if ((buf = malloc(len)) == NULL) { 832 | DBG("ERROR: malloc(): %s\n", strerror(errno)); 833 | break; 834 | } 835 | if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) { 836 | DBG("ERROR: sysctl(): %s\n", strerror(errno)); 837 | break; 838 | } 839 | ifm = (struct if_msghdr *) buf; 840 | sdl = (struct sockaddr_dl *) (ifm + 1); 841 | memcpy(hwaddr, LLADDR(sdl), ETHER_ADDR_LEN); 842 | #else 843 | result = ioctl(socketfd, SIOCGIFINDEX, &iface); 844 | if (result == -1) break; 845 | ifindex = iface.ifr_ifindex; 846 | 847 | memset(&iface, 0, sizeof(iface)); 848 | strncpy(iface.ifr_name, interface, sizeof iface.ifr_name - 1); 849 | result = ioctl(socketfd, SIOCGIFFLAGS, &iface); 850 | if (result == -1) break; 851 | iface.ifr_flags |= IFF_PROMISC; 852 | result = ioctl(socketfd, SIOCSIFFLAGS, &iface); 853 | if (result == -1) break; 854 | 855 | memset(&iface, 0, sizeof iface); 856 | strncpy(iface.ifr_name, interface, sizeof iface.ifr_name - 1); 857 | result = ioctl(socketfd, SIOCGIFHWADDR, &iface); 858 | if (result == -1) break; 859 | 860 | memset(&addr, 0, sizeof addr); 861 | addr.sll_family = AF_PACKET; 862 | addr.sll_protocol = htons(ETHERTYPE_DFS); 863 | addr.sll_ifindex = ifindex; 864 | addr.sll_hatype = 0; 865 | addr.sll_pkttype = PACKET_HOST | PACKET_BROADCAST; 866 | addr.sll_halen = ETH_ALEN; /* Assume ethernet! */ 867 | memcpy(&addr.sll_addr, &iface.ifr_hwaddr.sa_data, addr.sll_halen); 868 | if (hwaddr != NULL) memcpy(hwaddr, &iface.ifr_hwaddr.sa_data, ETH_ALEN); 869 | 870 | if (bind(socketfd, (struct sockaddr *)&addr, sizeof addr)) break; 871 | 872 | errno = 0; 873 | #endif 874 | /* unblock socket, better safe than sorry */ 875 | if ((fl = fcntl(socketfd, F_GETFL)) < 0) { 876 | DBG("ERROR: fcntl(): %s\n", strerror(errno)); 877 | break; 878 | } 879 | fl |= O_NONBLOCK; 880 | if ((fl = fcntl(socketfd, F_SETFL, fl)) < 0) { 881 | DBG("ERROR: fcntl(): %s\n", strerror(errno)); 882 | break; 883 | } 884 | 885 | return(socketfd); 886 | } while (0); 887 | 888 | { 889 | const int saved_errno = errno; 890 | close(socketfd); 891 | errno = saved_errno; 892 | return(-1); 893 | } 894 | } 895 | 896 | 897 | /* used for debug output of frames on screen */ 898 | #if DEBUG > 0 899 | static void dumpframe(unsigned char *frame, int len) { 900 | int i, b; 901 | int lines; 902 | const int LINEWIDTH=16; 903 | lines = (len + LINEWIDTH - 1) / LINEWIDTH; /* compute the number of lines */ 904 | /* display line by line */ 905 | for (i = 0; i < lines; i++) { 906 | /* read the line and output hex data */ 907 | for (b = 0; b < LINEWIDTH; b++) { 908 | int offset = (i * LINEWIDTH) + b; 909 | if (b == LINEWIDTH / 2) printf(" "); 910 | if (offset < len) { 911 | printf(" %02X", frame[offset]); 912 | } else { 913 | printf(" "); 914 | } 915 | } 916 | printf(" | "); /* delimiter between hex and ascii */ 917 | /* now output ascii data */ 918 | for (b = 0; b < LINEWIDTH; b++) { 919 | int offset = (i * LINEWIDTH) + b; 920 | if (b == LINEWIDTH / 2) printf(" "); 921 | if (offset >= len) { 922 | printf(" "); 923 | continue; 924 | } 925 | if ((frame[offset] >= ' ') && (frame[offset] <= '~')) { 926 | printf("%c", frame[offset]); 927 | } else { 928 | printf("."); 929 | } 930 | } 931 | /* newline and loop */ 932 | printf("\n"); 933 | } 934 | } 935 | #endif 936 | 937 | /* compare two chunks of data, returns 0 if data is the same, non-zero otherwise */ 938 | static int cmpdata(unsigned char *d1, unsigned char *d2, int len) { 939 | while (len-- > 0) { 940 | if (*d1 != *d2) return(1); 941 | d1++; 942 | d2++; 943 | } 944 | return(0); 945 | } 946 | 947 | /* compute the BSD checksum of l bytes starting at ptr */ 948 | static unsigned short bsdsum(unsigned char *ptr, unsigned short l) { 949 | unsigned short res = 0; 950 | for (; l > 0; l--) { 951 | res = (res << 15) | (res >> 1); 952 | res += *ptr; 953 | ptr++; 954 | } 955 | return(res); 956 | } 957 | 958 | static void help(void) { 959 | printf("EtherDFS Server (ethersrv) version " PVER "\n" 960 | "(C) 2017, 2018 Mateusz Viste, 2020 Michael Ortmann, 2023-2025 E. Voirin (oerg866)\n" 961 | "http://etherdfs.sourceforge.net\n" 962 | "\n" 963 | "usage: ethersrv [options] interface rootpath1 [rootpath2] ... [rootpathN]\n" 964 | "\n" 965 | "Options:\n" 966 | " -f Keep in foreground (do not daemonize)\n" 967 | " -h Display this information\n" 968 | ); 969 | } 970 | 971 | /* daemonize the process, return 0 on success, non-zero otherwise */ 972 | static int daemonize(void) { 973 | pid_t mypid; 974 | 975 | /* I don't want to get notified about SIGHUP */ 976 | signal(SIGHUP, SIG_IGN); 977 | 978 | /* fork off */ 979 | mypid = fork(); 980 | if (mypid == 0) { /* I'm the child, do nothing */ 981 | /* nothing to do - just continue */ 982 | } else if (mypid > 0) { /* I'm the parent - quit now */ 983 | exit(0); 984 | } else { /* error condition */ 985 | return(-2); 986 | } 987 | return(0); 988 | } 989 | 990 | /* generates a formatted MAC address printout and returns a static buffer */ 991 | static char *printmac(unsigned char *b) { 992 | static char macbuf[18]; 993 | sprintf(macbuf, "%02X:%02X:%02X:%02X:%02X:%02X", b[0], b[1], b[2], b[3], b[4], b[5]); 994 | return(macbuf); 995 | } 996 | 997 | 998 | int main(int argc, char **argv) { 999 | int sock, len, i, r; 1000 | unsigned char *buff; 1001 | unsigned char cksumflag; 1002 | unsigned short edf5framelen; 1003 | unsigned char mymac[6]; 1004 | char *intname, *root[26]; 1005 | struct struct_answcache *cacheptr; 1006 | int opt; 1007 | int daemon = 1; /* daemonize self by default */ 1008 | #ifdef __FreeBSD__ 1009 | int bpf_len; 1010 | unsigned char *bpf_buf; 1011 | struct bpf_hdr *bf_hdr; 1012 | #endif 1013 | #define lockfile "/var/run/ethersrv.lock" 1014 | 1015 | while ((opt = getopt(argc, argv, "fh")) != -1) { 1016 | switch (opt) { 1017 | case 'f': /* -f: no daemon */ 1018 | daemon = 0; 1019 | break; 1020 | case 'h': /* -h: help */ 1021 | help(); 1022 | return(0); 1023 | case '?': /* error */ 1024 | help(); 1025 | return(1); 1026 | } 1027 | } 1028 | /* I expect at least two positional arguments, and not more than 26 */ 1029 | if (argc - optind < 2 || argc - optind > 26) { 1030 | help(); 1031 | return(1); 1032 | } 1033 | intname = argv[optind++]; 1034 | /* load all "virtual drive" paths */ 1035 | for (i = 0; i < 26; i++) root[i] = NULL; 1036 | for (i = 0; i < (argc - optind); i++) { 1037 | char tmppath[PATH_MAX]; 1038 | if (realpath(argv[i + optind], tmppath) == NULL) { 1039 | fprintf(stderr, "ERROR: failed to resolve path '%s'\n", argv[i + optind]); 1040 | return(1); 1041 | } 1042 | root[i + 2] = strdup(tmppath); 1043 | if (isfat(root[i + 2]) == 0) { 1044 | drivesfat[i + 2] = 1; 1045 | } else { 1046 | drivesfat[i + 2] = 0; 1047 | fprintf(stderr, "WARNING: the path '%s' doesn't seem to be stored on a FAT filesystem! DOS attributes won't be supported.\n\n", root[i + 2]); 1048 | } 1049 | } 1050 | 1051 | sock = raw_sock(intname, mymac); 1052 | if (sock == -1) { 1053 | fprintf(stderr, "Error: failed to open socket (%s)\n" 1054 | "\n" 1055 | "Usually ethersrv requires to be launched as root to\n" 1056 | "be able to handle raw (ethernet) sockets. Are you root?\n", strerror(errno)); 1057 | return(1); 1058 | } 1059 | 1060 | /* setup signals catcher */ 1061 | signal(SIGTERM, sigcatcher); 1062 | signal(SIGQUIT, sigcatcher); 1063 | signal(SIGINT, sigcatcher); 1064 | 1065 | /* acquire the lock file (fail if already exists - likely ethersrv runs already) */ 1066 | if (lockme(lockfile) != 0) { 1067 | fprintf(stderr, "Error: failed to acquire a lock. Is ethersrv running already? If not, and you're really sure of that, then delete the lock file at '%s'.\n", lockfile); 1068 | return(1); 1069 | } 1070 | printf("Listening on '%s' [%s]\n", intname, printmac(mymac)); 1071 | for (i = 2; i < 26; i++) { 1072 | if (root[i] == NULL) break; 1073 | printf("Drive %c: mapped to %s\n", 'A' + i, root[i]); 1074 | } 1075 | 1076 | if (daemon != 0) { 1077 | if (daemonize() != 0) { 1078 | fprintf(stderr, "Error: failed to daemonize!\n"); 1079 | return(1); 1080 | } 1081 | } 1082 | #ifdef __FreeBSD__ 1083 | if (ioctl(sock, BIOCGBLEN, &bpf_len) < 0) { 1084 | DBG("ERROR1: could not get the required buffer length for reads on bpf files: %s\n", strerror(errno)); 1085 | return(1); 1086 | } 1087 | if ((bpf_buf = malloc(bpf_len)) == NULL) { 1088 | DBG("ERROR: malloc(): %s\n", strerror(errno)); 1089 | return(1); 1090 | } 1091 | #else 1092 | if ((buff = malloc(BUFF_LEN)) == NULL) { 1093 | DBG("ERROR: malloc(): %s\n", strerror(errno)); 1094 | return(1); 1095 | } 1096 | #endif 1097 | 1098 | /* main loop */ 1099 | while (1) { 1100 | #if DEBUG > 0 1101 | struct timeval stimeout = {10, 0}; /* set timeout to 10s */ 1102 | #endif 1103 | /* prepare the set of descriptors to be monitored later through select() */ 1104 | fd_set fdset; 1105 | FD_ZERO(&fdset); 1106 | FD_SET(sock, &fdset); 1107 | /* wait for something to happen on my socket */ 1108 | #if DEBUG > 0 1109 | r = select(sock + 1, &fdset, NULL, NULL, &stimeout); 1110 | #else 1111 | r = select(sock + 1, &fdset, NULL, NULL, NULL); 1112 | #endif 1113 | if (!r) 1114 | continue; /* timeout / heartbeat */ 1115 | if (r < 0) { 1116 | if (terminationflag) 1117 | break; 1118 | DBG("ERROR: select(): %s\n", strerror(errno)); 1119 | continue; 1120 | } 1121 | #ifdef __FreeBSD__ 1122 | if ((len = read(sock, bpf_buf, bpf_len)) < (int) sizeof (struct bpf_hdr)) { 1123 | DBG("ERROR: read(): %s\n", strerror(errno)); 1124 | continue; 1125 | } 1126 | bf_hdr = (struct bpf_hdr *) bpf_buf; 1127 | buff = bpf_buf + bf_hdr->bh_hdrlen; 1128 | #else 1129 | len = recv(sock, buff, BUFF_LEN, MSG_DONTWAIT); 1130 | #endif 1131 | if (len < 60) continue; /* restart if less than 60 bytes or negative */ 1132 | /* validate this is for me (or broadcast) */ 1133 | if ((cmpdata(mymac, buff, 6) != 0) && (cmpdata((unsigned char *)"\xff\xff\xff\xff\xff\xff", buff, 6) != 0)) continue; /* skip anything that is not for me */ 1134 | /* is this ETHERTYPE_DFS? */ 1135 | if (((unsigned short *)buff)[6] != htons(ETHERTYPE_DFS)) { 1136 | fprintf(stderr, "Error: Received non-ETHERTYPE_DFS frame\n"); 1137 | continue; 1138 | } 1139 | /* validate protocol version matches what I expect */ 1140 | if ((buff[56] & 127) != PROTOVER) { 1141 | fprintf(stderr, "Error: unsupported protocol version from %s\n", buff + 6); 1142 | continue; 1143 | } 1144 | cksumflag = buff[56] >> 7; 1145 | /* trim of padding, if any, or reject frame if it came truncated */ 1146 | edf5framelen = le16toh(((unsigned short *)buff)[26]); 1147 | if (edf5framelen == 0) { 1148 | /* nothing to do, edf5framelen is not provided */ 1149 | } else if (edf5framelen > len) { /* frame seems truncated */ 1150 | fprintf(stderr, "Error: received a truncated frame from %s\n", printmac(buff + 6)); 1151 | continue; 1152 | } else if (edf5framelen < 60) { /* obvious error */ 1153 | fprintf(stderr, "Error: received a malformed frame from %s\n", printmac(buff + 6)); 1154 | continue; 1155 | } else { /* edf5framelen seems sane, use it instead of the Ethernet length */ 1156 | #if DEBUG > 0 1157 | if (len != edf5framelen) { 1158 | DBG("Note: Received frame with padding from %s (edf5len = %u, ethernet len = %u)\n", printmac(buff + 6), edf5framelen, len); 1159 | } 1160 | #endif 1161 | len = edf5framelen; 1162 | } 1163 | /* */ 1164 | #if DEBUG > 0 1165 | DBG("Received frame of %d bytes (cksum = %s)\n", len, (cksumflag != 0)?"ENABLED":"DISABLED"); 1166 | dumpframe(buff, len); 1167 | #endif 1168 | #if SIMLOSS > 0 1169 | /* simulated frame LOSS (input) */ 1170 | if ((rand() & 31) == 0) { 1171 | fprintf(stderr, "INPUT LOSS!\n"); 1172 | continue; 1173 | } 1174 | #endif 1175 | /* validate the CKSUM, if any */ 1176 | if (cksumflag != 0) { 1177 | unsigned short cksum_remote, cksum_mine; 1178 | cksum_mine = bsdsum(buff + 56, len - 56); 1179 | cksum_remote = le16toh(((unsigned short *)buff)[27]); 1180 | if (cksum_mine != cksum_remote) { 1181 | fprintf(stderr, "CHECKSUM MISMATCH! Computed: 0x%02Xh Received: 0x%02Xh\n", cksum_mine, cksum_remote); 1182 | continue; 1183 | } 1184 | } 1185 | /* */ 1186 | cacheptr = findcacheentry(buff + 6); 1187 | /* process frame */ 1188 | len = process(cacheptr, buff, len, mymac, root); 1189 | /* update cache entry */ 1190 | if (len >= 0) { 1191 | cacheptr->len = len; 1192 | cacheptr->timestamp = time(NULL); 1193 | } else { 1194 | cacheptr->len = 0; 1195 | } 1196 | /* */ 1197 | #if SIMLOSS > 0 1198 | /* simulated frame LOSS (output) */ 1199 | if ((rand() & 31) == 0) { 1200 | fprintf(stderr, "OUTPUT LOSS!\n"); 1201 | continue; 1202 | } 1203 | #endif 1204 | DBG("---------------------------------\n"); 1205 | if (len > 0) { 1206 | /* fill in frame's length */ 1207 | cacheptr->frame[52] = len & 0xff; 1208 | cacheptr->frame[53] = (len >> 8) & 0xff; 1209 | /* fill in checksum into the answer */ 1210 | if (cksumflag != 0) { 1211 | unsigned short newcksum = bsdsum(cacheptr->frame + 56, len - 56); 1212 | cacheptr->frame[54] = newcksum & 0xff; 1213 | cacheptr->frame[55] = (newcksum >> 8) & 0xff; 1214 | cacheptr->frame[56] |= 128; /* make sure to set the CKS bit */ 1215 | } else { 1216 | cacheptr->frame[54] = 0; 1217 | cacheptr->frame[55] = 0; 1218 | cacheptr->frame[56] &= 127; /* make sure to reset the CKS bit */ 1219 | } 1220 | #if DEBUG > 0 1221 | DBG("Sending back an answer of %d bytes\n", len); 1222 | dumpframe(cacheptr->frame, len); 1223 | #endif 1224 | #ifdef __FreeBSD__ 1225 | i = write(sock, cacheptr->frame, len); 1226 | if (i < 0) { 1227 | fprintf(stderr, "ERROR: write() returned %d (%s)\n", i, strerror(errno)); 1228 | } else if (i != len) { 1229 | fprintf(stderr, "ERROR: write() sent less than expected (%d != %d)\n", i, len); 1230 | } 1231 | #else 1232 | i = send(sock, cacheptr->frame, len, 0); 1233 | if (i < 0) { 1234 | fprintf(stderr, "ERROR: send() returned %d (%s)\n", i, strerror(errno)); 1235 | } else if (i != len) { 1236 | fprintf(stderr, "ERROR: send() sent less than expected (%d != %d)\n", i, len); 1237 | } 1238 | #endif 1239 | } else { 1240 | fprintf(stderr, "Query ignored (result: %d)\n", len); 1241 | } 1242 | DBG("---------------------------------\n"); 1243 | } 1244 | /* remove the lock file and quit */ 1245 | unlockme(lockfile); 1246 | return(0); 1247 | } 1248 | --------------------------------------------------------------------------------