aboutsummaryrefslogtreecommitdiff
path: root/sftsr.c
blob: 37be41a5f362a712643d002dff050196f9129bd6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
/*
 * VBSF - VirtualBox shared folders for DOS, resident part
 * Copyright (C) 2022 Javier S. Pedro
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.

 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

#include <stdlib.h>
#include <string.h>
#include <i86.h>

#include "int21dos.h"
#include "unixtime.h"
#include "vboxshfl.h"
#include "sftsr.h"

TSRDATA data;

/** Private buffer for VirtualBox filenames. */
static SHFLSTRING_WITH_BUF(shflstr, SHFL_MAX_LEN);

static SHFLDIRINFO_WITH_NAME_BUF(shfldirinfo, SHFL_MAX_LEN);

static union {
	SHFLVOLINFO volinfo;
	SHFLCREATEPARMS create;
} parms;

static uint8_t map_shfl_attr_to_dosattr(const SHFLFSOBJATTR *a)
{
	// DOS attributes are in the higher word of fMode (see RTFS_DOS_*)
	uint8_t attr = (a->fMode >> 16) & 0x3F;
	if (a->fMode & 0x4000U) attr |= _A_SUBDIR;
	return attr;
}

static void map_shfl_info_to_dossft(DOSSFT __far *sft, SHFLFSOBJINFO *i)
{
	sft->attr = map_shfl_attr_to_dosattr(&i->Attr);
	sft->f_size = i->cbObject;
	timestampns_to_dos_time(&sft->f_time, &sft->f_date, i->ModificationTime, data.tz_offset);
}

static void map_shfl_info_to_dosdir(DOSDIR __far *dir, SHFLFSOBJINFO *i)
{
	dir->attr = map_shfl_attr_to_dosattr(&i->Attr);
	dir->f_size = i->cbObject;
	timestampns_to_dos_time(&dir->f_time, &dir->f_date, i->ModificationTime, data.tz_offset);
	dir->start_cluster = 0;
}

static void map_shfl_info_to_getattr(union INTPACK __far *r, SHFLFSOBJINFO *i)
{
	r->x.ax = map_shfl_attr_to_dosattr(&i->Attr);
	r->x.bx = ((uint32_t)i->cbObject) >> 16;
	r->x.di = ((uint16_t)i->cbObject);
	timestampns_to_dos_time(&r->x.cx, &r->x.dx, i->ModificationTime, data.tz_offset);
}

static int get_op_drive_num(union INTPACK __far *r)
{
	DOSSFT __far *sft;

	switch (r->h.al) {
	case DOS_FN_CLOSE:
	case DOS_FN_COMMIT:
	case DOS_FN_READ:
	case DOS_FN_WRITE:
	case DOS_FN_LOCK:
	case DOS_FN_UNLOCK:
	case DOS_FN_SEEK_END:
		// Some operations use an SFT and we directly get the drive from it
		sft = MK_FP(r->x.es, r->x.di);
		return sft->dev_info & 0x1F;

	case DOS_FN_RMDIR:
	case DOS_FN_MKDIR:
	case DOS_FN_CHDIR:
	case DOS_FN_SET_FILE_ATTR:
	case DOS_FN_GET_FILE_ATTR:
	case DOS_FN_RENAME:
	case DOS_FN_DELETE:
	case DOS_FN_OPEN:
	case DOS_FN_CREATE:
	case DOS_FN_FIND_FIRST:
	case DOS_FN_OPEN_EX:
		// We can use the drive of the first filename argument for these operations
		return drive_letter_to_index(data.dossda->fn1[0]);

	case DOS_FN_GET_DISK_FREE:
		// Otherwise just get the current drive from dos
		return drive_letter_to_index(data.dossda->drive_cds->curr_path[0]);

	case DOS_FN_FIND_NEXT:
		return data.dossda->sdb.drive_letter & 0x1F;

	default:
		// We don't support this operation
		return -1;
	}
}

static bool is_call_for_mounted_drive(union INTPACK __far *r)
{
	int drive = get_op_drive_num(r);

	if (drive < 0 || drive >= MAX_NUM_DRIVE) {
		return false;
	}

	return data.drives[drive].root != SHFL_ROOT_NIL;
}

static void clear_dos_err(union INTPACK __far *r)
{
	dlog_puts("->ok");
	r->x.flags &= ~INTR_CF;
}

static void set_dos_err(union INTPACK __far *r, int err)
{
	dlog_print("->dos error ");
	dlog_printd(err);
	dlog_endline();
	r->x.flags |= INTR_CF;
	r->x.ax = err;
}

static int vbox_err_to_dos(vboxerr err)
{
	switch (err) {
	case VINF_SUCCESS:
		return DOS_ERROR_SUCCESS;
	case VERR_INVALID_PARAMETER:
		return DOS_ERROR_INVALID_FUNCTION;
	case VERR_INVALID_HANDLE:
		return DOS_ERROR_INVALID_HANDLE;
	case VERR_FILE_NOT_FOUND:
		return DOS_ERROR_FILE_NOT_FOUND;
	case VERR_PATH_NOT_FOUND:
		return DOS_ERROR_PATH_NOT_FOUND;
	case VERR_NO_MORE_FILES:
		return DOS_ERROR_NO_MORE_FILES;
	case VERR_ALREADY_EXISTS:
		return DOS_ERROR_FILE_EXISTS;
	case VERR_TOO_MANY_OPEN_FILES:
		return DOS_ERROR_TOO_MANY_OPEN_FILES;
	case VERR_WRITE_PROTECT:
		return DOS_ERROR_WRITE_PROTECT;
	case VERR_NOT_A_DIRECTORY:
	case VERR_DIR_NOT_EMPTY: // Behavior seen in real DOS
		return DOS_ERROR_PATH_NOT_FOUND;
	default:
		return DOS_ERROR_GEN_FAILURE;
	}
}

static void set_vbox_err(union INTPACK __far *r, vboxerr err)
{
	dlog_print("->vbox error ");
	if (err < INT16_MIN || err > INT16_MAX) {
		dlog_printx(err >> 16);
		dlog_print(":");
		dlog_printx(err & 0xFFFF);
	} else {
		dlog_printd(err);
	}
	dlog_endline();
	set_dos_err(r, vbox_err_to_dos(err));
}

static int my_strrchr(const char __far *str, char c)
{
	int last = -1;
	const char __far *s = str;
	while (*s) {
		if (*s == c) last = s - str;
		s++;
	}
	return last;
}

static const char * get_basename(const char *path)
{
	int last_sep = my_strrchr(path, '\\');
	if (last_sep >= 0) {
		return &path[last_sep+1];
	} else {
		return path;
	}
}

static void translate_filename_to_host(SHFLSTRING *str)
{
	// TODO This should map UTF-8 to local CP :(
	(void) str;
}

static void translate_filename_from_host(SHFLSTRING *str)
{
	// TODO This should map UTF-8 to local CP :(
	// At least do a poor man's uppercase...
	unsigned i;
	for (i = 0; i < str->u16Length; i++) {
		if (str->ach[i] >= 'a' && str->ach[i] <= 'z') {
			str->ach[i] = 'A' + (str->ach[i] - 'a');
		}
	}
}

static void fix_wildcards(SHFLSTRING *str)
{
	unsigned i;

	// If this is the standard ????????.??? patterns, replace with *
	if (str->u16Length >= 8+1+3) {
		i = str->u16Length - (8+1+3);
		if (memcmp(&str->ach[i], "????????.???", (8+1+3)) == 0) {
			strcpy(&str->ach[i], "*");
			str->u16Length = i + 1;
		}
	}

	for (i = 1; i < str->u16Length; i++) {
		// VirtualBox will only match N consecutive ?s to filenames longer than N
		// Replace consecutive ???? with ?***
		if ( str->ach[i] == '?' &&
		     (str->ach[i-1] == '*' || str->ach[i-1] == '?') ) {
			str->ach[i] = '*';
		}
	}
}


static void copy_drive_relative_filename(SHFLSTRING *str, const char __far *path)
{
	// Assume X:.... path for now, i.e. drive_relative path starts at char 2
	shflstring_strcpy(str, path + 2);
}

static void copy_drive_relative_dirname(SHFLSTRING *str, const char __far *path)
{
	int last_sep = my_strrchr(path + 2, '\\');
	if (last_sep >= 0) {
		shflstring_strncpy(str, path + 2, last_sep == 0 ? 1 : last_sep);
	} else {
		shflstring_strcpy(str, path + 2);
	}
}

static bool copy_to_8_3_filename(char __far *dst, const SHFLSTRING *str)
{
	int last_dot = my_strrchr(str->ach, '.');
	unsigned namelen, extlen;
	bool valid_8_3 = true;

	namelen = last_dot >= 0 ? last_dot : str->u16Length;
	extlen = last_dot >= 0 ? str->u16Length - (last_dot + 1) : 0;

	if (extlen == 0 && (namelen <= 1 && str->ach[0] == '.')) {
		// . , .. files
		namelen = str->u16Length;
		extlen = 0;
	}

	if (namelen > 8) {
		namelen = 8;
		valid_8_3 = false;
	}

	if (extlen > 3) {
		extlen = 3;
		valid_8_3 = false;
	}

	_fmemcpy(&dst[0], str->ach, namelen);
	_fmemset(&dst[namelen], ' ', 8 - namelen);
	_fmemcpy(&dst[8], str->ach + last_dot + 1, extlen);
	_fmemset(&dst[8+extlen], ' ', 3 - extlen);

	return valid_8_3;
}

static uint16_t find_free_openfile()
{
	unsigned i;
	for (i = 1; i < NUM_FILES; i++) {
		if (data.files[i].root == SHFL_ROOT_NIL) {
			return i;
		}
	}
	return 0;
}

static bool is_valid_openfile_index(unsigned index)
{
	if (index > NUM_FILES) return false;
	if (index < 1) return false; // User programs cannot use index 0
	if (data.files[index].root == SHFL_ROOT_NIL) return 0;
	return true;
}

static inline void set_sft_openfile_index(DOSSFT __far *sft, unsigned index)
{
	sft->start_cluster = index;
}

static inline unsigned get_sft_openfile_index(DOSSFT __far *sft)
{
	return sft->start_cluster;
}

static void handle_create_open_ex(union INTPACK __far *r)
{
	const char __far *path = data.dossda->fn1;
	int drive = drive_letter_to_index(path[0]);
	SHFLROOT root = data.drives[drive].root;
	DOSSFT __far *sft = MK_FP(r->x.es, r->x.di);
	unsigned int action, mode;
	unsigned openfile;
	bool save_result;
	vboxerr err;

	switch (r->h.al) {
	case DOS_FN_CREATE:
		action = OPENEX_CREATE_IF_NEW | OPENEX_REPLACE_IF_EXISTS;
		mode = OPENEX_MODE_WRITE;
		save_result = false;
		break;
	case DOS_FN_OPEN:
		action = OPENEX_FAIL_IF_NEW | OPENEX_OPEN_IF_EXISTS;
		mode = data.dossda->open_mode & 0x7F;
		save_result = false;
		break;
	case DOS_FN_OPEN_EX:
	default:
		action = data.dossda->openex_act;
		mode = data.dossda->openex_mode & 0x7F;
		save_result = true;
		break;
	}

	dlog_print("handle_open for ");
	dlog_fprint(path);
	dlog_print(" act=");
	dlog_printx(action);
	dlog_print(" mode=");
	dlog_printx(mode);
	dlog_endline();

	openfile = find_free_openfile();
	if (!openfile) {
		set_dos_err(r, DOS_ERROR_TOO_MANY_OPEN_FILES);
		return;
	}

	copy_drive_relative_filename(&shflstr.shflstr, path);
	translate_filename_to_host(&shflstr.shflstr);

	memset(&parms.create, 0, sizeof(SHFLCREATEPARMS));
	if (action & OPENEX_REPLACE_IF_EXISTS) {
		parms.create.CreateFlags |= SHFL_CF_ACT_REPLACE_IF_EXISTS;
	} else if (action & OPENEX_OPEN_IF_EXISTS) {
		parms.create.CreateFlags |= SHFL_CF_ACT_OPEN_IF_EXISTS;
	} else {
		parms.create.CreateFlags |= SHFL_CF_ACT_FAIL_IF_EXISTS;
	}
	if (action & OPENEX_CREATE_IF_NEW) {
		parms.create.CreateFlags |= SHFL_CF_ACT_CREATE_IF_NEW;
	} else {
		parms.create.CreateFlags |= SHFL_CF_ACT_FAIL_IF_NEW;
	}

	if ((mode & OPENEX_MODE_RDWR) == OPENEX_MODE_RDWR) {
		parms.create.CreateFlags |= SHFL_CF_ACCESS_READWRITE;
	} else if (mode & OPENEX_MODE_WRITE) {
		parms.create.CreateFlags |= SHFL_CF_ACCESS_WRITE;
	} else {
		parms.create.CreateFlags |= SHFL_CF_ACCESS_READ;
	}

	if (!(parms.create.CreateFlags & SHFL_CF_ACCESS_WRITE)) {
		// Do we really want to create new files without opening them for writing?
		parms.create.CreateFlags |= SHFL_CF_ACT_FAIL_IF_NEW;
	}

	dlog_print("vbox create flags=");
	dlog_printx(parms.create.CreateFlags);
	dlog_endline();

	err = vbox_shfl_open(&data.vb, data.hgcm_client_id, root, &shflstr.shflstr, &parms.create);
	if (err) {
		set_vbox_err(r, err);
		return;
	}

	dlog_print("vbox success result=");
	dlog_printd(parms.create.Result);
	dlog_print(" openfile=");
	dlog_printu(openfile);
	dlog_endline();

	switch (parms.create.Result) {
	case SHFL_PATH_NOT_FOUND:
		set_dos_err(r, DOS_ERROR_PATH_NOT_FOUND);
		return;
	case SHFL_FILE_NOT_FOUND:
		set_dos_err(r, DOS_ERROR_FILE_NOT_FOUND);
		return;
	case SHFL_FILE_EXISTS:
		if (save_result) r->x.cx = OPENEX_FILE_OPENED;
		break;
	case SHFL_FILE_CREATED:
		if (save_result) r->x.cx = OPENEX_FILE_CREATED;
		break;
	case SHFL_FILE_REPLACED:
		if (save_result) r->x.cx = OPENEX_FILE_REPLACED;
		break;
	}

	if (parms.create.Handle == SHFL_HANDLE_NIL) {
		set_dos_err(r, DOS_ERROR_GEN_FAILURE);
		return;
	}

	data.files[openfile].root = root;
	data.files[openfile].handle = parms.create.Handle;

	// Fill in the SFT
	map_shfl_info_to_dossft(sft, &parms.create.Info);
	sft->open_mode = mode;
	sft->dev_info = 0x8040 | drive; // "Network drive, unwritten to"
	sft->f_pos = 0;
	set_sft_openfile_index(sft, openfile);

	clear_dos_err(r);
}

static void handle_close(union INTPACK __far *r)
{
	DOSSFT __far *sft = MK_FP(r->x.es, r->x.di);
	unsigned openfile = get_sft_openfile_index(sft);
	vboxerr err;

	dlog_print("handle_close openfile=");
	dlog_printu(openfile);
	dlog_endline();

	if (!is_valid_openfile_index(openfile)) {
		set_dos_err(r, DOS_ERROR_INVALID_HANDLE);
		return;
	}

	err = vbox_shfl_close(&data.vb, data.hgcm_client_id,
	                      data.files[openfile].root, data.files[openfile].handle);
	if (err) {
		set_vbox_err(r, err);
		return;
	}

	dos_sft_decref(sft);

	data.files[openfile].root = SHFL_ROOT_NIL;
	data.files[openfile].handle = SHFL_HANDLE_NIL;

	clear_dos_err(r);
}

static void handle_read(union INTPACK __far *r)
{
	DOSSFT __far *sft = MK_FP(r->x.es, r->x.di);
	unsigned openfile = get_sft_openfile_index(sft);
	uint8_t __far *buffer = data.dossda->cur_dta;
	unsigned long offset = sft->f_pos;
	unsigned bytes = r->x.cx;
	vboxerr err;

	dlog_print("handle_read openfile=");
	dlog_printu(openfile);
	dlog_print(" bytes=");
	dlog_printu(bytes);
	dlog_endline();

	if (!is_valid_openfile_index(openfile)) {
		set_dos_err(r, DOS_ERROR_INVALID_HANDLE);
		return;
	}

	err = vbox_shfl_read(&data.vb, data.hgcm_client_id,
	                     data.files[openfile].root, data.files[openfile].handle,
	                     offset, &bytes, buffer);
	if (err) {
		set_vbox_err(r, err);
		return;
	}

	dlog_print("handle_read bytes_read=");
	dlog_printu(bytes);
	dlog_endline();

	// Advance the file position
	sft->f_pos += bytes;

	r->x.cx = bytes;
	clear_dos_err(r);
}

static void handle_write(union INTPACK __far *r)
{
	DOSSFT __far *sft = MK_FP(r->x.es, r->x.di);
	unsigned openfile = get_sft_openfile_index(sft);
	uint8_t __far *buffer = data.dossda->cur_dta;
	unsigned long offset = sft->f_pos;
	unsigned bytes = r->x.cx;
	vboxerr err;

	dlog_print("handle_write openfile=");
	dlog_printu(openfile);
	dlog_print(" bytes=");
	dlog_printu(bytes);
	dlog_endline();

	if (!is_valid_openfile_index(openfile)) {
		set_dos_err(r, DOS_ERROR_INVALID_HANDLE);
		return;
	}

	err = vbox_shfl_write(&data.vb, data.hgcm_client_id,
	                      data.files[openfile].root, data.files[openfile].handle,
	                      offset, &bytes, buffer);
	if (err) {
		set_vbox_err(r, err);
		return;
	}

	dlog_print("handle_write bytes_written=");
	dlog_printu(bytes);
	dlog_endline();

	// Advance the file position
	sft->f_pos += bytes;

	// Assume the file has grown if we've written past the end
	if (sft->f_pos > sft->f_size) sft->f_size = sft->f_pos;

	r->x.cx = bytes;
	clear_dos_err(r);
}

static void handle_lock(union INTPACK __far *r)
{
	DOSSFT __far *sft = MK_FP(r->x.es, r->x.di);
	unsigned openfile = get_sft_openfile_index(sft);
	bool unlock = r->h.bl ? true : false;
	unsigned numops = r->x.cx, i;
	unsigned flags = (unlock ? SHFL_LOCK_CANCEL : SHFL_LOCK_EXCLUSIVE)
	        | SHFL_LOCK_WAIT | SHFL_LOCK_PARTIAL;
	DOSLOCK __far *ops = MK_FP(r->x.ds, r->x.dx);
	vboxerr err;

	dlog_print("handle_lock ");
	if (unlock) dlog_print("unlock");
	dlog_print(" numops=");
	dlog_printu(numops);
	dlog_endline();

	for (i = 0; i < numops; i++) {
		err = vbox_shfl_lock(&data.vb, data.hgcm_client_id,
		                     data.files[openfile].root, data.files[openfile].handle,
		                     ops[i].start_offset, ops[i].region_size, flags);
		if (err) {
			set_vbox_err(r, err);
			return;
		}
	}

	clear_dos_err(r);
}

static void handle_close_all(union INTPACK __far *r)
{
	vboxerr err;
	unsigned i;

	dlog_puts("handle_close_all");

	for (i = 0; i < NUM_FILES; ++i) {
		if (data.files[i].root != SHFL_ROOT_NIL) {
			err = vbox_shfl_close(&data.vb, data.hgcm_client_id,
			                      data.files[i].root, data.files[i].handle);
			if (err) {
				dlog_puts("vbox error on close all...");
				// We'll leak this handle...
			}

			data.files[i].root = SHFL_ROOT_NIL;
			data.files[i].handle = SHFL_HANDLE_NIL;
		}
	}

	clear_dos_err(r);
}

static void handle_delete(union INTPACK __far *r)
{
	const char __far *path = data.dossda->fn1;
	int drive = drive_letter_to_index(path[0]);
	SHFLROOT root = data.drives[drive].root;
	vboxerr err;

	dlog_print("handle_delete ");
	dlog_fprint(path);
	dlog_endline();

	copy_drive_relative_filename(&shflstr.shflstr, path);
	translate_filename_to_host(&shflstr.shflstr);

	err = vbox_shfl_remove(&data.vb, data.hgcm_client_id, root,
	                       &shflstr.shflstr, SHFL_REMOVE_FILE);
	if (err) {
		set_vbox_err(r, err);
		return;
	}

	clear_dos_err(r);
}

static void handle_rename(union INTPACK __far *r)
{
	const char __far *src = data.dossda->fn1;
	int srcdrive = drive_letter_to_index(src[0]);
	const char __far *dst = data.dossda->fn2;
	int dstdrive = drive_letter_to_index(dst[0]);
	SHFLROOT root = data.drives[srcdrive].root;
	vboxerr err;

	dlog_print("handle_rename ");
	dlog_fprint(src);
	dlog_print(" to ");
	dlog_fprint(dst);
	dlog_endline();

	if (srcdrive != dstdrive) {
		set_dos_err(r, DOS_ERROR_NOT_SAME_DEVICE);
		return;
	}

	copy_drive_relative_filename(&shflstr.shflstr, src);
	translate_filename_to_host(&shflstr.shflstr);

	// Reusing shfldirinfo buffer space here
	// Hoping no one does concurrent find_next and rename
	copy_drive_relative_filename(&shfldirinfo.dirinfo.name, dst);
	translate_filename_to_host(&shfldirinfo.dirinfo.name);

	err = vbox_shfl_rename(&data.vb, data.hgcm_client_id, root,
	                       &shflstr.shflstr, &shfldirinfo.dirinfo.name,
	                       SHFL_RENAME_DIR | SHFL_RENAME_FILE);
	if (err) {
		set_vbox_err(r, err);
		return;
	}

	clear_dos_err(r);
}

static void handle_getattr(union INTPACK __far *r)
{
	const char __far *path = data.dossda->fn1;
	int drive = drive_letter_to_index(path[0]);
	SHFLROOT root = data.drives[drive].root;
	vboxerr err;

	dlog_print("handle_getattr ");
	dlog_fprint(path);
	dlog_endline();

	copy_drive_relative_filename(&shflstr.shflstr, path);
	translate_filename_to_host(&shflstr.shflstr);

	memset(&parms.create, 0, sizeof(SHFLCREATEPARMS));
	parms.create.CreateFlags = SHFL_CF_LOOKUP;

	err = vbox_shfl_open(&data.vb, data.hgcm_client_id, root,
	                     &shflstr.shflstr, &parms.create);
	if (err) {
		set_vbox_err(r, err);
		return;
	}
	switch (parms.create.Result) {
	case SHFL_PATH_NOT_FOUND:
		set_dos_err(r, DOS_ERROR_PATH_NOT_FOUND);
		return;
	case SHFL_FILE_NOT_FOUND:
		set_dos_err(r, DOS_ERROR_PATH_NOT_FOUND);
		return;
	default:
		break;
	}

	map_shfl_info_to_getattr(r, &parms.create.Info);
	clear_dos_err(r);
}


static vboxerr open_search_dir(SHFLROOT root, const char __far *path)
{
	vboxerr err;

	dlog_puts("open_search_dir");

	copy_drive_relative_dirname(&shflstr.shflstr, path);
	translate_filename_to_host(&shflstr.shflstr);

	memset(&parms.create, 0, sizeof(SHFLCREATEPARMS));
	parms.create.CreateFlags = SHFL_CF_DIRECTORY
	        | SHFL_CF_ACT_OPEN_IF_EXISTS | SHFL_CF_ACT_FAIL_IF_NEW
	        | SHFL_CF_ACCESS_READ;

	err = vbox_shfl_open(&data.vb, data.hgcm_client_id, root,
	                     &shflstr.shflstr, &parms.create);
	if (err) {
		dlog_puts("open search dir failed");
		return err;
	}

	switch (parms.create.Result) {
	case SHFL_PATH_NOT_FOUND:
		return VERR_PATH_NOT_FOUND;
	case SHFL_FILE_NOT_FOUND:
		return VERR_FILE_NOT_FOUND;
	default:
		break;
	}

	if (parms.create.Handle == SHFL_HANDLE_NIL) {
		dlog_puts("open search dir returned no handle...");
		return VERR_INVALID_HANDLE;
	}

	data.files[SEARCH_DIR_FILE].root = root;
	data.files[SEARCH_DIR_FILE].handle = parms.create.Handle;

	return 0;
}

static void close_search_dir()
{
	vboxerr err;

	if (data.files[SEARCH_DIR_FILE].root == SHFL_ROOT_NIL) {
		// Already closed
		return;
	}

	err = vbox_shfl_close(&data.vb, data.hgcm_client_id,
	                      data.files[SEARCH_DIR_FILE].root,
	                      data.files[SEARCH_DIR_FILE].handle);
	if (err) {
		dlog_puts("vbox error on close_search_dir, ignoring");
	}

	data.files[SEARCH_DIR_FILE].root = SHFL_ROOT_NIL;
	data.files[SEARCH_DIR_FILE].handle = SHFL_HANDLE_NIL;
}

static inline bool is_search_dir_open()
{
	return data.files[SEARCH_DIR_FILE].root != SHFL_ROOT_NIL;
}

/** Simulates a directory entry with the current volume label. */
static vboxerr find_volume_label(SHFLROOT root)
{
	DOSDIR __far *found_file = &data.dossda->found_file;
	vboxerr err;

	shflstring_clear(&shflstr.shflstr);

	err = vbox_shfl_query_map_name(&data.vb, data.hgcm_client_id, root, &shflstr.shflstr);
	if (err) return err;

	translate_filename_from_host(&shflstr.shflstr);

	dlog_print("label: ");
	dlog_fprint(shflstr.buf);
	dlog_endline();

	found_file->attr = _A_VOLID;
	copy_to_8_3_filename(found_file->filename, &shflstr.shflstr);
	found_file->f_date = 0;
	found_file->f_time = 0;
	found_file->f_size = 0;
	found_file->start_cluster = 0;

	return 0;
}

/** Gets and fills in the next directory entry from VirtualBox. */
static vboxerr find_next_from_vbox(uint8_t search_attr)
{
	DOSDIR __far *found_file = &data.dossda->found_file;
	vboxerr err;

	if (!is_search_dir_open()) {
		dlog_puts("find_next called, but no opendir handle");
		return VERR_INVALID_HANDLE;
	}

	while (1) { // Loop until we have a valid file (or an error)
		unsigned size = sizeof(shfldirinfo), resume = 0, count = 0;
		dlog_puts("calling vbox list");

		err = vbox_shfl_list(&data.vb, data.hgcm_client_id,
		                     data.files[SEARCH_DIR_FILE].root, data.files[SEARCH_DIR_FILE].handle,
		                     SHFL_LIST_RETURN_ONE, &size, &shflstr.shflstr, &shfldirinfo.dirinfo,
		                     &resume, &count);

		// Reset the size of the buffer here since VirtualBox "shortens" it,
		// (since it expects to fit in more entries in the same space, but
		//  we won't allow that via SHFL_LIST_RETURN_ONE).
		shfldirinfo.dirinfo.name.u16Size = sizeof(shfldirinfo.buf);

		if (err) {
			return err;
		}

		if (count != 1) {
			return VERR_IO_BAD_LENGTH;
		}

		dlog_print("got diritem name=");
		dlog_fprint(shfldirinfo.dirinfo.name.ach);
		dlog_print(" sfnLen=");
		dlog_printu(shfldirinfo.dirinfo.cucShortName);
		dlog_endline();

		// TODO Use the short filename if available from a windows host
		// i.e. shfldirinfo.dirinfo.cucShortName

		translate_filename_from_host(&shfldirinfo.dirinfo.name);

		if (!copy_to_8_3_filename(found_file->filename, &shfldirinfo.dirinfo.name)) {
			dlog_puts("hiding file with long filename");
			continue;
		}
		map_shfl_info_to_dosdir(found_file, &shfldirinfo.dirinfo.Info);

		if (found_file->attr & ~search_attr) {
			continue; // Skip this one
		}

		break;
	};

	return 0;
}

static void handle_find(union INTPACK __far *r)
{
	const char __far *path = data.dossda->fn1;
	const char __far *search_mask = data.dossda->fcb_fn1;
	int drive = drive_letter_to_index(path[0]);
	SHFLROOT root = data.drives[drive].root;
	DOSDIR __far *found_file = &data.dossda->found_file;
	uint8_t search_attr;
	vboxerr err;

	if (r->h.al == DOS_FN_FIND_FIRST) {
		search_attr = data.dossda->search_attr;

		dlog_print("find_first path=");
		dlog_fprint(path);
		dlog_print(" mask=");
		dlog_fnprint(search_mask, 8+3);
		dlog_print(" attr=");
		dlog_printx(search_attr);
		dlog_endline();

		close_search_dir();
		err = open_search_dir(root, path);
		if (err) {
			set_vbox_err(r, err);
			return;
		}

		copy_drive_relative_filename(&shflstr.shflstr, path);
		translate_filename_to_host(&shflstr.shflstr);
		fix_wildcards(&shflstr.shflstr);

		// It is important that we initialize DOS' search structure
		// or DOS may decide never to call us again
		data.dossda->sdb.drive_letter = 0x80 | drive;
		data.dossda->sdb.search_attr = search_attr;
		_fmemcpy(data.dossda->sdb.search_templ, search_mask, 8+3);
		data.dossda->sdb.dir_entry = 0;
		data.dossda->sdb.par_clstr = 0;

		if (search_attr & _A_VOLID) {
			// Simulate an initial entry with the volume label
			// if we are searching for it.
			// DOS actually expects to always find it first.
			dlog_puts("search volid");
			err = find_volume_label(root);
			if (err) {
				dlog_puts("search volid err");
				set_vbox_err(r, err);
				return;
			}
			dlog_puts("search volid OK");
			clear_dos_err(r);
			return;
		}
	} else {
		search_attr = data.dossda->sdb.search_attr;

		dlog_print("find_next");
		dlog_print(" attr=");
		dlog_printx(search_attr);
		dlog_endline();
	}

	err = find_next_from_vbox(search_attr);
	if (err) {
		if (err == VERR_NO_MORE_FILES) {
			dlog_puts("no more files");
		}
		close_search_dir();
		set_vbox_err(r, err);
		return;
	}

	dlog_print("accepted file name='");
	dlog_fnprint(&found_file->filename[0], 8);
	dlog_putc(' ');
	dlog_fnprint(&found_file->filename[8], 3);
	dlog_print("' attr=");
	dlog_printx(found_file->attr);
	dlog_endline();

	clear_dos_err(r);
}

static void handle_chdir(union INTPACK __far *r)
{
	const char __far *path = data.dossda->fn1;
	int drive = drive_letter_to_index(path[0]);
	SHFLROOT root = data.drives[drive].root;
	vboxerr err;

	dlog_print("handle_chdir to ");
	dlog_fprint(path);
	dlog_endline();

	// Just have to check if the directory exists
	copy_drive_relative_filename(&shflstr.shflstr, path);
	translate_filename_to_host(&shflstr.shflstr);

	memset(&parms.create, 0, sizeof(SHFLCREATEPARMS));
	parms.create.CreateFlags = SHFL_CF_LOOKUP;

	err = vbox_shfl_open(&data.vb, data.hgcm_client_id, root,
	                     &shflstr.shflstr, &parms.create);
	if (err) {
		set_vbox_err(r, err);
		return;
	}

	switch (parms.create.Result) {
	case SHFL_PATH_NOT_FOUND:
	case SHFL_FILE_NOT_FOUND:
		set_dos_err(r, DOS_ERROR_PATH_NOT_FOUND);
		return;
	default:
		break;
	}

	// Also check whether it is really a directory
	if (!(map_shfl_attr_to_dosattr(&parms.create.Info.Attr) & _A_SUBDIR)) {
		set_dos_err(r, DOS_ERROR_PATH_NOT_FOUND);
		return;
	}

	clear_dos_err(r);
}

static void handle_mkdir(union INTPACK __far *r)
{
	const char __far *path = data.dossda->fn1;
	int drive = drive_letter_to_index(path[0]);
	SHFLROOT root = data.drives[drive].root;
	vboxerr err;

	dlog_print("handle_mkdir ");
	dlog_fprint(path);
	dlog_endline();

	copy_drive_relative_filename(&shflstr.shflstr, path);
	translate_filename_to_host(&shflstr.shflstr);

	memset(&parms.create, 0, sizeof(SHFLCREATEPARMS));
	parms.create.CreateFlags = SHFL_CF_DIRECTORY
	        | SHFL_CF_ACT_FAIL_IF_EXISTS | SHFL_CF_ACT_CREATE_IF_NEW;

	err = vbox_shfl_open(&data.vb, data.hgcm_client_id, root,
	                     &shflstr.shflstr, &parms.create);
	if (err) {
		set_vbox_err(r, err);
		return;
	}

	switch (parms.create.Result) {
	case SHFL_PATH_NOT_FOUND:
	case SHFL_FILE_NOT_FOUND:
		set_dos_err(r, DOS_ERROR_PATH_NOT_FOUND);
		return;
	case SHFL_FILE_EXISTS:
		set_dos_err(r, DOS_ERROR_FILE_EXISTS);
		return;
	default:
		break;
	}

	clear_dos_err(r);
}

static void handle_rmdir(union INTPACK __far *r)
{
	const char __far *path = data.dossda->fn1;
	int drive = drive_letter_to_index(path[0]);
	SHFLROOT root = data.drives[drive].root;
	vboxerr err;

	dlog_print("handle_rmdir ");
	dlog_fprint(path);
	dlog_endline();

	copy_drive_relative_filename(&shflstr.shflstr, path);
	translate_filename_to_host(&shflstr.shflstr);

	err = vbox_shfl_remove(&data.vb, data.hgcm_client_id, root,
	                       &shflstr.shflstr, SHFL_REMOVE_DIR);
	if (err) {
		set_vbox_err(r, err);
		return;
	}

	clear_dos_err(r);
}

static void handle_get_disk_free(union INTPACK __far *r)
{
	const unsigned long total_space = 10 * 1024 * 1024UL;
	const unsigned long free_space = 4 * 1024 * 1024UL;
	const unsigned cluster_bytes = 4 * 4096UL;

	// TODO SHFLVOLINFO

	r->h.ah = 0; // media ID byte
	r->h.al = 4; /* Sectors per cluster */
	r->x.cx = 4096; /* Bytes per sector */
	r->x.bx = total_space / cluster_bytes; /* Total clusters */
	r->x.dx = free_space / cluster_bytes;  /* Number of available clusters */

	dlog_print("disk free");
	dlog_printd(r->x.dx);
	dlog_endline();

	clear_dos_err(r);
}

static bool int2f_11_handler(union INTPACK r)
#pragma aux int2f_11_handler "*" parm caller [] value [al] modify [ax bx cx dx si di es gs fs]
{
	if (r.h.ah != 0x11) return false; // Only interested in network redirector functions
	if (r.h.al == 0xff && r.x.bx == 0x5742 && r.x.cx == 0x5346) {
		// These are the magic numbers to our private "Get TSR data" function
		dlog_puts("Get TSR data");
		r.x.es = get_ds();
		r.x.di = FP_OFF(&data);
		r.x.bx = 0x5444;
		r.x.cx = 1;
		return true;
	}

	dlog_print("2f al=");
	dlog_printx(r.h.al);
	dlog_endline();

	// Handle special functions that target all redirectors first
	switch (r.h.al) {
	case DOS_FN_CLOSE_ALL:
		handle_close_all(&r);
		return false; // Let others do the same
	}

	// Now handle normal functions if they refer to our mounted drives
	if (!is_call_for_mounted_drive(&r)) {
		return false;
	}

	switch (r.h.al) {
	case DOS_FN_CLOSE:
		handle_close(&r);
		return true;
	case DOS_FN_CREATE:
	case DOS_FN_OPEN:
	case DOS_FN_OPEN_EX:
		handle_create_open_ex(&r);
		return true;
	case DOS_FN_READ:
		handle_read(&r);
		return true;
	case DOS_FN_WRITE:
		handle_write(&r);
		return true;
	case DOS_FN_LOCK:
		handle_lock(&r);
		return true;
	case DOS_FN_DELETE:
		handle_delete(&r);
		return true;
	case DOS_FN_RENAME:
		handle_rename(&r);
		return true;
	case DOS_FN_GET_FILE_ATTR:
		handle_getattr(&r);
		return true;
	case DOS_FN_FIND_FIRST:
	case DOS_FN_FIND_NEXT:
		handle_find(&r);
		return true;
	case DOS_FN_CHDIR:
		handle_chdir(&r);
		return true;
	case DOS_FN_MKDIR:
		handle_mkdir(&r);
		return true;
	case DOS_FN_RMDIR:
		handle_rmdir(&r);
		return true;
	case DOS_FN_GET_DISK_FREE:
		handle_get_disk_free(&r);
		return true;
	case DOS_FN_SEEK_END:
		// I have no testcase for this function, so unsupported
		set_dos_err(&r, DOS_ERROR_INVALID_FUNCTION);
		return true;
	}

	return false;
}

void __declspec(naked) __far int2f_isr(void)
{
	__asm {
		pusha
		push ds
		push es
		push fs
		push gs

		mov bp, sp
		push cs
		pop ds

		call int2f_11_handler
		test al, al
		jnz handled

		pop gs
		pop fs
		pop es
		pop ds
		popa

		; Jump to the next handler in the chain
		jmp dword ptr cs:[data + 0] ; wasm doesn't support structs, this is data.prev_int2f_handler

	handled:
		pop gs
		pop fs
		pop es
		pop ds
		popa
		iret
	}
}

static LPTSRDATA int2f_get_tsr_data(void);
#pragma aux int2f_get_tsr_data = \
	"mov ax, 0x11ff" \
	"mov bx, 0x5742" /* Add magic numbers */ \
	"mov cx, 0x5346" \
	"int 0x2f"   \
	"cmp bx, 0x5444" /* Test output magic number */ \
	"jne fail" \
	"cmp cx, 1" \
	"jne fail" \
	"jmp end" \
	"fail:" \
	"xor ax, ax" \
	"mov es, ax" \
	"mov di, ax" \
	"end:" \
	__value [es di] \
	__modify [ax bx cx]

LPTSRDATA __far get_tsr_data(bool installed)
{
	if (installed) {
		return int2f_get_tsr_data();
	} else {
		return MK_FP(get_cs(), FP_OFF(&data));
	}
}

int resident_end;