/*
 * Copyright (C) 2022 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 <stdbool.h>
#include <dlfcn.h>
#include <fcntl.h>
#include <ipp.h>
#include "../includes/common.h"

bool isInitialized = false;

bool isVulnerable = false;

bool isTestInProgress = false;

const char *kExposedLanguageString = "en-us";

static size_t (*realStrlen)(const char *str) = NULL;

void init() {
    realStrlen = (size_t(*)(const char *))dlsym(RTLD_NEXT, "strlen");
    if (realStrlen == NULL) {
        return;
    }
    isInitialized = true;
}

size_t strlen(const char *str) {
    if (!isInitialized) {
        init();
    }
    if (isTestInProgress && (strcmp(str, kExposedLanguageString) == 0)) {
        isVulnerable = true;
    }
    return realStrlen(str);
}

int main(int argc, char **argv) {
    FAIL_CHECK(argc > 1);
    int fileDescriptor = open((const char *)argv[1], O_RDONLY);
    FAIL_CHECK(fileDescriptor >= 0);
    ipp_t *job = ippNew();
    if (!job) {
        close(fileDescriptor);
        FAIL_CHECK(job != NULL);
    }
    isTestInProgress = true;
    ippReadFile(fileDescriptor, job);
    isTestInProgress = false;
    free(job);
    close(fileDescriptor);
    return (isVulnerable) ? EXIT_VULNERABLE : EXIT_SUCCESS;
}
