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
/* GATE PROJECT LICENSE:
+----------------------------------------------------------------------------+
| Copyright(c) 2018-2025, Stefan Meislinger                                  |
| All rights reserved.                                                       |
|                                                                            |
| Redistribution and use in source and binary forms, with or without         |
| modification, are permitted provided that the following conditions are met:|
|                                                                            |
| 1. Redistributions of source code must retain the above copyright notice,  |
|    this list of conditions and the following disclaimer.                   |
| 2. Redistributions in binary form must reproduce the above copyright       |
|    notice, this list of conditions and the following disclaimer in the     |
|    documentation and/or other materials provided with the distribution.    |
|                                                                            |
| THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"|
| AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE  |
| IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE |
| ARE DISCLAIMED.IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE    |
| LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR        |
| CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF       |
| SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS   |
| INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN    |
| CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)    |
| ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF     |
| THE POSSIBILITY OF SUCH DAMAGE.                                            |
+----------------------------------------------------------------------------+
*/

#include "gate/tech/filesystems.h"
#include "gate/results.h"

gate_result_t gate_filesystem_read_bootsector(gate_controlstream_t* blockstream, gate_filesystem_fat_bootsect_t* bootsect)
{
    gate_result_t ret;
    char buffer[512];
    gate_size_t received = 0;

    do
    {
        ret = gate_stream_seek(blockstream, 0, GATE_STREAM_SEEK_BEGIN, NULL);
        GATE_BREAK_IF_FAILED(ret);

        ret = gate_stream_read(blockstream, buffer, 512, &received);
        GATE_BREAK_IF_FAILED(ret);

        gate_mem_copy(bootsect, &buffer[0], 512);
    } while (0);

    return ret;
}

static unsigned get_total_clusters(gate_filesystem_fat_bootsect_t const* bootsect)
{
    return (unsigned)bootsect->bpb.total_sectors / (unsigned)bootsect->bpb.sectors_per_cluster;
}

static unsigned get_first_root_dir_sector(gate_filesystem_fat_bootsect_t const* bootsect)
{
    return (unsigned)bootsect->bpb.reserved_sectors + (unsigned)bootsect->bpb.sectors_per_fat * (unsigned)bootsect->bpb.number_of_fats;
}

static unsigned get_root_dir_sectors(gate_filesystem_fat_bootsect_t const* bootsect)
{
    return (bootsect->bpb.root_entries * 32 + (unsigned)bootsect->bpb.bytes_per_sector - 1)
        / (unsigned)bootsect->bpb.bytes_per_sector;
}

static unsigned get_total_data_sectors(gate_filesystem_fat_bootsect_t const* bootsect)
{
    unsigned const first_root_dir_sector = get_first_root_dir_sector(bootsect);
    unsigned const root_dir_sectors = get_root_dir_sectors(bootsect);
    return (unsigned)bootsect->bpb.total_sectors - first_root_dir_sector - root_dir_sectors;
}

static unsigned get_total_data_clusters(gate_filesystem_fat_bootsect_t const* bootsect)
{
    return get_total_data_sectors(bootsect) / (unsigned)bootsect->bpb.sectors_per_cluster;
}

static unsigned get_root_dir_sectors_count(gate_filesystem_fat_bootsect_t const* bootsect)
{
    unsigned const sector_size = bootsect->bpb.bytes_per_sector;
    return (bootsect->bpb.root_entries * 32 + sector_size - 1) / sector_size;
}

static unsigned get_data_cluster_sector(gate_filesystem_fat_bootsect_t const* bootsect, unsigned cluster_num)
{
    /* notice: our cluster_num starts with "0" (FAT clusters start with "2") */
    unsigned const root_dir_sectors = get_root_dir_sectors_count(bootsect);
    unsigned const first_data_cluster_sector = get_first_root_dir_sector(bootsect) + root_dir_sectors;
    return first_data_cluster_sector + cluster_num * (unsigned)bootsect->bpb.sectors_per_cluster;
}

static unsigned get_fat_type(gate_filesystem_fat_bootsect_t const* bootsect)
{
    gate_size_t total_clusters = bootsect->bpb.total_sectors / bootsect->bpb.sectors_per_cluster;

    if (total_clusters < 4085)
    {
        return 12;
    }
    else if (total_clusters < 65525)
    {
        return 16;
    }
    else
    {
        return 32;
    }
}

static gate_result_t read_sector(gate_controlstream_t* blockstream, gate_filesystem_fat_bootsect_t const* bootsect, unsigned sector, char* out_buffer)
{
    const gate_size_t sector_length = bootsect->bpb.bytes_per_sector;
    const gate_int64_t pos = (gate_int64_t)sector * (gate_int64_t)sector_length;
    gate_size_t length_returned;
    gate_result_t result = gate_stream_seek(blockstream, pos, GATE_STREAM_SEEK_BEGIN, NULL);
    if (GATE_SUCCEEDED(result))
    {
        result = gate_stream_read_block((gate_stream_t*)blockstream, out_buffer, sector_length, &length_returned);
    }
    return result;
}

gate_result_t gate_filesystem_read_fat_entries(gate_controlstream_t* blockstream, gate_filesystem_fat_bootsect_t const* bootsect,
    gate_uint16_t* fat_entries, gate_size_t fat_entries_capacity, gate_size_t* fat_entries_count)
{
    const unsigned fat_type = get_fat_type(bootsect);
    const unsigned fat_start = bootsect->bpb.reserved_sectors;
    const unsigned sector_len = bootsect->bpb.bytes_per_sector;
    char local_buffer[512 * 3];
    char* buffer = &local_buffer[0];
    const gate_size_t buffer_required_len = (gate_size_t)sector_len * 3u;
    unsigned ndx, pos;
    gate_size_t entry_counter = 0;
    gate_result_t ret = GATE_RESULT_FAILED;;


    if (sizeof(local_buffer) > buffer_required_len)
    {
        buffer = gate_mem_alloc(buffer_required_len);
        if (buffer == NULL)
        {
            return GATE_RESULT_OUTOFMEMORY;
        }
    }

    if (!fat_entries_count)
    {
        fat_entries_count = &entry_counter;
    }

    switch (fat_type)
    {
    case 12:
    {
        for (ndx = 0; (ndx < bootsect->bpb.sectors_per_fat) && (fat_entries_capacity > 0); ndx += 3)
        {
            ret = read_sector(blockstream, bootsect, fat_start + ndx, &buffer[0]);
            GATE_BREAK_IF_FAILED(ret);
            ret = read_sector(blockstream, bootsect, fat_start + ndx + 1, &buffer[sector_len]);
            GATE_BREAK_IF_FAILED(ret);
            ret = read_sector(blockstream, bootsect, fat_start + ndx + 2, &buffer[sector_len * 2]);
            GATE_BREAK_IF_FAILED(ret);

            for (pos = 0; (pos < 3 * sector_len) && (fat_entries_capacity > 0); pos += 3)
            {
                *fat_entries = (gate_uint16_t)buffer[pos] | ((gate_uint16_t)buffer[pos + 1] << 8);
                ++fat_entries;
                ++(*fat_entries_count);
                if (0 == --fat_entries_capacity)
                {
                    break;
                }

                *fat_entries = (((gate_uint16_t)buffer[pos + 1] >> 4) & 0x0f) | ((gate_uint16_t)buffer[pos + 2] << 4);
                ++fat_entries;
                ++(*fat_entries_count);
                --fat_entries_capacity;
            }
        }
        break;
    }
    case 16:
    case 32:
    default:
    {
        ret = GATE_RESULT_NOTSUPPORTED;
        break;
    }
    }

    if (buffer && (buffer != &local_buffer[0]))
    {
        gate_mem_dealloc(buffer);
    }
    return ret;
}

gate_result_t gate_filesystem_read_next_fat_entry(
    gate_controlstream_t* blockstream, gate_filesystem_fat_bootsect_t const* bootsect, gate_uint32_t fat_entry, gate_uint32_t* next_fat_entry)
{
    const unsigned fat_type = get_fat_type(bootsect);
    const unsigned fat_start = bootsect->bpb.reserved_sectors;
    const unsigned sector_len = bootsect->bpb.bytes_per_sector;
    unsigned cluster_pos;
    unsigned fat_offset;
    unsigned sector_num;
    unsigned sector_offset;
    unsigned char local_buffer[512 * 2];
    unsigned char* buffer = &local_buffer[0];
    const gate_size_t buffer_required_len = (gate_size_t)sector_len * 2u;
    unsigned next_cluster;
    gate_result_t ret = GATE_RESULT_FAILED;

    if (sizeof(local_buffer) > buffer_required_len)
    {
        buffer = (unsigned char*)gate_mem_alloc(buffer_required_len);
        if (buffer == NULL)
        {
            return GATE_RESULT_OUTOFMEMORY;
        }
    }

    switch (fat_type)
    {
    case 12:
    {
        cluster_pos = fat_entry;
        fat_offset = (cluster_pos / 2) * 3;
        sector_num = fat_offset / sector_len;
        sector_offset = fat_offset % sector_len;

        ret = read_sector(blockstream, bootsect, fat_start + sector_num, (char*)&buffer[0]);
        GATE_BREAK_IF_FAILED(ret);
        if (sector_offset >= sector_len - 2)
        {
            /* fat entry is on the boundary to the next sector */
            ret = read_sector(blockstream, bootsect, fat_start + sector_num, (char*)&buffer[sector_len]);
            GATE_BREAK_IF_FAILED(ret);
        }

        if ((cluster_pos & 1) == 0)
        {
            next_cluster = (gate_uint16_t)buffer[sector_offset] | (((gate_uint16_t)buffer[sector_offset + 1] & 0x0f) << 8);
        }
        else
        {
            next_cluster = (((gate_uint16_t)buffer[sector_offset + 1] >> 4) & 0x0f) | ((gate_uint16_t)buffer[sector_offset + 2] << 4);
        }

        if (next_cluster >= 0xff8)
        {
            ret = GATE_RESULT_ENDOFSTREAM;
            *next_fat_entry = 0;
        }
        else if (next_cluster == 0xff7)
        {
            ret = GATE_RESULT_INVALIDCONTENT;
        }
        else
        {
            *next_fat_entry = next_cluster;
            ret = GATE_RESULT_OK;
        }
        break;
    }
    case 16:
    case 32:
    default:
    {
        ret = GATE_RESULT_NOTSUPPORTED;
        break;
    }
    }

    if (buffer && (buffer != &local_buffer[0]))
    {
        gate_mem_dealloc(buffer);
    }
    return ret;
}



gate_result_t gate_filesystem_read_fat_cluster(gate_controlstream_t* blockstream, gate_filesystem_fat_bootsect_t const* bootsect,
    gate_uint32_t cluster, char* buffer, gate_size_t buffer_capacity, gate_size_t* buffer_filled)
{
    unsigned fat_type = get_fat_type(bootsect);
    unsigned total_clusters;
    unsigned sector_num;
    unsigned byte_count;
    gate_int64_t stream_offset;
    gate_result_t result;

    switch (fat_type)
    {
    case 12:
    {
        if (cluster < 2)
        {
            /* first FAT clusters has cluster-id 2 */
            return GATE_RESULT_INVALIDARG;
        }
        cluster -= 2;
        total_clusters = get_total_data_clusters(bootsect);
        if (cluster >= total_clusters)
        {
            return GATE_RESULT_OUTOFBOUNDS;
        }
        sector_num = get_data_cluster_sector(bootsect, (unsigned)cluster);
        stream_offset = (gate_int64_t)sector_num * (gate_int64_t)bootsect->bpb.bytes_per_sector;
        byte_count = (unsigned)bootsect->bpb.sectors_per_cluster * (unsigned)bootsect->bpb.bytes_per_sector;
        if (buffer_capacity > byte_count)
        {
            buffer_capacity = byte_count;
        }
        result = gate_stream_seek(blockstream, stream_offset, GATE_STREAM_SEEK_BEGIN, NULL);
        GATE_RETURN_IF_FAILED(result);
        return gate_stream_read_block((gate_stream_t*)blockstream, buffer, buffer_capacity, buffer_filled);
    }
    case 16:
    case 32:
    default:
        return GATE_RESULT_NOTSUPPORTED;
    }
}

static gate_result_t read_fat_dir(gate_controlstream_t* blockstream, gate_filesystem_fat_bootsect_t const* bootsect,
    unsigned start_sector, unsigned sectors_count, gate_filesystem_fat_direntry_callback_t callback, void* user_param)
{
    const unsigned sectorlen = bootsect->bpb.bytes_per_sector;
    const unsigned sectorentries = sectorlen / 32;

    gate_result_t result = GATE_RESULT_OK;
    unsigned ndx, ent;
    char buffer[4096];
    gate_filesystem_fat_direntry_t const* ptr_direntry;

    for (ndx = 0; ndx != sectors_count; ++ndx)
    {
        result = read_sector(blockstream, bootsect, start_sector + ndx, buffer);
        GATE_RETURN_IF_FAILED(result);
        ptr_direntry = (gate_filesystem_fat_direntry_t const*)buffer;

        for (ent = 0; ent != sectorentries; ++ent, ++ptr_direntry)
        {
            switch ((unsigned char)ptr_direntry->filename[0])
            {
            case 0:
                /* end of directory reached */
                return GATE_RESULT_OK;
            case 0xe5:
                /* unused_entry, skip */
                continue;
            default:
                if (ptr_direntry->attributes == 0x0f)
                {
                    /* long filename, skip */
                    continue;
                }

                /* standard entry: */
                if (!callback(ptr_direntry, user_param))
                {
                    /* canceled by callback */
                    return GATE_RESULT_CANCELED;
                }
                break;
            }
        }
    }
    return result;
}

gate_result_t gate_filesystem_read_fat_directory(gate_controlstream_t* blockstream, gate_filesystem_fat_bootsect_t const* bootsect,
    gate_string_t const* subdir, gate_filesystem_fat_direntry_callback_t callback, void* user_param)
{
    const unsigned root_sector = get_first_root_dir_sector(bootsect);
    const unsigned root_sectors_count = get_root_dir_sectors(bootsect);

    gate_result_t ret = read_fat_dir(blockstream, bootsect, root_sector, root_sectors_count, callback, user_param);
    if (ret == GATE_RESULT_CANCELED)
    {
        ret = GATE_RESULT_OK;
    }
    return ret;
}

struct find_fat_file_param
{
    char filename[8];
    char fileext[3];
    gate_filesystem_fat_direntry_t matched_entry;
};

static gate_bool_t find_fat_file_cb(gate_filesystem_fat_direntry_t const* entry, void* user_param)
{
    struct find_fat_file_param* param = (struct find_fat_file_param*)user_param;
    if ((0 == gate_mem_compare(entry->filename, param->filename, 8))
        && (0 == gate_mem_compare(entry->extension, param->fileext, 3)))
    {
        gate_mem_copy(&param->matched_entry, entry, sizeof(gate_filesystem_fat_direntry_t));
        return false;
    }
    return true;
}


gate_result_t gate_filesystem_find_fat_file(gate_controlstream_t* blockstream, gate_filesystem_fat_bootsect_t const* bootsect,
    gate_string_t const* path, gate_filesystem_fat_direntry_t* ptr_found_entry)
{
    gate_result_t ret;
    gate_size_t pos;
    gate_size_t len = gate_string_length(path);
    struct find_fat_file_param param;

    gate_mem_clear(&param, sizeof(param));
    gate_mem_fill(&param.filename[0], ' ', sizeof(param.filename));
    gate_mem_fill(&param.fileext[0], ' ', sizeof(param.fileext));
    pos = gate_string_char_pos_last(path, '.');
    if (pos == GATE_STR_NPOS)
    {
        pos = len > 8 ? 8 : len;
        gate_mem_copy(param.filename, gate_string_ptr(path, 0), pos);
    }
    else
    {
        gate_mem_copy(param.filename, gate_string_ptr(path, 0), pos > 8 ? 8 : pos);
        if (len - pos - 1 >= 3)
        {
            gate_mem_copy(param.fileext, gate_string_ptr(path, pos + 1), 3);
        }
        else
        {
            gate_mem_copy(param.fileext, gate_string_ptr(path, pos + 1), len - pos - 1);
        }
    }

    ret = gate_filesystem_read_fat_directory(blockstream, bootsect, NULL, &find_fat_file_cb, &param);
    if (GATE_SUCCEEDED(ret))
    {
        if (param.matched_entry.filename[0] != 0)
        {
            gate_mem_copy(ptr_found_entry, &param.matched_entry, sizeof(gate_filesystem_fat_direntry_t));
        }
        else
        {
            ret = GATE_RESULT_NOMATCH;
        }
    }
    return ret;
}