/**
 * Copyright (C) 2020 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <dlfcn.h>
#include <fcntl.h>
#include <ipp.h>

#include "../includes/common.h"

int isInitialized = 0;
void *check_ptr = NULL;
size_t text_len = sizeof("text/plain") - 1;

static void *(*real_malloc)(size_t) = NULL;
static int (*real_strcmp)(const char *str1, const char *str2) = NULL;

void init(void) {
    real_malloc = (void *(*)(size_t))dlsym(RTLD_NEXT, "malloc");
    if (real_malloc == NULL) {
        return;
    }
    real_strcmp = (int (*)(const char *, const char *))dlsym(RTLD_NEXT, "strcmp");
    if (real_strcmp == NULL) {
        return;
    }
    isInitialized = 1;
}

void *malloc(size_t size) {
    if (!isInitialized) {
        init();
    }
    void *tmp = real_malloc(size);
    if (size == text_len) {
        check_ptr = tmp;
    }
    return tmp;
}

int strcmp(const char *str1, const char *str2) {
    if (!isInitialized) {
        init();
    }
    if ((str1 == check_ptr) && (str1[text_len - 1] != '\0')) {
        exit(EXIT_VULNERABLE);
    }
    return real_strcmp(str1, str2);
}

int main(int argc, char **argv) {
    if (argc < 2) {
        return EXIT_FAILURE;
    }

    int file_desc = open((const char *)argv[1], O_RDONLY);
    if (file_desc < 0) {
        return EXIT_FAILURE;
    }

    ipp_t *job = ippNew();
    if (!job) {
        return EXIT_FAILURE;
    }
    ippReadFile(file_desc, job);

    if (job) {
        free(job);
    }
    close(file_desc);
    return EXIT_SUCCESS;
}
