/* =============================================================================
 * 04_bounded_strings.c  --  string functions that know the buffer size
 * =============================================================================
 *
 * [Questions this demo answers]
 *   - The first defense against buffer overflows is in YOUR code: use library
 *     functions that are told how big the destination is. What do fgets,
 *     snprintf, strncpy and scanf("%7s") actually do when the input is too
 *     long?
 *   - How do you DETECT that an input was cut short, so the program can
 *     handle it instead of silently using half a line?
 *
 * [How to build & run]
 *   make && ./build/04_bounded_strings
 *
 * [How to read the output]
 *   Each part feeds inputs of growing length into an 8-byte buffer and shows
 *   the bytes that end up in it ('.' marks the terminating NUL, '_' a byte
 *   the function did not write). Every call stays inside the 8 bytes; the
 *   interesting part is what each function does at the limit.
 *
 * [Systems link / CS:APP 3.10.4]
 *   C strings carry no length, so every function that writes one needs the
 *   destination size from somewhere. Functions that do not take it (gets,
 *   strcpy, strcat, sprintf, scanf's plain %s) cannot be used safely on
 *   input you do not control. gets() was removed from the C language in C11.
 * -------------------------------------------------------------------------- */

#define _GNU_SOURCE          /* fmemopen on older glibc */
#include <stdio.h>
#include <string.h>

#define BUFSZ 8

/* [Idea] Print the BUFSZ bytes of buf as a legend:
 *     '.' = NUL terminator, '_' = never written (still the 0x7f fill),
 *     '~' = newline, else the character itself. */
static void show(const char *label, const char *buf)
{
    printf("    %-34s [", label);
    for (int k = 0; k < BUFSZ; k++) {
        unsigned char c = (unsigned char)buf[k];
        putchar(c == 0 ? '.' : c == 0x7f ? '_' : c == '\n' ? '~' :
                (c >= 32 && c < 127) ? c : '?');
    }
    printf("]\n");
}

static void part_a(void)
{
    printf("PART A: fgets(buf, 8, stream) -- reads at most 7 chars + NUL\n");
    const char *inputs[] = {"hi\n", "1234567\n", "123456789012\n"};
    for (int k = 0; k < 3; k++) {
        FILE *in = fmemopen((void *)inputs[k], strlen(inputs[k]), "r");
        char buf[BUFSZ];
        memset(buf, 0x7f, sizeof buf);
        fgets(buf, sizeof buf, in);
        int whole = strchr(buf, '\n') != NULL;          /* got the end of the line? */
        char label[64];
        snprintf(label, sizeof label, "input of %zu chars + newline:", strlen(inputs[k]) - 1);
        show(label, buf);
        if (!whole) {
            int c, dropped = 0;
            while ((c = fgetc(in)) != EOF && c != '\n')  /* drain the rest of the line */
                dropped++;
            printf("      no '\\n' in buf: the line was TOO LONG; %d more chars were left\n"
                   "      unread (here: drained), and the program can report an error\n", dropped);
        }
        fclose(in);
    }
    printf("\n");
}

static void part_b(void)
{
    printf("PART B: snprintf(buf, 8, \"user=%%s\", name) -- returns the length it WANTED\n");
    const char *names[] = {"al", "bob", "carol"};
    for (int k = 0; k < 3; k++) {
        char buf[BUFSZ];
        memset(buf, 0x7f, sizeof buf);
        int want = snprintf(buf, sizeof buf, "user=%s", names[k]);
        char label[64];
        snprintf(label, sizeof label, "name \"%s\" -> returned %d:", names[k], want);
        show(label, buf);
        if (want >= BUFSZ)
            printf("      returned %d >= 8: TRUNCATED (always NUL-terminated, though)\n", want);
    }
    printf("\n");
}

static void part_c(void)
{
    printf("PART C: strncpy(buf, src, 8) -- bounded, but a trap\n");
    const char *srcs[] = {"abc", "abcdefgh", "abcdefghijk"};
    for (int k = 0; k < 3; k++) {
        char buf[BUFSZ];
        memset(buf, 0x7f, sizeof buf);
        strncpy(buf, srcs[k], sizeof buf);
        char label[64];
        snprintf(label, sizeof label, "src \"%s\" (%zu chars):", srcs[k], strlen(srcs[k]));
        show(label, buf);
        if (memchr(buf, 0, sizeof buf) == NULL)
            printf("      no NUL anywhere: buf is NOT a valid string; strlen(buf) would read\n"
                   "      past its end. Write buf[7] = '\\0' yourself, or use snprintf.\n");
    }
    printf("    (and for short sources strncpy fills ALL remaining bytes with NULs)\n\n");
}

static void part_d(void)
{
    printf("PART D: sscanf(input, \"%%7s\", buf) -- a field width for %%s\n");
    const char *inputs[] = {"short", "muchtoolongword"};
    for (int k = 0; k < 2; k++) {
        char buf[BUFSZ];
        memset(buf, 0x7f, sizeof buf);
        int n = sscanf(inputs[k], "%7s", buf);
        char label[64];
        snprintf(label, sizeof label, "input \"%s\" (%d field):", inputs[k], n);
        show(label, buf);
    }
    printf("    Without the 7, %%s copies the whole word whatever its length.\n\n");
}

int main(void)
{
    printf("=== Demo 04: bounded string functions (8-byte buffer) ===\n");
    printf("  (in [....]:  '.' = NUL,  '_' = byte never written,  '~' = newline)\n\n");
    part_a();
    part_b();
    part_c();
    part_d();
    printf("Observations:\n");
    printf("  * Every function here was told the buffer size, and none wrote past it.\n");
    printf("  * Bounded is not the same as correct: fgets and snprintf TRUNCATE, and\n"
           "    the caller must check (no '\\n' / return value >= size) and decide.\n");
    printf("  * strncpy may leave the buffer without a terminating NUL; snprintf (or\n"
           "    strlcpy where available) always terminates.\n");
    printf("  * Rule: never call a string-writing function without the destination's\n"
           "    size, and never pass input you do not control to gets/strcpy/sprintf.\n");
    return 0;
}
