#include <sys/types.h>
#include <dirent.h>
#include <sys/time.h> 
#include <unistd.h>
#include <sys/stat.h>
#include <errno.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <sys/socket.h>

#define NODEFINE
#include <u.h>
#include <libc.h>
#include <fcall.h>
#include "fd.h"

int
pm_open(char *file, int mode)
{
	char *path;
	int ufd, umode;
	File *f;
	struct stat s;
	
	if(strcmp(file, "stdin$") == 0)
		return pm_dup(0, -1);
	if(strcmp(file, "stdout$") == 0)
		return pm_dup(1, -1);
	if(strcmp(file, "stderr$") == 0)
		return pm_dup(2, -1);
		
	umode = mode&3;
	if(mode&PM_OTRUNC)
		umode |= O_TRUNC;
		
//	rlock(&dotlock);
	if((ufd = open(file, mode)) < 0){
		pm_oserror();
//		runlock(&dotlock);
		return -1;
	}
	if(fstat(ufd, &s) < 0){
		close(ufd);
		pm_oserror();
//		runlock(&dotlock);
		return -1;
	}
	if((path = pm_openpath(file)) == nil){
		close(ufd);
//		runlock(&dotlock);
		return -1;
	}
//	runlock(&dotlock);
	if((f = pm_allocfile(ufd)) == nil){
		pm_free(path);
		close(ufd);
		return -1;
	}
	f->type = S_ISDIR(s.st_mode) ? Tdir : Tfile;
	f->ufd = ufd;
	f->path = path;
	pm_qunlock(&f->lk);
	return f->pmfd;
}


syntax highlighted by Code2HTML, v. 0.9.1