-
Notifications
You must be signed in to change notification settings - Fork 6
/
dl.c
2541 lines (2229 loc) · 74.8 KB
/
dl.c
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
/*
* DeskLink for *nix (dl)
* Copyright (C) 2004
* Stephen Hurd
*
* Redistribution of modified and unmodified copies
* is premitted provided the copyright remains intact
*/
/*
DeskLink+
2005 John R. Hogerhuis Extensions and enhancements
2019 Brian K. White - repackaging, reorganizing, bootstrap function
2020 Kurt McCullum - TS-DOS loaders
2022 Gabriele Gorla - TS-DOS subdirectories
DeskLink2
2023 Brian K. White - disk image files, pdd1 FDC mode, pdd2 cache & memory
DeskLink2 is free software; you can redistribute it and/or modify it
under the terms of the GNU General Public License version 2 or any
later version as published by the Free Software Foundation.
DeskLink2 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 (in the file "COPYING"); if not, write to the
Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
MA 02111, USA.
*/
#include <termios.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/param.h>
#include <dirent.h>
#include <unistd.h>
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#include <errno.h>
#include <stdbool.h>
#include "constants.h"
#include "dir_list.h"
#if defined(__APPLE__) || defined(__NetBSD__) || defined(OpenBSD)
#include <util.h>
#endif
#if defined(__FreeBSD__)
#include <libutil.h>
#endif
#if defined(__linux__)
#include <utmp.h>
#endif
#if defined(USE_XATTR)
# if defined(__FreeBSD__)
# include <sys/extattr.h>
# else
# include <sys/xattr.h>
# endif
# if defined(__linux__)
# define XATTR_PREFIX "user."
# define XATTR_SUFFIX ""
# elif defined(__APPLE__)
# define XATTR_PREFIX ""
# define XATTR_SUFFIX "#S"
# else
# define XATTR_PREFIX ""
# define XATTR_SUFFIX ""
# endif
#endif
/*** config **************************************************/
#ifndef APP_NAME
#define APP_NAME "DeskLink2"
#endif
#ifndef APP_LIB_DIR
#define APP_LIB_DIR "."
#endif
#ifndef TTY_PREFIX
#define TTY_PREFIX "ttyS"
#endif
#ifndef DEFAULT_BAUD
#define DEFAULT_BAUD 19200
#endif
// default model emulation, 1=pdd1 2=pdd2
// TS-DOS directories requires tpdd1
#ifndef DEFAULT_MODEL
#define DEFAULT_MODEL 1
#endif
// if a loader fails in bootstrap(), try increasing this
#ifndef DEFAULT_BASIC_BYTE_MS
#define DEFAULT_BASIC_BYTE_MS 8
#endif
// TODO
// * What does Cambridge Z88 do?
// * What do CP/M clients do?
// * What do the original Brother knitting machines do?
#ifndef DEFAULT_ATTR
#define DEFAULT_ATTR 0x46 // F
#endif
#ifndef RAW_ATTR
#define RAW_ATTR 0x20 // space
#endif
#if defined(USE_XATTR) && !defined(XATTR_NAME)
#define XATTR_NAME "pdd.attr"
#endif
#define DEFAULT_TPDD1_IMG_SUFFIX ".pdd1"
#define DEFAULT_TPDD2_IMG_SUFFIX ".pdd2"
#ifndef DEFAULT_UPCASE
#define DEFAULT_UPCASE false
#endif
#ifndef DEFAULT_RTSCTS
#define DEFAULT_RTSCTS false
#endif
#ifndef DEFAULT_DOTPOS
#define DEFAULT_DOTPOS DOT_FLOPPY
#endif
#ifndef DEFAULT_OPERATION_MODE
#define DEFAULT_OPERATION_MODE MODE_OPR
#endif
#ifndef DEFAULT_TILDES
#define DEFAULT_TILDES true
#endif
// To mimic the original Desk-Link from Travelling Software:
//#define DEFAULT_DME_ROOT_LABEL "ROOT "
//#define DEFAULT_DME_PARENT_LABEL "PARENT"
#ifndef TSDOS_ROOT_LABEL
#define TSDOS_ROOT_LABEL "0: "
#endif
#ifndef TSDOS_PARENT_LABEL
#define TSDOS_PARENT_LABEL "^ "
#endif
// you can't change this unless you also hack ts-dos
#define TSDOS_DIR_LABEL "<>"
/*
* Support for Ultimate ROM II TS-DOS & Sardine loader: see ref/ur2.txt
* These filenames will always be loadable "by magic" in any cd path, even
* if no such filename exists anywhere in the share tree. For any of these
* filenames, search the following paths: cwd, share root, app_lib_dir.
* TODO add $XDG_DATA_HOME (~/.local/share/myapp mac: ~/Library/myapp/)
*/
const char * magic_files [] = {
"DOS100.CO",
"DOS200.CO",
"DOSNEC.CO",
"SAR100.CO",
"SAR200.CO",
"SARNEC.CO", // SARNEC.CO is known to have existed, but is currently lost.
"DOSM10.CO", // The rest of these probably never existed.
"DOSK85.CO", //
"SARM10.CO", //
"SARK85.CO" //
};
// terminal emulation
#define SSO "\033[7m" // set standout
#define RSO "\033[m" // reset standout
#define D8C "\033 F" // disable 8-bit vtxx control bytes (0x80-0x9F)
// The roms in Brother FB-100, knitking FDD19, Purple Computing D103, and
// TANDY 26-3808 have all been dumped and compared, and are all identical.
// So the rom is from Brother not TANDY.
//#ifndef FB100_ROM
//#define FB100_ROM "fb100.rom"
//#endif
#ifndef TPDD2_ROM
#define TPDD2_ROM "tpdd2.rom"
#endif
// termios VMIN & VTIME
#define C_CC_VMIN 1
#define C_CC_VTIME 5
/*************************************************************/
int debug = 0;
int operation_mode = DEFAULT_OPERATION_MODE;
bool upcase = DEFAULT_UPCASE;
bool rtscts = DEFAULT_RTSCTS;
bool tildes = DEFAULT_TILDES;
unsigned dot_offset = DEFAULT_DOTPOS; // 0 for raw, 6 for KC-85, 8 for WP-2
uint8_t model = DEFAULT_MODEL;
int baud = DEFAULT_BAUD;
int BASIC_byte_us = DEFAULT_BASIC_BYTE_MS*1000;
char client_tty_name[PATH_MAX+1] = {0x00};
char disk_img_fname[PATH_MAX+1] = {0x00};
char app_lib_dir[PATH_MAX+1] = APP_LIB_DIR;
char share_path[2][PATH_MAX+1] = {{0},{0}};
char dme_root_label[7] = TSDOS_ROOT_LABEL;
char dme_parent_label[7] = TSDOS_PARENT_LABEL;
char dme_dir_label[3] = TSDOS_DIR_LABEL;
char default_attr = DEFAULT_ATTR;
#if defined(USE_XATTR)
char* xattr_name = XATTR_PREFIX XATTR_NAME XATTR_SUFFIX;
#endif
bool enable_magic_files = true;
#if !defined(_WIN)
bool getty_mode = false;
#endif
char** args;
int f_open_mode = F_OPEN_NONE;
int client_tty_fd = -1;
int disk_img_fd = -1;
struct termios client_termios;
int o_file_h = -1;
uint8_t gb[TPDD_MSG_MAX];
char iwd[PATH_MAX+1] = {0x00};
char cwd[PATH_MAX+1] = {0x00};
char dme_cwd[7] = DEFAULT_DME_ROOT_LABEL;
char bootstrap_fname[PATH_MAX+1] = {0x00};
uint8_t dme = 0;
uint8_t bank = 0;
bool dme_disabled = false;
uint8_t ch[2] = {0xFF}; // 0x00 is a valid Operation-mode command, so init to 0xFF
uint8_t rb[SECTOR_LEN] = {0x00}; // pdd1 disk image record buffer
FILE_ENTRY* cur_file;
int dir_depth=0;
uint8_t pdd1_condition = PDD1_COND_NONE; // pdd1 condition bit flags
uint8_t pdd2_condition = PDD2_COND_NONE; // pdd2 condition bit flags
// drive cpu memory map
uint8_t ioport[IOPORT_LEN] = {0x00}; // i/o port
uint8_t cpuram[CPURAM_LEN] = {0x00}; // 128 bytes cpu internal ram
uint8_t ga[GA_LEN] = {0x00}; // gate array interface
uint8_t ram[RAM_LEN] = {0x00}; // 2k ram (pdd2 disk image record buffer)
uint8_t rom[ROM_LEN] = {0x00}; // 4k cpu internal mask rom
void show_main_help();
/* primitives and utilities */
// dbg(verbosity_threshold, printf_format, args...)
// dbg(3,"err %02X",err); // means only show this message if debug>=3
void dbg( const int v, const char* format, ... ) {
if (debug<v) return;
va_list args;
va_start( args, format );
vfprintf( stderr, format, args );
fflush(stderr);
va_end( args );
}
// dbg_b(verbosity_threshold, buffer, len)
// dbg_b(3, b, 24); // like dbg() except
// print n bytes of b[] as hex pairs and a trailing newline
// if n<0, then use TPDD_MSG_MAX
void dbg_b(const int v, unsigned char* b, int n) {
if (debug<v) return;
unsigned i;
if (n<0) n = TPDD_MSG_MAX;
for (i=0;i<n;i++) fprintf (stderr,"%02X ",b[i]);
fprintf (stderr, "\n");
fflush(stderr);
}
// like dbg_b, except assume b[] is an Operation-mode req or ret block
// and parse it to display the parts: cmd, len, payload, checksum.
void dbg_p(const int v, unsigned char* b) {
dbg(v,"cmd: %1$02X\nlen: %2$02X (%2$u)\nchk: %3$02X\ndat: ",b[0],b[1],b[b[1]+2]);
dbg_b(v,b+2,b[1]);
}
/** xattr **************************************************/
void dl_getxattr(const char* path, uint8_t* value) {
#if defined(USE_XATTR)
# if defined(__linux__)
getxattr(path, xattr_name, value, 1);
# elif defined(__APPLE__)
getxattr(path, xattr_name, value, 1, 0, 0);
# elif defined(__FreeBSD__)
extattr_get_file(path, EXTATTR_NAMESPACE_USER, xattr_name, value, 1);
# endif
#endif
}
void dl_fgetxattr(int fd, uint8_t* value) {
#if defined(USE_XATTR)
# if defined(__linux__)
fgetxattr(fd, xattr_name, value, 1);
# elif defined(__APPLE__)
fgetxattr(fd, xattr_name, value, 1, 0, 0);
# elif defined(__FreeBSD__)
extattr_get_fd(fd, EXTATTR_NAMESPACE_USER, xattr_name, value, 1);
# endif
#endif
}
void dl_fsetxattr(int fd, const uint8_t* value) {
#if defined(USE_XATTR)
# if defined(__linux__)
fsetxattr(fd, xattr_name, value, 1, 0);
# elif defined(__APPLE__)
fsetxattr(fd, xattr_name, value, 1, 0, 0);
# elif defined(__FreeBSD__)
extattr_set_fd(fd, EXTATTR_NAMESPACE_USER, xattr_name, value, 1);
# endif
#endif
}
/***********************************************************/
// string-to-bool
bool stobool (const char* s) {
return (
atoi(s)>0
|| !strcasecmp(s,"true")
|| !strcasecmp(s,"on")
|| !strcasecmp(s,"yes")
|| !strcmp(s,":")
) ? true : false;
}
// int-to-rate - given int 9600 return macro B9600
int itor (int i) {
return
i==75?B75: // kc85 supports, drive does not
i==110?B110: // kc85 supports, drive does not
i==150?B150: // drive supports, kc85 does not
i==300?B300:
i==600?B600:
i==1200?B1200:
i==2400?B2400:
i==4800?B4800:
i==9600?B9600: // default Brother FB-100, KnitKing FDD19, Purple Computing D103
i==19200?B19200: // default TANDY 26-3808, TANDY 26-3814
i==38400?B38400:
#if defined(B76800) //#if defined(__sparc__) // ref/baud_linux.c
i==76800?B76800: // drive supports, local platform may
#endif
0;
}
// given 19200 return 9 (the # in "COM:#8N1ENN")
int baud_to_stat_code (int r) {
return
r==75?1: // kc85 supports, drive does not
r==110?2: // kc85 supports, drive does not
// r==150?0: // drive supports, kc85 does not
r==300?3:
r==600?4:
r==1200?5:
r==2400?6:
r==4800?7:
r==9600?8:
r==19200?9:
// b==76800?0: // drive supports, kc85 does not
0;
}
void update_cwd () {
memset(cwd,0x00,PATH_MAX);
(void)!getcwd(cwd,PATH_MAX);
// if the current directory is not writable, set the write-protected disk flag
uint8_t wp = 0;
if (access(cwd,W_OK|X_OK)) wp = 1;
pdd1_condition |= wp << PDD1_COND_BIT_WPROT;
pdd2_condition |= wp << PDD2_COND_BIT_WPROT;
}
void add_share_path (char* s) {
dbg(3,"%s(%s)\n",__func__,s);
if (!share_path[0][0]) { strcpy(share_path[0],s); return; }
if (!share_path[1][0]) { strcpy(share_path[1],s); return; }
dbg(2,"Discarded excess share path \"%s\"\n",s);
}
void cd_share_path () {
if (!share_path[bank][0]) return;
if (!strncmp(cwd,share_path[bank],PATH_MAX)) return;
if (chdir(share_path[bank])) dbg(0,"FAILED CD TO \"%s\"\n",share_path[bank]);
update_cwd();
}
// maybe rewrite f[] with /path/to/f
void find_lib_file (char* f) {
if (f[0]==0x00) return;
char t[PATH_MAX+1]={0x00};
// rewrite ~/foo to $HOME/foo
if (f[0]=='~' && f[1]=='/') {
strcpy(t,f);
memset(f,0x00,PATH_MAX);
strcpy(f,getenv("HOME"));
strcat(f,t+1);
}
if (f[0]=='/') return; // don't rewrite any absolute path
if (f[0]=='.' && f[1]=='/') return; // don't rewrite explicit relative path
if (f[0]=='.' && f[1]=='.' && f[2]=='/') return; // don't rewrite explicit relative path
if (!access(f,F_OK)) return; // if pathless filename exists & accessible, use it as-is
// none of above matched, look in app_lib_dir
memset(t,0x00,PATH_MAX);
strcpy(t,app_lib_dir);
strcat(t,"/");
strcat(t,f);
// if found in app_lib_dir then rewrite with that path
if (!access(t,F_OK)) {
memset(f,0x00,PATH_MAX);
strcpy(f,t);
}
// else leave f[] as it was, some consumers create the file if not exist
}
int check_disk_image () {
// if they didn't ask for any disk image, then bail without error
if (!disk_img_fname[0]) return 0;
dbg(3,"looking for disk image \"%s\"\n",disk_img_fname);
find_lib_file(disk_img_fname);
// disk_img_fname has now been re-written if and as necessary,
// and still may or may not exist
struct stat info;
if (!stat(disk_img_fname, &info) && info.st_size>0) {
// if file exists and >0 bytes
dbg(1,"Loading disk image file \"%s\"\n",disk_img_fname);
// use file size to automatically set model 1 vs 2 or reject file
if (info.st_size==PDD1_IMG_LEN) model = 1;
if (info.st_size==PDD2_IMG_LEN) model = 2;
if (model==1 && info.st_size != PDD1_IMG_LEN) {
dbg(0,"%d bytes, expected %u bytes for TPDD1\n",info.st_size,PDD1_IMG_LEN);
return 1;
}
if (model==2 && info.st_size != PDD2_IMG_LEN) {
dbg(0,"%d bytes, expected %u bytes for TPDD2\n",info.st_size,PDD2_IMG_LEN);
return 1;
}
} else {
// if file doesn't exist or is 0 bytes
dbg(1,"Disk image file \"%s\" is empty or does not exist.\nIt will be created if the client issues a format command.\n",disk_img_fname);
// use file name to automatically set model 1 vs 2
char ext[6] = {0};
strncpy(ext,disk_img_fname+strlen(disk_img_fname)-5,5);
if (!strcasecmp(ext,DEFAULT_TPDD1_IMG_SUFFIX)) model = 1;
else if (!strcasecmp(ext,DEFAULT_TPDD2_IMG_SUFFIX)) model = 2;
}
// rewrite with leading path if not already
// because we we may cd all over the place
if (disk_img_fname[0]=='/') return 0;
char t[PATH_MAX+1] = {0};
strcpy(t,iwd);
strcat(t,"/");
strcat(t,disk_img_fname);
memcpy(disk_img_fname,t,PATH_MAX+1);
return 0;
}
// search for TTY(s) matching TTY_PREFIX
void find_ttys (char* f) {
dbg(3,"%s(%s)\n",__func__,f);
// open /dev
char path[] = "/dev/";
DIR* dir = opendir(path);
if (!dir){dbg(0,"Cannot open \"%s\"\n",path); return;}
// read /dev, look for all files beginning with prefix
// add any matches to ttys[]
char** ttys = malloc(sizeof(char*));
struct dirent *files;
uint16_t nttys = 0, l=strlen(f);
#if defined(__FreeBSD__)
char* p;
#endif
dbg(2,"Searching for \"%s%s*\"\n",path,f);
while ((files = readdir(dir))) {
if (strncmp(files->d_name,f,l)) continue;
#if defined(__FreeBSD__)
p = strrchr(files->d_name,'.');
if (p!=NULL) if (!strcmp(p,".init") || !strcmp(p,".lock")) continue;
#endif
nttys++;
ttys = realloc(ttys, (nttys+1) * sizeof(char(*)));
ttys[nttys] = files->d_name;
}
closedir(dir);
int i=0;
if (nttys==1) i=1; // if there is only one element in ttys[], use it
if (nttys>1) while (!i) { // if more than 1 then menu
dbg(0,"\n");
for (i=1;i<=nttys;i++) dbg(0,"%d) %s\n",i,ttys[i]);
i=0; char a[6]={0};
dbg(0,"Which serial port is the TPDD client on (1-%d or q) ? ",nttys);
if (fgets(a,sizeof(a),stdin)) i=atoi(a);
if (i<1 || i>nttys) i=0;
dbg(0,"\n");
if (a[0]=='q'||a[0]=='Q') break;
}
// set client_tty_name[] with the final result
client_tty_name[0]=0x00;
if (i) {
strcpy(client_tty_name,path);
strcat(client_tty_name,ttys[i]);
}
free(ttys);
}
// take the user-supplied tty arg and figure out the actual /dev/ttyfoo
void resolve_client_tty_name () {
dbg(3,"%s()\n",__func__);
switch (client_tty_name[0]) {
case 0x00:
// nothing supplied, scan for any ttys matching the default prefix
find_ttys(TTY_PREFIX);
break;
case '-':
// stdin/stdout mode, silence all messages - untested
debug = -1;
strcpy (client_tty_name,"/dev/tty");
client_tty_fd=1;
break;
default:
// something given, try with and without prepending /dev/
if (!access(client_tty_name,F_OK)) break;
char t[PATH_MAX+1]={0x00};
int i = 0;
strcpy(t,client_tty_name);
strcpy(client_tty_name,"/dev/");
if (!strncmp(client_tty_name,t,5)) i=5;
strcat(client_tty_name,t+i);
}
}
// set termios VMIN & VTIME
void client_tty_vmt(int m,int t) {
if (m<-1 || t<-1) tcgetattr(client_tty_fd,&client_termios);
if (m<0) m = C_CC_VMIN;
if (t<0) t = C_CC_VTIME;
if (client_termios.c_cc[VMIN] == m && client_termios.c_cc[VTIME] == t) return;
client_termios.c_cc[VMIN] = m;
client_termios.c_cc[VTIME] = t;
tcsetattr(client_tty_fd,TCSANOW,&client_termios);
}
int open_client_tty () {
dbg(3,"%s()\n",__func__);
if (!client_tty_name[0]) {
show_main_help();
dbg(0,"Error: No serial device specified\n(searched: /dev/%s*)\n",TTY_PREFIX);
return 1;
}
dbg(0,"Opening \"%s\" ... ",client_tty_name);
// open with O_NONBLOCK to avoid hang if client not ready, then unset later.
if (client_tty_fd<0) client_tty_fd=open((char *)client_tty_name,O_RDWR|O_NOCTTY|O_NONBLOCK);
if (client_tty_fd<0) { dbg(0,"%s\n",strerror(errno)); return 1; }
dbg(0,"OK\n");
#ifdef TIOCEXCL
ioctl(client_tty_fd,TIOCEXCL);
#endif
#if !defined(_WIN)
if (getty_mode) {
debug = -1;
if (!login_tty(client_tty_fd)) client_tty_fd = STDIN_FILENO;
else (void)!daemon(1,1);
}
#endif
(void)!tcflush(client_tty_fd, TCIOFLUSH);
// unset O_NONBLOCK
fcntl(client_tty_fd, F_SETFL, fcntl(client_tty_fd, F_GETFL, NULL) & ~O_NONBLOCK);
if (tcgetattr(client_tty_fd,&client_termios)==-1) return 21;
cfmakeraw(&client_termios);
client_termios.c_cflag |= CLOCAL|CS8;
if (rtscts) client_termios.c_cflag |= CRTSCTS;
else client_termios.c_cflag &= ~CRTSCTS;
if (cfsetspeed(&client_termios,itor(baud))==-1) return 22;
if (tcsetattr(client_tty_fd,TCSANOW,&client_termios)==-1) return 23;
client_tty_vmt(-2,-2);
return 0;
}
int write_client_tty(void* b, int n) {
dbg(4,"%s(%u)\n",__func__,n);
n = write(client_tty_fd,b,n);
dbg(3,"SENT: "); dbg_b(3,b,n);
return n;
}
// It is correct that this blocks and waits forever.
// The one time we don't want to block, we don't use this.
int read_client_tty(void* b, const unsigned int n) {
dbg(4,"%s(%u)\n",__func__,n);
unsigned t = 0;
int i = 0;
while (t<n) if ((i = read(client_tty_fd, b+t, n-t))) t+=i;
if (i<0) {
dbg(0,"error: %s\n",strerror(errno));
exit(EXIT_FAILURE);
}
dbg(3,"RCVD: "); dbg_b(3,b,n);
return t;
}
// cat a file to terminal, for custom loader directions in bootstrap()
void dcat(char* f) {
char b[4097]={0x00};
int h=open(f,O_RDONLY);
if (h<0) return;
while (read(h,&b,4096)>0) dbg(0,"%s",b);
close(h);
}
/*
* The manual says:
*
* "The checksum is the one's complement of the least significant byte
* of the number of bytes from the block format through the data block."
*
* But the bytes are summed, not just counted!
* Replace "number of" with "sum of the".
*
* Sum all the bytes in the specified range.
* Take the least significant byte of that sum.
* Invert all the bits in that byte.
*
* b[0] = cmd (block format)
* b[1] = len
* b[2] to b[1+len] = 0 to 128 bytes of payload (data block)
* ignore everything after b[1+len]
*/
uint8_t checksum(unsigned char* b) {
uint16_t s=0; uint8_t i, l=2+b[1];
for (i=0;i<l;i++) s+=b[i];
return ~(s&0xFF);
}
char* collapse_padded_fname(char* fname) {
dbg(3,"%s(\"%s\")\n",__func__,fname);
if (!dot_offset) return fname;
int i;
for (i=dot_offset;i>1;i--) if (fname[i-1]!=' ') break;
if (fname[dot_offset+1]==dme_dir_label[0] && fname[dot_offset+2]==dme_dir_label[1]) {
fname[i]=0x00;
} else {
fname[i]=fname[dot_offset];
fname[i+1]=fname[dot_offset+1];
fname[i+2]=fname[dot_offset+2];
fname[i+3]=0x00;
}
return fname;
}
void lsx (char* path,char* match,char* fmt) {
struct dirent *files;
DIR *dir = opendir(path);
if (!dir){dbg(0,"Cannot open \"%s\"",path); return;}
int i;
while ((files = readdir(dir))) {
for (i=strlen(files->d_name);files->d_name[i]!='.';i--);
if (!strcmp(files->d_name+i+1,match)) dbg(0,fmt,files->d_name);
}
closedir(dir);
}
int check_magic_file(char* b) {
dbg(3,"%s(\"%s\")\n",__func__,b);
if (!enable_magic_files) return 1;
int l = sizeof(magic_files)/sizeof(magic_files[0]);
for (int i=0;i<l;++i) if (!strcmp(magic_files[i],b)) return 0;
return 1;
}
// This is kind of silly but why not. Load a rom image file into rom[],
// then tpdd2 mem_read() in the ROM address range returns data from rom[].
void load_rom(char* f) {
dbg(3,"%s(%s)\n",__func__,f);
char t[PATH_MAX+1] = {0x00};
strncpy(t,f,PATH_MAX);
find_lib_file(t);
int h = open(t,O_RDONLY);
if (h<0) return;
(void)!read(h,rom,ROM_LEN);
close(h);
dbg_b(3,rom,ROM_LEN);
}
////////////////////////////////////////////////////////////////////////
//
// FDC MODE
//
/*
* sectors: 0-79
* sector: 1293 bytes
* | LSC 1 byte | ID 12 bytes | DATA 1280 bytes |
* LSC: logical sector size code
* ID: 12 bytes of arbitrary data, searchable by req_fdc_search_id()
* DATA: 1280 bytes of arbitrary data, read/writable in lsc_to_len(LSC)-sized chunks
*/
// standard fdc-mode 8-byte response
// e = error code ERR_FDC_* -> ascii hex pair
// s = status or data -> ascii hex pair
// l = length or address -> 2 ascii hex pairs
// TODO - don't assume endianness
void ret_fdc_std(uint8_t e, uint8_t s, uint16_t l) {
dbg(2,"%s()\n",__func__);
char b[9] = { 0x00 };
snprintf(b,9,"%02X%02X%04X",e,s,l);
dbg(2,"FDC: response: \"%s\"\n",b);
write_client_tty(b,8);
}
// p : physical sector to seek to
// m : mode read-only / write-only / read-write
int open_disk_image (int p, int m) {
dbg(2,"%s(%d,%d)\n",__func__,p,m);
int of; int e=ERR_FDC_SUCCESS;
if (!*disk_img_fname) e=ERR_FDC_NO_DISK;
if (!e) switch (m) {
case O_RDWR: of=O_RDWR; dbg(2,"edit rw\n");
if (access(disk_img_fname,W_OK)) e=ERR_FDC_WRITE_PROTECT;
break;
case O_WRONLY: of=O_WRONLY;
if (access(disk_img_fname,F_OK)) { of|=O_CREAT; dbg(2,"create\n");} else {
dbg(2,"edit wo\n");
if (access(disk_img_fname,W_OK)) e=ERR_FDC_WRITE_PROTECT;
}
break;
default: of=O_RDONLY; dbg(2,"read\n"); break;
}
if (!e) {
disk_img_fd=open(disk_img_fname,of|O_EXCL,0666);
if (disk_img_fd<0) { dbg(0,"%s\n",strerror(errno)) ;e=ERR_FDC_READ;}
}
if (!e) {
int s = (p*SECTOR_LEN); // initial seek position to start of physical sector
if (lseek(disk_img_fd,s,SEEK_SET)!=s) e=ERR_FDC_READ;
}
if (operation_mode) switch (e) {
//case ERR_FDC_SUCCESS: e=ERR_SUCCESS; break; // same
case ERR_FDC_NO_DISK: e=ERR_NO_DISK; break;
case ERR_FDC_WRITE_PROTECT: e=ERR_WRITE_PROTECT; break;
case ERR_FDC_READ: e=ERR_READ_TIMEOUT; break;
}
return e;
}
void req_fdc_set_mode(int m) {
dbg(2,"%s(%d)\n",__func__,m);
operation_mode = m; // no response, just switch modes
if (m==MODE_OPR) dbg(2,"Switched to \"Operation\" mode\n");
}
// disk state
// ret_fdc_std(e,s,l)
// e = ERR_FDC_SUCCESS
// s =
// bit 7 = disk not inserted
// bit 6 = disk changed
// bit 5 = disk write-protected
// 0-4 not used
// l = 0
void req_fdc_condition() {
dbg(2,"%s()\n",__func__);
ret_fdc_std(ERR_FDC_SUCCESS,pdd1_condition,0);
}
// lc = logical sector size code
void req_fdc_format(uint8_t lc) {
dbg(2,"%s(%d)\n",__func__,lc);
uint16_t ll = FDC_LOGICAL_SECTOR_SIZE[lc];
uint8_t rn = 0; // physical sector number
uint8_t rc = (PDD1_TRACKS*PDD1_SECTORS); // total record count
dbg(0,"Format: Logical sector size: %d = %d\n",lc,ll);
uint8_t e = open_disk_image(0,O_RDWR);
if (e) { ret_fdc_std(e,0,0); return; }
memset(rb,0x00,SECTOR_LEN);
rb[0]=lc; // logical sector size code
for (rn=0;rn<rc;rn++) {
if (write(disk_img_fd,rb,SECTOR_LEN)<0) {
dbg(0,"%s\n",strerror(errno));
e = ERR_FDC_READ;
break;
}
}
close(disk_img_fd);
if (!e) rn = 0;
ret_fdc_std(e,rn,0);
}
// read ID section of a sector
// p = physical sector number 0-79
void req_fdc_read_id(uint8_t p) {
dbg(2,"%s(%d)\n",__func__,p);
uint8_t e = open_disk_image(p,O_RDONLY);
if (e) { ret_fdc_std(e,0,0); return; }
int r = read(disk_img_fd,rb,SECTOR_HEADER_LEN);
close(disk_img_fd);
dbg_b(2,rb,SECTOR_HEADER_LEN);
if(r!=SECTOR_HEADER_LEN) {
ret_fdc_std(ERR_FDC_READ,p,0);
return;
}
uint16_t l = FDC_LOGICAL_SECTOR_SIZE[rb[0]]; // get logical size from header
ret_fdc_std(ERR_FDC_SUCCESS,p,l); // send OK
char t=0x00;
read_client_tty(&t,1); // read 1 byte from client
if (t==FDC_CMD_EOL) write_client_tty(rb+1,r-1); // if 0D send data else silently abort
}
// read DATA section of a sector
// tp = target physical sector 0-79
// tl = target logical sector 1-20
void req_fdc_read_sector(uint8_t tp,uint8_t tl) {
dbg(2,"%s(%d,%d)\n",__func__,tp,tl);
uint8_t e = open_disk_image(tp,O_RDONLY);
if (e) { ret_fdc_std(e,0,0); return; }
if (read(disk_img_fd,rb,SECTOR_HEADER_LEN)!=SECTOR_HEADER_LEN) { // read header
dbg(1,"failed read header\n");
close(disk_img_fd);
ret_fdc_std(ERR_FDC_READ,tp,0);
return;
}
dbg_b(3,rb,SECTOR_HEADER_LEN);
uint16_t l = FDC_LOGICAL_SECTOR_SIZE[rb[0]]; // get logical size from header
if (l*tl>SECTOR_DATA_LEN) {
close(disk_img_fd);
ret_fdc_std(ERR_FDC_LSN_HI,tp,l);
return;
}
// seek to target_physical*(id_len+physical_len) + id_len + (target_logical-1)*logical_len
int s = (tp*SECTOR_LEN)+SECTOR_HEADER_LEN+((tl-1)*l);
if (lseek(disk_img_fd,s,SEEK_SET)!=s) {
dbg(1,"failed seek %d : %s\n",s,strerror(errno));
close(disk_img_fd);
ret_fdc_std(ERR_FDC_READ,tp,0);
return;
}
memset(rb,0x00,l);
if (read(disk_img_fd,rb,l)!=l) { // read one logical sector of DATA
dbg(1,"failed logical sector read\n");
close(disk_img_fd);
ret_fdc_std(ERR_FDC_READ,tp,0);
return;
}
close(disk_img_fd);
ret_fdc_std(ERR_FDC_SUCCESS,tp,l); // 1st stage response
char t=0x00;
read_client_tty(&t,1); // read 1 byte from client
if (t==FDC_CMD_EOL) write_client_tty(rb,l); // if 0D send data else silently abort
}
// ref/search_id_section.txt
void req_fdc_search_id() {
dbg(2,"%s()\n",__func__);
int rn = 0; // physical sector number
int rc = (PDD1_TRACKS*PDD1_SECTORS); // total record count
char sb[SECTOR_ID_LEN] = {0x00}; // search data
uint8_t e = open_disk_image(0,O_RDONLY);
if (e) { ret_fdc_std(e,0,0); return; }
ret_fdc_std(ERR_FDC_SUCCESS,0,0); // tell client to send data
read_client_tty(sb,SECTOR_ID_LEN); // read 12 bytes from client
uint16_t l = 0;
bool found = false;
for (rn=0;rn<rc;rn++) {
memset(rb,0x00,SECTOR_HEADER_LEN);
if (read(disk_img_fd,rb,SECTOR_LEN)!=SECTOR_LEN) { // read one record
dbg(0,"%s\n",strerror(errno));
close(disk_img_fd);
ret_fdc_std(ERR_FDC_READ,rn,0);
return;
}
dbg(3,"%d ",rn);
dbg_b(3,rb,SECTOR_HEADER_LEN);
l = FDC_LOGICAL_SECTOR_SIZE[rb[0]]; // get logical size from header
// does sb exactly match ID?
if (!strncmp(sb,(char*)rb+1,SECTOR_ID_LEN)) {
found = true;
break;
}
}
close(disk_img_fd);
if (found) {
ret_fdc_std(ERR_FDC_SUCCESS,rn,l);
} else {
ret_fdc_std(ERR_FDC_ID_NOT_FOUND,255,l);
}
}
void req_fdc_write_id(int tp) {
dbg(2,"%s(%d)\n",__func__,tp);
uint8_t e = open_disk_image(tp,O_RDWR);
if (e) { ret_fdc_std(e,0,0); return; }
if (read(disk_img_fd,rb,1)!=1) { // read LSC
dbg(0,"failed to read LSC\n");
close(disk_img_fd);
ret_fdc_std(ERR_FDC_READ,tp,0);
return;
}
uint16_t l = FDC_LOGICAL_SECTOR_SIZE[rb[0]]; // get logical size from LSC
ret_fdc_std(ERR_FDC_SUCCESS,tp,l); // tell client to send data
read_client_tty(rb,SECTOR_ID_LEN); // read 12 bytes from client
// write those to the file
if (write(disk_img_fd,rb,SECTOR_ID_LEN)<0) {
dbg(0,"%s\n",strerror(errno));
e = ERR_FDC_READ;
l = 0;
}
close(disk_img_fd);
ret_fdc_std(e,tp,l); // send final response to client
}