Beispiel #1
0
int pipe_exec_fg(char const **argv, int in, int out) {
	int pid;

	pid = fork();
	if (pid < 0) {

		ropen(0, fd_rp(in), STAT_READER);
		ropen(1, fd_rp(out), STAT_WRITER);

		if (execv(argv[0], argv)) {
			if (errno == ENOENT) {
				fprintf(stderr, "%s: %s: command not found\n", getname_s(), argv[0]);
			}
			else {
				perror(argv[0]);
			}
			
			abort();
		}
	}
	close(in);
	close(out);
	mwait(PORT_CHILD, pid);

	return 0;
}
Beispiel #2
0
static void
handle_copy(struct cfg *cf, struct rtpp_session *spa, int idx, char *rname)
{

    if (spa->rrcs[idx] == NULL) {
	spa->rrcs[idx] = ropen(cf, spa, rname, idx);
	rtpp_log_write(RTPP_LOG_INFO, spa->log,
	  "starting recording RTP session on port %d", spa->ports[idx]);
    }
    if (spa->rtcp->rrcs[idx] == NULL && cf->rrtcp != 0) {
	spa->rtcp->rrcs[idx] = ropen(cf, spa->rtcp, rname, idx);
	rtpp_log_write(RTPP_LOG_INFO, spa->log,
	  "starting recording RTCP session on port %d", spa->rtcp->ports[idx]);
    }
}
Beispiel #3
0
///////////////////////////////////////////////////////////////////////
// Class				:	CRenderer
// Method				:	getPhotonMap
// Description			:	Load a photon map
// Return Value			:
// Comments				:
CPhotonMap		*CRenderer::getPhotonMap(const char *name) {
    CFileResource	*map;
    char			fileName[OS_MAX_PATH_LENGTH];
    FILE			*in;

    assert(name != NULL);
    assert(frameFiles != NULL);

    // Check the cache to see if the file is in the memory
    if (frameFiles->find(name,map) == FALSE) {

        // Locate the file
        if (locateFile(fileName,name,texturePath)) {
            // Try to open the file
            in		=	ropen(fileName,"rb",filePhotonMap,TRUE);
        } else {
            in		=	NULL;
        }

        // Read it
        map		=	new CPhotonMap(name,in);
        frameFiles->insert(map->name,map);
    }

    return (CPhotonMap *) map;
}
Beispiel #4
0
static void logit(const char *filename, int addcwd)
{
	static int logfd = -1;
	char *p = getenv("DEPMAKER");
	char buf[1024];
	char buf2[1024];

	if (!p) return;

	if (logfd == -1) {
		int (*ropen)(const char *, int , int );
		ropen = dlsym((void *)-1, "open");
		logfd = ropen(p, O_WRONLY|O_CREAT|O_APPEND, 0644);
	}

	buf[0] = 0;
	if (addcwd && filename[0] != '/') {
		getcwd(buf2, sizeof(buf2));
		strlcat(buf,buf2,sizeof(buf));
		strlcat(buf,"/",sizeof(buf));
	}
	strlcat(buf, filename, sizeof(buf));
	strlcat(buf, "\n", sizeof(buf));
	write(logfd, buf, strlen(buf));
}
/*
 * Try to open a file for reading in the current
 * directory and all include paths
 */
int filelist_ropen(const stringsize_t *name)
{
	includePathscnt_t cnt0;
	stringsize_t namelen;
	stringsize_t inclen;
	int fdes;
	char *cbuf, *cpos;


	namelen = *name;
	if( (cbuf=(char*)malloc(includeMaxLen+namelen+1))==NULL ) {
		systemError(EM_OutOfMemory);
		return -1;
	}
	/* copy name to cbuf */
	memcpy( cbuf+includeMaxLen, (const char*)(name+1), namelen );
	/* terminate the string */
	*(cbuf+includeMaxLen+namelen) = '\0';

	if( (fdes=ropen(cbuf+includeMaxLen))!=-1 ) {
		free(cbuf);
		return fdes;
	}

	for( cnt0=0; cnt0<includePaths_count; ++cnt0 )
	{
		cpos= cbuf+includeMaxLen-(inclen=*(*(includePaths+cnt0)));
		memcpy( cpos, *(includePaths+cnt0)+1, inclen );
		if( (fdes=ropen(cpos))!=-1 )
		{
			break;
		}
	}

	free(cbuf);
	return fdes;
}
Beispiel #6
0
void *load_exec(const char *name) {
	int fd;
	uint64_t size;
	char *path;
	void *image;

	/* attempt to find requested file */
	if (name[0] == '/' || name[0] == '@') {
		path = strdup(name);
	}
	else {
		path = strvcat(getenv("PATH"), "/", name, NULL);
	}

	fd = ropen(-1, fs_find(path), STAT_READER);

	if (fd < 0 || !rp_type(fd_rp(fd), "file")) {
		/* file not found */
		return NULL;
	}
	else {
		/* read whole file into buffer */
		size = rp_size(fd_rp(fd));

		if (!size) {
			return NULL;
		}

		image = aalloc(size, PAGESZ);
		
		if (!image) {
			return NULL;
		}

		if (rp_read(fd_rp(fd), image, size, 0) != size) {
			free(image);
			close(fd);
			return NULL;
		}

		close(fd);
		return image;
	}
}
Beispiel #7
0
///////////////////////////////////////////////////////////////////////
// Class				:	CIrradianceCache
// Method				:	CIrradianceCache
// Description			:	Ctor
// Return Value			:
// Comments				:
CIrradianceCache::CIrradianceCache(const char *name,unsigned int f,FILE *in,const float *from,const float *to,const float *tondc) : CTexture3d(name,from,to,tondc,3,cacheChannels) {
	int	i;

	assert(dataSize == 7);
	assert(numChannels == 3);
	
	memory				=	new CMemStack;		// Where we allocate our memory from
	root				=	NULL;
	maxDepth			=	1;
	flags				=	f;
	osCreateMutex(mutex);

	// Are we reading from file ?
	if (flags & CACHE_READ) {
		if (in == NULL)	in	=	ropen(name,"rb",fileIrradianceCache);

		if (in != NULL) {
		
			// Read the samples
			fread(&maxDepth,	sizeof(int),1,in);
			root	=	readNode(in);

			// Close the file
			fclose(in);
		}
	}

	// Are we creating a fresh cache ?
	if (root == NULL) {
		vector	center,bmin,bmax;

		// Transform the bounding box to the world
		transformBound(bmin,bmax,to,CRenderer::worldBmin,CRenderer::worldBmax);

		root			=	(CCacheNode *) memory->alloc(sizeof(CCacheNode));
		for (i=0;i<8;i++)	root->children[i]	=	NULL;
		addvv(center,bmin,bmax);
		mulvf(center,0.5f);
		movvv(root->center,center);
		subvv(bmax,bmin);
		root->side		=	max(max(bmax[0],bmax[1]),bmax[2]);
		root->samples	=	NULL;
	}
}
Beispiel #8
0
/* this handles exec calls */
void _init(void)
{
	char buf[1024];
	int (*ropen)(const char *, int , int );
	int fd, i, len;

	if (realpath("/proc/self/exe", buf)) {
		logit(buf, 1);
	}

	ropen = dlsym((void *)-1, "open");

	fd = ropen("/proc/self/cmdline", O_RDONLY, 0);

	strcpy(buf,"COMMAND: ");
	len = read(fd, buf+9, sizeof(buf)-10);
	for (i=0;i<len;i++) if (buf[9+i] == 0) buf[9+i] = ' ';
	buf[9+len] = 0;
	logit(buf, 0);
}
Beispiel #9
0
///////////////////////////////////////////////////////////////////////
// Class				:	CIrradianceCache
// Method				:	~CIrradianceCache
// Description			:	Dtor
// Return Value			:
// Comments				:
CIrradianceCache::~CIrradianceCache() {

	osDeleteMutex(mutex);

	// Are we writing the file out ?
	if (flags & CACHE_WRITE) {
		if (name[0] != 0) {
			FILE	*out	=	ropen(name,"wb",fileIrradianceCache);

			if (out != NULL) {
			
				// Write the samples
				fwrite(&maxDepth,	sizeof(int),1,out);
				writeNode(out,root);

				fclose(out);
			}
		}
	}

	// Delete the memory pool
	delete memory;
}
void connectHandler(int socket) {
        struct packedHedderFormat packedHedder;
	int isAuthenticated = 0;
	char tkeyForTest[32];
	int i,n;
	int intrespons;
	int count = 0;
	container *attrkeys = NULL;

        #ifdef DEBUG_TIME
      		struct timeval start_time, end_time;
                struct timeval tot_start_time, tot_end_time;
                gettimeofday(&tot_start_time, NULL);
        #endif

	ionice_benice();

while ((i=recv(socket, &packedHedder, sizeof(struct packedHedderFormat),MSG_WAITALL)) > 0) {

	#ifdef DEBUG
	printf("size is: %i\nversion: %i\ncommand: %i\n",packedHedder.size,packedHedder.version,packedHedder.command);
	#endif
	packedHedder.size = packedHedder.size - sizeof(packedHedder);

	if (attrkeys == NULL) {
		attrkeys = ropen();
	}

	if (packedHedder.command == bbc_askToAuthenticate) {
		if ((i=recv(socket, tkeyForTest, sizeof(tkeyForTest),MSG_WAITALL)) == -1) {
        	    perror("Cant read tkeyForTest");
        	    exit(1);
        	}		
		if (1) {
			printf("authenticated\n");
			intrespons = bbc_authenticate_ok;

			bbdocument_init(NULL);

			isAuthenticated = 1;
		}
		else {
			printf("authenticate faild\n");
			intrespons = bbc_authenticate_feiled;

               	}

		if ((n=sendall(socket, &intrespons, sizeof(intrespons))) == -1) {
                               perror("Cant recv filerest");
                               exit(1);
               	}
			
		
	}
	else {
		if (!isAuthenticated) {
			printf("user not autentikated\n");
			exit(1);
		}


		if (packedHedder.command == bbc_docadd) {
			#ifdef DEBUG
			printf("bbc_docadd\n");
			#endif

			char *subname,*documenturi,*documenttype,*document,*acl_allow,*acl_denied,*title,*doctype;
			char *attributes;
			int dokument_size;
			unsigned int lastmodified;

			#ifdef DEBUG_TIME
                		gettimeofday(&start_time, NULL);
        		#endif

			//subname
			if ((i=recvall(socket, &intrespons, sizeof(intrespons))) == 0) {
                    		perror("Cant read intrespons");
                    		exit(1);
                	}
			subname = malloc(intrespons +1);
			if ((i=recvall(socket, subname, intrespons)) == 0) {
                                perror("Cant read subname");
                                exit(1);
                        }

			//documenturi
			if ((i=recvall(socket, &intrespons, sizeof(intrespons))) == 0) {
                    		perror("Cant read intrespons");
                    		exit(1);
                	}
			documenturi = malloc(intrespons +1);
			if ((i=recvall(socket, documenturi, intrespons)) == 0) {
                                perror("Cant read documenturi");
                                exit(1);
                        }

			//documenttype
			if ((i=recvall(socket, &intrespons, sizeof(intrespons))) == 0) {
                    		perror("Cant read intrespons");
                    		exit(1);
                	}
			documenttype = malloc(intrespons +1);
			if ((i=recvall(socket, documenttype, intrespons)) == 0) {
                                perror("Cant read documenttype");
                                exit(1);
                        }

			//document
			//dokument_size
			if ((i=recvall(socket, &dokument_size, sizeof(dokument_size))) == 0) {
                    		perror("Cant read dokument_size");
                    		exit(1);
                	}

			document = malloc(dokument_size +1);

			if (dokument_size == 0) {
				document[0] = '\0';
			}
			else {
				if ((i=recvall(socket, document, dokument_size)) == 0) {
                        	        fprintf(stderr,"Can't read document of size %i\n",dokument_size);
					perror("recvall");
                        	        exit(1);
                        	}
			}
			//lastmodified
			if ((i=recvall(socket, &lastmodified, sizeof(lastmodified))) == 0) {
                    		perror("Cant read lastmodified");
                    		exit(1);
                	}

			//acl_allow
			if ((i=recvall(socket, &intrespons, sizeof(intrespons))) == 0) {
                    		perror("Cant read intrespons");
                    		exit(1);
                	}
			acl_allow = malloc(intrespons +1);
			if ((i=recvall(socket, acl_allow, intrespons)) == 0) {
                                perror("Cant read acl_allow");
                                exit(1);
                        }

			//acl_denied
			if ((i=recvall(socket, &intrespons, sizeof(intrespons))) == 0) {
                    		perror("Cant read intrespons");
                    		exit(1);
                	}
			acl_denied = malloc(intrespons +1);
			if ((i=recvall(socket, acl_denied, intrespons)) == 0) {
                                perror("Cant read acl_denied");
                                exit(1);
                        }

			//title
			if ((i=recvall(socket, &intrespons, sizeof(intrespons))) == 0) {
                    		perror("Cant read intrespons");
                    		exit(1);
                	}
			title = malloc(intrespons +1);
			if ((i=recvall(socket, title, intrespons)) == 0) {
                                perror("Cant read title");
                                exit(1);
                        }

			//doctype
			if ((i=recvall(socket, &intrespons, sizeof(intrespons))) == 0) {
                    		perror("Cant read intrespons");
                    		exit(1);
                	}
			doctype = malloc(intrespons +1);
			if ((i=recvall(socket, doctype, intrespons)) == 0) {
                                perror("Cant read doctype");
                                exit(1);
                        }

			// Attribute list
			if ((i = recvall(socket, &intrespons, sizeof(intrespons))) == 0)
				err(1, "Can't receive attribute list len");
			attributes = malloc(intrespons +1);
			if ((i=recvall(socket, attributes, intrespons)) == 0)
				err(1, "Can't receive attribute list");

			#ifdef DEBUG_TIME
                		gettimeofday(&end_time, NULL);
                		printf("Time debug: bbdn_docadd recv data time: %f\n",getTimeDifference(&start_time, &end_time));
        		#endif

			printf("\n");
			printf("########################################################\n");
			printf("Url: %s\n",documenturi);
			printf("got subname \"%s\": title \"%s\". Nr %i, dokument_size %i attrib: %s\n",subname,title,count,dokument_size, attributes);
			printf("########################################################\n");
			printf("calling bbdocument_add():\n");
        		#ifdef DEBUG_TIME
        		        gettimeofday(&start_time, NULL);
		        #endif

			intrespons = bbdocument_add(subname,documenturi,documenttype,document,dokument_size,lastmodified,acl_allow,acl_denied,title,doctype, attributes, attrkeys);

			printf(":bbdocument_add end\n");
			printf("########################################################\n");

			#ifdef DEBUG_TIME
                		gettimeofday(&end_time, NULL);
                		printf("Time debug: bbdn_docadd runing bbdocument_add() time: %f\n",getTimeDifference(&start_time, &end_time));
        		#endif
			free(subname);
			free(documenturi);
			free(documenttype);
			free(document);
			free(acl_allow);
			free(acl_denied);
			free(title);
			free(doctype);
			free(attributes);

			// send status
	                if ((n=sendall(socket, &intrespons, sizeof(intrespons))) == -1) {
                               perror("Cant recv filerest");
                               exit(1);
	                }

		}
		else if (packedHedder.command == bbc_opencollection) {
			char *subname;
			char path[PATH_MAX];

			printf("open collection\n");

                        if ((i=recv(socket, &intrespons, sizeof(intrespons),MSG_WAITALL)) == -1)
                                err(1, "Cant read intrespons");
                        subname = malloc(intrespons +1);
                        if ((i=recv(socket, subname, intrespons,MSG_WAITALL)) == -1)
                                err(1, "Cant read subname");

			GetFilPathForLot(path, 1, subname);
			strcat(path, "fullyCrawled");

			unlink(path);

			free(subname);
		}
		else if (packedHedder.command == bbc_closecollection) {
			printf("closecollection\n");
			char *subname;
			//subname
                        if ((i=recv(socket, &intrespons, sizeof(intrespons),MSG_WAITALL)) == -1) {
                                perror("Cant read intrespons");
                                exit(1);
                        }
                        subname = malloc(intrespons +1);
                        if ((i=recv(socket, subname, intrespons,MSG_WAITALL)) == -1) {
                                perror("Cant read subname");
                                exit(1);
                        }

			bbdocument_close(attrkeys);
			attrkeys = NULL;

			//toDo må bruke subname, og C ikke perl her
			printf("cleanin lots start\n");
			char command[PATH_MAX];
			snprintf(command,sizeof(command),"perl %s -l -s \"%s\"",bfile("perl/cleanLots.pl"),subname);

			printf("running \"%s\"\n",command);
			intrespons = system(command);
			printf("cleanin lots end\n");

			// legger subnamet til listen over ventene subnavn, og huper searchd.
			lot_recache_collection(subname);


			/* We are done crawling  */
			{
				int fd = lotOpenFileNoCasheByLotNrl(1, "fullyCrawled", ">>", '\0', subname);

				if (fd == -1) {
					warn("Unable to write fullyCrawled file");
				} else {
					close(fd);
				}
			}

			free(subname);

                        if ((n=sendall(socket, &intrespons, sizeof(intrespons))) == -1) {
                                       perror("Cant recv filerest");
                                       exit(1);
                        }
			
		}
		else if (packedHedder.command == bbc_deleteuri) {
			printf("deleteuri\n");
			char *subname, *uri;
			//subname
                        if ((i=recv(socket, &intrespons, sizeof(intrespons),MSG_WAITALL)) == -1) {
                                perror("Cant read intrespons");
                                exit(1);
                        }
                        subname = malloc(intrespons +1);
                        if ((i=recv(socket, subname, intrespons,MSG_WAITALL)) == -1) {
                                perror("Cant read subname");
                                exit(1);
                        }
			subname[intrespons] = '\0';
                        if ((i=recv(socket, &intrespons, sizeof(intrespons),MSG_WAITALL)) == -1) {
                                perror("Cant read intrespons");
                                exit(1);
                        }
                        uri = malloc(intrespons +1);
                        if ((i=recv(socket, uri, intrespons,MSG_WAITALL)) == -1) {
                                perror("Cant read uri");
                                exit(1);
                        }
			uri[intrespons] = '\0';

			printf("going to delete: %s from %s\n", uri, subname);

			/* Add docid to the gced file */
			{
				FILE *fh;
				unsigned int DocID, lastmodified;
				unsigned int lotNr;
				int err = 0;

				if (uriindex_get(uri, &DocID, &lastmodified, subname) == 0) {
					fprintf(stderr,"Unable to get uri info. uri=\"%s\",subname=\"%s\".",uri,subname);
					perror("Unable to get uri info");
					err++;
				}
				if (!err) {
					lotNr = rLotForDOCid(DocID);

					if ((fh = lotOpenFileNoCasheByLotNr(lotNr,"gced","a", 'e',subname)) == NULL) {
						perror("can't open gced file");
						err++;
					} else {
						fwrite(&DocID, sizeof(DocID), 1, fh);
						fclose(fh);
					}
				}
				if (!err) {
					struct reformat *re;

					if((re = reopen(rLotForDOCid(DocID), sizeof(struct DocumentIndexFormat), "DocumentIndex", subname, RE_HAVE_4_BYTES_VERSION_PREFIX)) == NULL) {
						perror("can't reopen()");
						err++;
					} else {
						DIS_delete(RE_DocumentIndex(re, DocID));
						reclose(re);
					}
				}
				//markerer at den er skitten
				if (!err) {
					FILE *dirtfh;
					dirtfh = lotOpenFileNoCashe(DocID,"dirty","ab",'e',subname);
					fwrite("1",1,1,dirtfh);
					fclose(dirtfh);
				}
				if (err == 0) 
					bbdocument_delete(uri, subname);
			}
			free(subname);

			intrespons = 1; // Always return ok for now
                        if ((n=sendall(socket, &intrespons, sizeof(intrespons))) == -1) {
                                       perror("Cant recv filerest");
                                       exit(1);
                        }

		}
		else if (packedHedder.command == bbc_deletecollection) {
			printf("deletecollection\n");
			char *subname, *uri;
			//subname
                        if ((i=recv(socket, &intrespons, sizeof(intrespons),MSG_WAITALL)) == -1) {
                                perror("Cant read intrespons");
                                exit(1);
                        }
                        subname = malloc(intrespons +1);
                        if ((i=recv(socket, subname, intrespons,MSG_WAITALL)) == -1) {
                                perror("Cant read subname");
                                exit(1);
                        }
			subname[intrespons] = '\0';


			printf("going to delete collection: %s\n", subname);

			intrespons = bbdocument_deletecoll(subname);

			if ((n=sendall(socket, &intrespons, sizeof(intrespons))) == -1) {
                	               perror("Cant recv filerest");
        	                       exit(1);
	               	}


			free(subname);
		}
		else if (packedHedder.command == bbc_addwhisper) {
			whisper_t add;
			char *subname;

			if ((i=recv(socket, &intrespons, sizeof(intrespons),MSG_WAITALL)) == -1) 
				err(1, "Cant read intrespons");
			subname = malloc(intrespons+1);
			if ((i=recv(socket, subname, intrespons,MSG_WAITALL)) == -1) {
				perror("Cant read subname");
				exit(1);
			}
			subname[intrespons] = '\0';
			if ((i=recv(socket, &add, sizeof(add),MSG_WAITALL)) == -1) 
				err(1, "Cant read add whisper");

			gcwhisper_write(subname, add);
			free(subname);

		}
		else if (packedHedder.command == bbc_HasSufficientSpace) {

			char *subname;
			//subname
			if ((i=recvall(socket, &intrespons, sizeof(intrespons))) == 0) {
                    		perror("Cant read intrespons");
                    		exit(1);
                	}
			subname = malloc(intrespons +1);
			if ((i=recvall(socket, subname, intrespons)) == 0) {
                                perror("Cant read subname");
                                exit(1);
                        }

			// tester bare i lot 1 her. Må også sjekke andre loter når vi begynner å støtte frlere disker på ES.
			intrespons = lotHasSufficientSpace(1, 4096, subname);

			if ((n=sendall(socket, &intrespons, sizeof(intrespons))) == -1) {
                	               perror("Cant recv filerest");
        	                       exit(1);
	               	}

			printf("~Asked for HasSufficientSpace for subname \"%s\". Returnerer %d\n",subname, intrespons);

			free(subname);
		}
		else {
			printf("unnown comand. %i\n", packedHedder.command);
		}
	}

	++count;

//	#ifdef DEBUG_BREAK_AFTER
//	if (count >= DEBUG_BREAK_AFTER) {
//		printf("exeting after %i docoments\n",count);
//		exit(1);
//	}
//	#endif


}

        #ifdef DEBUG_TIME
                gettimeofday(&tot_end_time, NULL);
                printf("Time debug: bbdn total time time: %f\n",getTimeDifference(&tot_start_time, &tot_end_time));
        #endif

}
Beispiel #11
0
///////////////////////////////////////////////////////////////////////
// Class				:	CRenderer
// Method				:	getCache
// Description			:	Load a cache
// Return Value			:
// Comments				:
CTexture3d		*CRenderer::getCache(const char *name,const char *mode,const float *from,const float *to) {
    CFileResource	*cache;

    assert(name != NULL);
    assert(frameFiles != NULL);

    // Check the memory first
    if (frameFiles->find(name,cache) == FALSE) {
        char				fileName[OS_MAX_PATH_LENGTH];
        int					flags;
        char				type[128];
        int					createChannel = FALSE;

        // Process the file mode
        if (strcmp(mode,"r") == 0) {
            flags	=	CACHE_READ| CACHE_SAMPLE;
        } else if (strcmp(mode,"w") == 0) {
            flags	=	CACHE_WRITE | CACHE_SAMPLE;
        } else if (strcmp(mode,"R") == 0) {
            flags	=	CACHE_READ | CACHE_RDONLY;
        } else if (strcmp(mode,"rw") == 0) {
            flags	=	CACHE_READ | CACHE_WRITE | CACHE_SAMPLE;
        } else {
            flags	=	CACHE_SAMPLE;
        }

        // Try to read the file
        cache		=	NULL;
        if (flags & CACHE_READ) {

            // Locate the file
            if (locateFile(fileName,name,texturePath)) {
                FILE	*in	=	ropen(fileName,type);

                if (in != NULL) {
                    // If we're netrendering and writing, treat specially
                    if ((netClient != INVALID_SOCKET) && (flags & CACHE_WRITE)) {
                        flags			&=	~CACHE_WRITE;		// don't flush cache to disk
                        createChannel	=	TRUE;
                        if (strncmp(fileName,temporaryPath,strlen(temporaryPath)) == 0) {
                            // it's a temp file, delete it after we're done
                            registerFrameTemporary(fileName,TRUE);
                        }
                        // always remove the file mapping when writing
                        registerFrameTemporary(name,FALSE);
                    }

                    // Create the cache
                    if (strcmp(type,fileIrradianceCache) == 0) {
                        cache	=	new CIrradianceCache(name,flags,in,from,to,NULL);
                    } else {
                        error(CODE_BUG,"Unable to recognize the file format of \"%s\"\n",name);
                        fclose(in);
                    }
                }
            }
        }

        // If there is no cache, create it
        if (cache == NULL) {
            // If we're netrendering and writing, treat specially
            if ((netClient != INVALID_SOCKET) && (flags & CACHE_WRITE)) {
                flags			&=	~CACHE_WRITE;		// don't flush cache to
                createChannel	=	TRUE;
                // always remove the file mapping when writing
                registerFrameTemporary(name,FALSE);
            }

            // go ahead and create the cache
            cache	=	new CIrradianceCache(name,flags,NULL,from,to,CRenderer::toNDC);
        }

        // Create channels if possible
        if (createChannel == TRUE) {
            if (cache != NULL) {
                requestRemoteChannel(new CRemoteICacheChannel((CIrradianceCache *) cache));
            }
        }

        frameFiles->insert(cache->name,cache);
    }

    return (CTexture3d *) cache;
}
Beispiel #12
0
void
respond(Req *r, char *error)
{
	int i, m, n;
	char errbuf[ERRMAX];
	Srv *srv;

	srv = r->srv;
	assert(srv != nil);

	if(r->responded){
		assert(r->pool);
		goto free;
	}
		
	assert(r->responded == 0);
	r->error = error;

	switch(r->ifcall.type){
	default:
		assert(0);
	/*
	 * Flush is special.  If the handler says so, we return
	 * without further processing.  Respond will be called
	 * again once it is safe.
	 */
	case Tflush:
		if(rflush(r, error)<0)
			return;
		break;
	case Tversion:	rversion(r, error);	break;
	case Tauth:	rauth(r, error);	break;
	case Tattach:	rattach(r, error);	break;
	case Twalk:	rwalk(r, error);	break;
	case Topen:	ropen(r, error);	break;
	case Tcreate:	rcreate(r, error);	break;
	case Tread:	rread(r, error);	break;
	case Twrite:	rwrite(r, error);	break;
	case Tclunk:	rclunk(r, error);	break;
	case Tremove:	rremove(r, error, errbuf);	break;
	case Tstat:	rstat(r, error);	break;
	case Twstat:	rwstat(r, error);	break;
	}

	r->ofcall.tag = r->ifcall.tag;
	r->ofcall.type = r->ifcall.type+1;
	if(r->error)
		setfcallerror(&r->ofcall, r->error);

if(chatty9p)
	fprint(2, "-%d-> %F\n", srv->outfd, &r->ofcall);

	qlock(&srv->wlock);
	n = convS2M(&r->ofcall, srv->wbuf, srv->msize);
	if(n <= 0){
		fprint(2, "n = %d %F\n", n, &r->ofcall);
		abort();
	}
	assert(n > 2);
	/*
	 * There is a race here - we must remove the entry before
	 * the write, so that if the client is very fast and reuses the
	 * tag, the read loop won't think it is still in use.
	 * 
	 * By removing the entry before the write, we open up a 
	 * race with incoming Tflush messages.  Specifically, an
	 * incoming Tflush might not see r even though it has not
	 * yet been responded to.  It would then send an Rflush
	 * immediately, potentially before we do the write.  This can't
	 * happen because we already old srv->wlock, so nothing
	 * is going out on the wire before this write.
	 */
	if(r->pool)	/* not a fake */
		closereq(removereq(r->pool, r->ifcall.tag));

	qlock(&r->lk);
	r->responded = 1;
	if(r->pool)
	if(r->ref.ref == 1+r->nflush)
	if(r->fid){
		/*
		 * There are no references other than in our r->flush array,
		 * so no one else should be accessing r concurrently.
		 * Close the fid now, before responding to the message.
		 * 
		 * If the client is behaving (there are no outstanding T-messages
		 * that reference r->fid) and the message is a Tclunk or Tremove,
		 * then this closefid will call destroyfid.  
		 * 
		 * This means destroyfid can't piddle around 
		 * indefinitely (we're holding srv->wlock!), but it provides
		 * for tighter semantics as to when destroyfid is called.
		 *
		 * LANL has observed cases where waiting until after the write
		 * can delay a closefid on a Twrite for many 9P transactions,
		 * so that a handful of transactions can happen including a Tclunk
		 * and a Topen, and the original fid will still not be destroyed.
		 */
		closefid(r->fid);
		r->fid = nil;
	}
	qunlock(&r->lk);
	m = write(srv->outfd, srv->wbuf, n);
	if(m != n)
		sysfatal("lib9p srv: write %d returned %d on fd %d: %r", n, m, srv->outfd);
	qunlock(&srv->wlock);

free:
	qlock(&r->lk);	/* no one will add flushes now */

	for(i=0; i<r->nflush; i++){
		r->flush[i]->oldreq = nil;	/* so it doesn't try to lock us! */
		respond(r->flush[i], nil);
	}
	free(r->flush);
	r->flush = nil;
	r->nflush = 0;
	qunlock(&r->lk);

	if(r->pool)
		closereq(r);
	else
		free(r);
}
Beispiel #13
0
int
gcrepo(int LotNr, char *subname)
{
	int i;
	struct ReposetoryHeaderFormat ReposetoryHeader;

	char htmlbuffer[524288];
	char imagebuffer[524288];
	char *acl_allow;
	char *acl_deny;
	char *url, *attributes;
	unsigned long int raddress;
	char path[1024];
	char path2[1024];
	char path3[1024];
	FILE *FNREPO;
	struct reformat *re;

	int keept = 0;
	int gced = 0;

	container *attrkeys = ropen();


	if((re = reopen(LotNr, sizeof(struct DocumentIndexFormat), "DocumentIndex", subname, RE_HAVE_4_BYTES_VERSION_PREFIX|RE_COPYONCLOSE)) == NULL) {
		perror("reopen DocumentIndex");
		return 0;
	}


        if ( (FNREPO = lotOpenFileNoCasheByLotNr(LotNr,"reposetory","rb", 's',subname)) == NULL) {
		#ifdef DEBUG
                	printf("lot dont have a reposetory file\n");
		#endif
                return 0;
        }


	while (rGetNext_fh(LotNr,&ReposetoryHeader,htmlbuffer,sizeof(htmlbuffer),imagebuffer,&raddress,0,0,subname,&acl_allow,&acl_deny, FNREPO ,&url, &attributes)) {


		#ifdef DEBUG
		printf("dokument \"%s\", DocID %u.\n",
			RE_DocumentIndex(re,ReposetoryHeader.DocID)->Url,
			ReposetoryHeader.DocID);
		#endif

		//printf("%p\n", docindex.RepositoryPointer);
		if (raddress != RE_DocumentIndex(re,ReposetoryHeader.DocID)->RepositoryPointer) {
			#ifdef DEBUG
			printf("Garbage collecting %d at %u. docindex has %u\n", ReposetoryHeader.DocID, raddress,RE_DocumentIndex(re,ReposetoryHeader.DocID)->RepositoryPointer);
			#endif
			++gced;
		}
		else {
			unsigned long int offset;
			offset = rApendPost(&ReposetoryHeader, htmlbuffer, imagebuffer, subname, acl_allow, acl_deny, "repo.wip", url, attributes, attrkeys);
			RE_DocumentIndex(re,ReposetoryHeader.DocID)->RepositoryPointer = offset;
			#ifdef DEBUG
			printf("Writing DocID: %d\n", ReposetoryHeader.DocID);
			#endif
			++keept;

		}
	}
	fclose(FNREPO);

	//lokker filen repo.wip
	//lotCloseFiles();
	rclose(attrkeys);

	printf("keept %i\ngced %i\n",keept,gced);

	reclose(re);


	/* And we have a race... */
	GetFilPathForLot(path, LotNr, subname);
	strcpy(path2, path);
	strcpy(path3, path);
	strcat(path, "repo.wip");
	strcat(path2, "reposetory");
	rename(path, path2);
	strcpy(path, path3);
	strcat(path, "DocumentIndex.wip");
	strcat(path3, "DocumentIndex");
	rename(path, path3);

	#ifdef DI_FILE_CASHE
		closeDICache();
	#endif


	return 0;
}
int bbdocument_init(container **attrkeys) {

	DIR *dirp;
	FILE *filep;
	char buf[512];
	char path[512];
	struct dirent *dp;
	char lines[512];
	char **splitdata;
	int TokCount;
	struct fileFilterFormat *fileFilter = NULL;

	char fileFilterName[] = "fileFilter";
	perl_embed_init(NULL, 1);


	//chtbl_init(&htbl, PRIME_TBLSIZ, bbdocument_h, bbdocument_hmatch, free);
	h_fileFilter = create_hashtable(PRIME_TBLSIZ, bbdocument_h, bbdocument_hmatch);

	printf("opening %s\n",bfile(fileFilterName));
	if ((dirp = opendir(bfile(fileFilterName))) == NULL) {
		fprintf(stderr,"warn: cant open fileFilter \"%s\". Cant use fileFilters\n",bfile(fileFilterName));
		return 1;
	}  
	while ((dp = readdir(dirp)) != NULL) {
		if (dp->d_name[0] == '.') {
			continue;
		}
		sprintf(path,"%s/%s/",bfile(fileFilterName),dp->d_name);
		sprintf(buf,"%sruninfo",path);
		printf("%s\n",buf);
		if ((filep = fopen(buf,"r")) == NULL) {
			printf("no runinfo file for \"%s\"\n",dp->d_name);	
			continue;
		}
		
		printf("loading \"%s\"\n",dp->d_name);


		while ((!feof(filep)) && (fgets(lines,sizeof(lines) -1,filep) != NULL)) {
			

			//blanke linjer og komentarer som starter på #
			if ((lines[0] == '\n') || (lines[0] == '#')) {
				continue;
			}

			//void chomp(char string[])
			chomp(lines);

			//printf("line %s\n",lines);
			TokCount = split(lines, ": ", &splitdata);			
			//printf("\tfound %d token(s):\n", TokCount);

			/*
			if (TokCount != 2) {
				printf("bad config line \"%s\". Splitet in %i elements\n",lines,TokCount);
				continue;
			}
			*/

			if (strcmp(splitdata[0],"documentstype") == 0) {

				//legger til det gamle filteret
				if (fileFilter != NULL) {
					if (NULL != hashtable_search(h_fileFilter,fileFilter->documentstype )) {
						printf("####################### BUG ################################\n");
						printf("allredy have a filter for \"%s\"!\n",fileFilter->documentstype);
						printf("#######################/BUG ################################\n");
					}
					//add to hash
					printf("inserting %s\n",(*fileFilter).documentstype);
					//chtbl_insert(&htbl,(void *)fileFilter);
					if (!hashtable_insert(h_fileFilter,fileFilter->documentstype,fileFilter) ) {
                        		        printf("cant insert\n");
                		        	exit(-1);
		                        }

					printf("end inserting\n");
				}
				//begynner på et nytt filter

				fileFilter = malloc(sizeof(struct fileFilterFormat));
				fileFilter->attrwhitelist = NULL;

				//ikke alle filfiltere har sat alle opsjoner, så vi nulstiller alt, slik at det er lett og strcmp()'e
				//etter en verdi, uten at vi må tenke på at den kansje ikke er satt.
				memset(fileFilter,'\0',sizeof(struct fileFilterFormat));

				// default til FILTER_EXEOC
				fileFilter->filtertype = FILTER_EXEOC;

				strcpy((*fileFilter).documentstype,splitdata[1]);
				
				strlcpy(fileFilter->path, path, sizeof fileFilter->path);
				

			}
			else if (strcmp(splitdata[0],"command") == 0) {
				//vi kan ha : i komandoen. Kopierer derfor først inn hele, så fjerner vi command:
				//strcpy((*fileFilter).command,splitdata[1]);
			
				strscpy((*fileFilter).command,lines,sizeof((*fileFilter).command));
				strcasesandr((*fileFilter).command,sizeof((*fileFilter).command),"command: ","");
				//leger til path der vi har sakt vi skal ha lokal path ( ./ )
				strcasesandr((*fileFilter).command,sizeof((*fileFilter).command),"./",path);
				printf(".command %s\n",(*fileFilter).command);
			}
			else if (strcmp(splitdata[0],"comment") == 0) {
				strscpy((*fileFilter).comment,splitdata[1],sizeof((*fileFilter).comment));
			}
			else if (strcmp(splitdata[0],"format") == 0) {
				strscpy((*fileFilter).format,splitdata[1],sizeof((*fileFilter).format));
			}
			else if (strcmp(splitdata[0],"outputtype") == 0) {
				//stdio, file, osv,,
				strcpy((*fileFilter).outputtype,splitdata[1]);
			}
			else if (strcmp(splitdata[0],"outputformat") == 0) {
				//text, html
				strcpy((*fileFilter).outputformat,splitdata[1]);
			}
			else if (strcmp(splitdata[0], "filtertype") == 0) {
			
				if (strcmp(splitdata[1], FILTER_EXEOC_STR) == 0)
					fileFilter->filtertype = FILTER_EXEOC;

				else if (strcmp(splitdata[1], FILTER_PERL_PLUGIN_STR) == 0) 
					fileFilter->filtertype = FILTER_PERL_PLUGIN;

				else 
					errx(1, "Unknown filtertype %s\n", splitdata[1]);
			
			}
			else if (strcmp(splitdata[0], "attrwhitelist") == 0) {
				// TODO: Free fileFilter->attrwhitelist
				if (!split(splitdata[1], ",", &fileFilter->attrwhitelist))
					warnx("attrwhitelist was empty.");

			}
			else {
				printf("unknown command \"%s\"\n",lines);
			}

			//clean
			FreeSplitList(splitdata);

		}


		if (fileFilter != NULL) {
			//add to hash
			printf("inserting %s\n",(*fileFilter).documentstype);
			//chtbl_insert(&htbl,(void *)fileFilter);
			if (!hashtable_insert(h_fileFilter,fileFilter->documentstype,fileFilter) ) {
                                printf("cant insert\n");
                        	exit(-1);
                        }
			printf("end inserting\n");
		}
		//markerer at vi har lagt det til
		fileFilter = NULL;

		fclose(filep);
	}
	closedir(dirp);

	if (attrkeys != NULL) {
		*attrkeys = ropen();
	}

	return 1;
}
Beispiel #15
0
///////////////////////////////////////////////////////////////////////
// Class				:	CRenderer
// Method				:	getTexture3d
// Description			:	Get a point cloud or brickmap
// Return Value			:
// Comments				:
CTexture3d			*CRenderer::getTexture3d(const char *name,int write,const char* channels,const float *from,const float *to,int hierarchy) {
    CFileResource	*texture3d;
    char			fileName[OS_MAX_PATH_LENGTH];
    FILE			*in;

    assert(name != NULL);
    assert(frameFiles != NULL);

    if (frameFiles->find(name,texture3d) == FALSE) {

        if (from == NULL) {
            from	=	world->from;
            to		=	world->to;
        }

        // If we are writing, it must be a point cloud
        if (write == TRUE) {

            if (netClient != INVALID_SOCKET) {
                CPointCloud	*cloud	=	new CPointCloud(name,world->from,world->to,CRenderer::toNDC,channels,FALSE);
                texture3d			=	cloud;

                // Ensure we unmap the file when done.  Do not delete it
                // as we mark the file to never be written in the server
                registerFrameTemporary(name,FALSE);
                requestRemoteChannel(new CRemotePtCloudChannel(cloud));
            } else {
                // alloate a point cloud which will be written to disk
                texture3d	=	new CPointCloud(name,from,to,CRenderer::toNDC,channels,TRUE);
            }

        } else {
            // Locate the file
            if (locateFile(fileName,name,texturePath)) {
                // Try to open the file
                if ((in	=	ropen(fileName,"rb",filePointCloud,TRUE)) != NULL) {
                    if (hierarchy == TRUE) {
                        texture3d	=	new CPointHierarchy(name,from,to,in);
                    } else {
                        texture3d	=	new CPointCloud(name,from,to,in);
                    }
                } else {
                    if ((in	=	ropen(fileName,"rb",fileBrickMap,TRUE)) != NULL) {
                        texture3d	=	new CBrickMap(in,name,from,to);
                    }
                }
            } else {
                in		=	NULL;
            }

            if (in == NULL) {
                // allocate a dummy blank-channel point cloud
                error(CODE_BADTOKEN,"Cannot find or open Texture3D file \"%s\"\n",name);
                texture3d	=	new CPointCloud(name,world->from,world->to,NULL,NULL,FALSE);
                // remove the dummy mapping once the frame ends
                registerFrameTemporary(name,FALSE);
            }
        }

        frameFiles->insert(texture3d->name,texture3d);
    }

    return (CPointCloud *) texture3d;
}
Beispiel #16
0
void
ioproc0(void *v)
{
	long n;
	Mfile *mf;
	uchar mdata[IOHDRSZ + Maxfdata];
	Request req;
	Job *job;

	USED(v);

	for(;;){
		n = read9pmsg(mfd[0], mdata, sizeof mdata);
		if(n <= 0){
			syslog(0, logfile, "error reading mntpt: %r");
			break;
		}
		job = newjob();
		if(convM2S(mdata, n, &job->request) != n){
			freejob(job);
			continue;
		}
		if(debug)
			syslog(0, logfile, "%F", &job->request);

		getactivity(&req);
		req.aborttime = now + 60;	/* don't spend more than 60 seconds */

		mf = nil;
		switch(job->request.type){
		case Tversion:
		case Tauth:
		case Tflush:
			break;
		case Tattach:
			mf = newfid(job->request.fid, 1);
			if(mf == nil){
				sendmsg(job, "fid in use");
				goto skip;
			}
			break;
		default:
			mf = newfid(job->request.fid, 0);
			if(mf == nil){
				sendmsg(job, "unknown fid");
				goto skip;
			}
			break;
		}

		switch(job->request.type){
		default:
			syslog(1, logfile, "unknown request type %d", job->request.type);
			break;
		case Tversion:
			rversion(job);
			break;
		case Tauth:
			rauth(job);
			break;
		case Tflush:
			rflush(job);
			break;
		case Tattach:
			rattach(job, mf);
			break;
		case Twalk:
			rwalk(job, mf);
			break;
		case Topen:
			ropen(job, mf);
			break;
		case Tcreate:
			rcreate(job, mf);
			break;
		case Tread:
			rread(job, mf);
			break;
		case Twrite:
			rwrite(job, mf, &req);
			break;
		case Tclunk:
			rclunk(job, mf);
			break;
		case Tremove:
			rremove(job, mf);
			break;
		case Tstat:
			rstat(job, mf);
			break;
		case Twstat:
			rwstat(job, mf);
			break;
		}
skip:
		freejob(job);
		putactivity();
	}
}
Beispiel #17
0
int main() {
	struct tar_file *boot_image, *file;
	char const **argv;
	uint64_t temp, temp1, temp2;

	argv = malloc(sizeof(char*) * 4);

	/* Boot Image */
	boot_image = tar_parse((void*) BOOT_IMAGE);

	/* Dynamic Linker */
	file = tar_find(boot_image, "lib/dl.so");
	dl_load(file->start);

	/* Initial Root Filesystem / Device Filesystem / System Filesystem (tmpfs) */
	argv[0] = "tmpfs";
	argv[1] = NULL;
	file = tar_find(boot_image, "sbin/tmpfs");
	fs_root = start(file, argv);
	fs_cons("/dev", "dir");
	fs_cons("/sys", "dir");
	
	/* Serial Driver */
	argv[0] = "serial";
	argv[1] = NULL;
	file = tar_find(boot_image, "sbin/serial");
	fs_plink("/dev/serial", start(file, argv), NULL);
	ropen(1, fs_find("/dev/serial"), STAT_WRITER);
	ropen(2, fs_find("/dev/serial"), STAT_WRITER);
	stdout = fdopen(1, "w");
	stderr = fdopen(2, "w");

	fs_plink("/dev/stderr", fs_find("/dev/serial"), NULL);

	/* Keyboard Driver */
	argv[0] = "kbd";
	argv[1] = NULL;
	file = tar_find(boot_image, "sbin/kbd");
	temp = start(file, argv);

	/* Graphics Driver */
	argv[0] = "svga";
	argv[1] = NULL;
	file = tar_find(boot_image, "sbin/svga");
	start(file, argv);

	/* Init control file */
	fs_plink("/sys/init", RP_CONS(getpid(), 0), NULL);

	/* Initrd */
	initrd_init();
	fs_plink("/dev/initrd", RP_CONS(getpid(), 1), NULL);

	/* Root filesystem (tarfs) */
	argv[0] = "tarfs";
	argv[1] = "/dev/initrd";
	argv[2] = NULL;
	file = tar_find(boot_image, "sbin/tarfs");
	temp = start(file, argv);

	/* Link /dev and /sys and change root */
	temp1 = fs_find("/dev");
	temp2 = fs_find("/sys");
	fs_root = temp;
	fs_plink("/dev", temp1, NULL);
	fs_plink("/sys", temp2, NULL);

	/* Terminal Driver */
	argv[0] = "biterm";
	argv[1] = "/dev/kbd";
	argv[2] = "/dev/svga0";
	argv[3] = NULL;
	file = tar_find(boot_image, "sbin/biterm");
	fs_plink("/dev/tty", start(file, argv), NULL);

	/* Temporary filesystem */
	argv[0] = "tmpfs";
	argv[1] = NULL;
	file = tar_find(boot_image, "sbin/tmpfs");
	fs_plink("/tmp", start(file, argv), NULL);

	/* Time Driver */
	argv[0] = "time";
	argv[1] = NULL;
	file = tar_find(boot_image, "sbin/time");
	fs_plink("/dev/time", start(file, argv), NULL);

	/* Pipe Driver */
	argv[0] = "pipe";
	argv[1] = NULL;
	file = tar_find(boot_image, "sbin/pipe");
	fs_plink("/sys/pipe", start(file, argv), NULL);

	setname("init");
	
	mwait(PORT_CHILD, 0);

	printf("INIT PANIC: system daemon died\n");
	for(;;);
	return 0;
}
Beispiel #18
0
Datei: cs.c Projekt: brho/akaros
static void *job_thread(void *arg)
{
	struct mfile *mf;
	struct job *job = arg;

	spinlock_lock(&dblock);
	mf = newfid(job->request.fid);

	if (debug)
		fprintf(stderr, "CS:%F", &job->request);
	switch (job->request.type) {
	default:
		fprintf(stderr, "CS:unknown request type %d", job->request.type);
		break;
	case Tversion:
		rversion(job);
		break;
	case Tauth:
		rauth(job);
		break;
	case Tflush:
		rflush(job);
		break;
	case Tattach:
		rattach(job, mf);
		break;
	case Twalk:
		rwalk(job, mf);
		break;
	case Topen:
		ropen(job, mf);
		break;
	case Tcreate:
		rcreate(job, mf);
		break;
	case Tread:
		rread(job, mf);
		break;
	case Twrite:
		rwrite(job, mf);
		break;
	case Tclunk:
		rclunk(job, mf);
		break;
	case Tremove:
		rremove(job, mf);
		break;
	case Tstat:
		rstat(job, mf);
		break;
	case Twstat:
		rwstat(job, mf);
		break;
	}
	spinlock_unlock(&dblock);

	freejob(job);

	if (debug)
		fprintf(stderr, "CS:Job done\n");
	return 0;
}
Beispiel #19
0
void
io(void)
{
	volatile long n;
	volatile uchar mdata[IOHDRSZ + Maxfdata];
	Job *volatile job;
	Mfile *volatile mf;
	volatile Request req;

	memset(&req, 0, sizeof req);
	/*
	 *  a slave process is sometimes forked to wait for replies from other
	 *  servers.  The master process returns immediately via a longjmp
	 *  through 'mret'.
	 */
	if(setjmp(req.mret))
		putactivity(0);
	req.isslave = 0;
	stop = 0;
	while(!stop){
		procsetname("%d %s/dns Twrites of %d 9p rpcs read; %d alarms",
			stats.qrecvd9p, mntpt, stats.qrecvd9prpc, stats.alarms);
		n = read9pmsg(mfd[0], mdata, sizeof mdata);
		if(n<=0){
			dnslog("error reading 9P from %s: %r", mntpt);
			sleep(2000);	/* don't thrash after read error */
			return;
		}

		stats.qrecvd9prpc++;
		job = newjob();
		if(convM2S(mdata, n, &job->request) != n){
			freejob(job);
			continue;
		}
		mf = newfid(job->request.fid, 0);
		if(debug)
			dnslog("%F", &job->request);

		getactivity(&req, 0);
		req.aborttime = timems() + Maxreqtm;
		req.from = "9p";

		switch(job->request.type){
		default:
			warning("unknown request type %d", job->request.type);
			break;
		case Tversion:
			rversion(job);
			break;
		case Tauth:
			rauth(job);
			break;
		case Tflush:
			rflush(job);
			break;
		case Tattach:
			rattach(job, mf);
			break;
		case Twalk:
			rwalk(job, mf);
			break;
		case Topen:
			ropen(job, mf);
			break;
		case Tcreate:
			rcreate(job, mf);
			break;
		case Tread:
			rread(job, mf);
			break;
		case Twrite:
			/* &req is handed to dnresolve() */
			rwrite(job, mf, &req);
			break;
		case Tclunk:
			rclunk(job, mf);
			break;
		case Tremove:
			rremove(job, mf);
			break;
		case Tstat:
			rstat(job, mf);
			break;
		case Twstat:
			rwstat(job, mf);
			break;
		}

		freejob(job);

		/*
		 *  slave processes die after replying
		 */
		if(req.isslave){
			putactivity(0);
			_exits(0);
		}

		putactivity(0);
	}
	/* kill any udp server, notifier, etc. processes */
	postnote(PNGROUP, getpid(), "die");
	sleep(1000);
}
Beispiel #20
0
FILE *fdopen(int fd, const char *mode) {
	FILE *stream;
	int status;
	
	if (fd < 0) {
		return NULL;
	}

	// check mode
	if (mode[0] != 'a' && mode[0] != 'w' && mode[0] != 'r') {
		errno = EINVAL;
		return NULL;
	}

	// check if the object is not a file
	if (!rp_type(fd_rp(fd), "file")) {
		errno = EISDIR;
		return NULL;
	}

	status = 0;

	// check read permissions
	if (mode[0] == 'r' || mode[1] == '+') {
		status |= STAT_READER;
	}

	// check write permissions
	if (mode[0] == 'w' || mode[0] == 'a' || mode[1] == '+') {
		status |= STAT_WRITER;
	}

	// open file for real
	fd = ropen(fd, fd_rp(fd), status);
	if (fd < 0) {
		return NULL;
	}

	// reset (erase) the file contents
	if (mode[0] == 'w') {
		rp_reset(fd_rp(fd));
	}

	stream = calloc(sizeof(FILE), 1);

	if (!stream) {
		errno = ENOMEM;
		return NULL;
	}

	stream->fd       = fd;
	stream->mutex    = false;
	stream->position = 0;
	stream->size     = rp_size(fd_rp(fd));
	stream->buffer   = NULL;
	stream->buffsize = 0;
	stream->buffpos  = 0;
	stream->revbuf   = EOF;
	stream->flags    = FILE_NBF | FILE_READ;

	if (mode[0] == 'w' || mode[0] == 'a' || mode[1] == '+') {
		stream->flags |= FILE_WRITE;
	}

	// position the stream properly
	if (mode[0] == 'a' && mode[1] != '+') {
		fseek(stream, 0, SEEK_END);
	}
	else {
		fseek(stream, 0, SEEK_SET);
	}

	return stream;
}
Beispiel #21
0
void
rfServ_(int acceptSock)
{
    static char          fname[] = "rfServ_()";
    struct LSFHeader     msgHdr;
    struct LSFHeader     buf;
    struct sockaddr_in   from;
    socklen_t            fromLen = sizeof(from);
    int                  sock;
    XDR                  xdrs;

    sock = accept(acceptSock, (struct sockaddr *)&from, &fromLen);
    if (sock < 0) {
        ls_errlog(stderr, I18N_FUNC_FAIL_MM, fname, "readDecodeHdr_");
        closesocket(acceptSock);
        return;
    }

    xdrmem_create(&xdrs, (char *) &buf, sizeof(buf), XDR_DECODE);

    for (;;) {

        XDR_SETPOS(&xdrs, 0);
        if (readDecodeHdr_(sock,
                           (char *)&buf,
                           SOCK_READ_FIX,
                           &xdrs,
                           &msgHdr) < 0) {
            ls_errlog(stderr, I18N_FUNC_FAIL_MM, fname, "readDecodeHdr_");
            closesocket(sock);
            xdr_destroy(&xdrs);
            return;
        }

        switch (msgHdr.opCode) {
            case RF_OPEN:
                ropen(sock, &msgHdr);
                break;

            case RF_CLOSE:
                rclose(sock, &msgHdr);
                break;

            case RF_WRITE:
                rwrite(sock, &msgHdr);
                break;

            case RF_READ:
                rread(sock, &msgHdr);
                break;

            case RF_STAT:
                rstat(sock, &msgHdr);
                break;

            case RF_GETMNTHOST:
                rgetmnthost(sock, &msgHdr);
                break;

            case RF_FSTAT:
                rfstat(sock, &msgHdr);
                break;

            case RF_LSEEK:
                rlseek(sock, &msgHdr);
                break;

            case RF_UNLINK:
                runlink(sock, &msgHdr);
                break;

            case RF_TERMINATE:
                closesocket(sock);
                return;

            default:
                ls_errlog(stderr, _i18n_msg_get(ls_catd, NL_SETN, 602,
                                                "%s: Unknown opcode %d"),
                          fname, msgHdr.opCode);
                xdr_destroy(&xdrs);
                break;
        }
    }

}
Beispiel #22
0
int main(int argc, char *argv[]) {
    int fin=-1, fout=-1, f=0;
    char buf[8192], xstring[128]="";
    int rlen, wlen, blen=512, argi, r=0, w=0;

    for(argi=1; argi<argc || argc==1; argi++) {
        if (argc==1 || !strcmp(argv[argi], "--help")) {
            fprintf(stderr, "inlet    [-v|-a|-bN|-p1|-p2|--help] <pipename1 in> [-|<pipename2 out>]\n");
            fprintf(stderr, "Flags:   -v=verbose; -bN=N byte buffer (i.e. -b512); -pN=open pipe N first\n");
            fprintf(stderr, "         -a=always reopen p1 even if p1 closes (note: p2 will never close)\n");
            fprintf(stderr, "Info:    inlet reads from pipe1 to pipe2; if pipe1 closes it is reopened automatically.\n");
            fprintf(stderr, "Purpose: Trick an application into believing that it is reading from a single file (i.e. pipe2):\n");
            fprintf(stderr, "           1) when in fact multiple writers are dynamically opening and closing to pipe1.\n");
            fprintf(stderr, "           2) or from a remote shell (i.e. rsh) or remote machine\n");
            fprintf(stderr, "         while pipe2 is always kept open by the inlet program.\n");
            fprintf(stderr, "Notes:   Pipes can be created by the mkfifo command.\n");
            fprintf(stderr, "         Each pipe open is sequentially suspended (i.e. blocked) until another task accesses it.\n");
            fprintf(stderr, "         O_NDELAY and O_NONBLOCK are not used by inlet (see unix \"man -s 2 open\")\n");
            fprintf(stderr, "Example: mkfifo p1 p2; inlet -v -a p1 p2 & ; cat p2 & ; echo hello >p1; echo Konichiwa >p1;\n");
            fprintf(stderr, "\n");
            exit(1);
        }
        else if (!strcmp(argv[argi],  "-v"))    {
            vflag=1;
        }
        else if (!strcmp(argv[argi],  "-a"))    {
            aflag=1;
        }
        else if (!strncmp(argv[argi], "-b", 2)) {
            blen=atoi(argv[argi]+2);
        }
        else if (!strcmp(argv[argi],  "-p1"))   {
            pflag=1;
        }
        else if (!strcmp(argv[argi],  "-p2"))   {
            pflag=2;
        }
        else if ( strncmp(argv[argi], "-",  1) || strlen(argv[argi])>1) {
            if      (f==0) {
                f++;
                r=argi;
            }
            else if (f==1) {
                f++;
                w=argi;
            }
            else           {
                fprintf(stderr, "inlet: unexpected pipename or filename \"%s\"\n", argv[argi]);
                exit(1);
            }
        }
    }
    if (f!=2) {
        fprintf(stderr, "inlet: missing in or out pipe names\n");
        exit(1);
    }

    if    (vflag) {
        fprintf(stderr, "inlet: bufsize=%d (-b%d)\n", blen, blen);
    }

    if (pflag==1) {
        fin=ropen(argv[r]);
        fout=wopen(argv[w]);
    }
    else          {
        fout=wopen(argv[w]);
        fin=ropen(argv[r]);
    }

    if (vflag) {
        fprintf(stderr, "inlet: start reading pipe \"%s\" writing to \"%s\"\n", argv[r], argv[w]);
    }
    for(;;) {
        rlen = read(fin, buf, blen);
        if (vflag) {
            fprintf(stderr, "inlet: %d=read(\"%s\",buf,%d bytes);\n", rlen, argv[r], blen);
        }

        if      (rlen==0) {
            close(fin);
            if (aflag) {
                fin=ropen(argv[r]);
            }
            else {
                break;
            } /* eof on pipe1 */
        }
        else if (rlen<0) {
            if (vflag) {
                fprintf(stderr, "inlet: read error from \"%s\"\n", rlen, argv[r]);
            }
            perror("inlet: read");
            return 1;
        }

        wlen=write(fout, buf, rlen);
        if (vflag) {
            fprintf(stderr, "inlet: %d=write(\"%s\",buf,%d bytes);\n", wlen, argv[w], rlen);
        }
        if (wlen != rlen) {
            if (vflag) {
                fprintf(stderr, "inlet: write(\"%s\") length %d != read length %d\n", argv[w], wlen, rlen);
            }
            perror("inlet: write");
            return 1;
        }
    }
    return 0;
}
Beispiel #23
0
Datei: srv.c Projekt: npe9/harvey
void
respond(Req *r, char *error)
{
	int i, m, n;
	char errbuf[ERRMAX];
	Srv *srv;

	srv = r->srv;
	assert(srv != nil);

	assert(r->responded == 0);
	r->error = error;

	switch(r->ifcall.type){
	default:
		assert(0);
	/*
	 * Flush is special.  If the handler says so, we return
	 * without further processing.  Respond will be called
	 * again once it is safe.
	 */
	case Tflush:
		if(rflush(r, error)<0)
			return;
		break;
	case Tversion:	rversion(r, error);	break;
	case Tauth:	rauth(r, error);	break;
	case Tattach:	rattach(r, error);	break;
	case Twalk:	rwalk(r, error);	break;
	case Topen:	ropen(r, error);	break;
	case Tcreate:	rcreate(r, error);	break;
	case Tread:	rread(r, error);	break;
	case Twrite:	rwrite(r, error);	break;
	case Tclunk:	rclunk(r, error);	break;
	case Tremove:	rremove(r, error, errbuf);	break;
	case Tstat:	rstat(r, error);	break;
	case Twstat:	rwstat(r, error);	break;
	}

	r->ofcall.tag = r->ifcall.tag;
	r->ofcall.type = r->ifcall.type+1;
	if(r->error)
		setfcallerror(&r->ofcall, r->error);

if(chatty9p)
	fprint(2, "-%d-> %F\n", srv->outfd, &r->ofcall);

	qlock(&srv->wlock);
	n = convS2M(&r->ofcall, srv->wbuf, srv->msize);
	if(n <= 0){
		fprint(2, "n = %d %F\n", n, &r->ofcall);
		abort();
	}
	assert(n > 2);
	if(r->pool)	/* not a fake */
		closereq(removereq(r->pool, r->ifcall.tag));
	m = write(srv->outfd, srv->wbuf, n);
	if(m != n)
		sysfatal("lib9p srv: write %d returned %d on fd %d: %r", n, m, srv->outfd);
	qunlock(&srv->wlock);

	qlock(&r->lk);	/* no one will add flushes now */
	r->responded = 1;
	qunlock(&r->lk);

	for(i=0; i<r->nflush; i++)
		respond(r->flush[i], nil);
	free(r->flush);
	r->flush = nil;
	r->nflush = 0;

	if(r->pool)
		closereq(r);
	else
		free(r);
}
Beispiel #24
0
/* Use script to produce jpeg frames */
void script_animate (int iw)
{
    char buf[SCRIPT_LINE_SIZE],output[SCRIPT_LINE_SIZE],*ptr;
    int i,hascontent,quality,frames;
    FILE *fp;
    glob_t globbuf;
    
    strcpy(buf, "scr_anim");
    if (!(fp=ropen(buf)))
    {
        printf ("\nAnimation script \"%s\" does not exist,\n", buf);
        xterm_get_focus(iw); clear_stdin_buffer();
        if (!strcasecmp("y", readline_gets
                        ("Do you want a default one created (y/n)?","y")))
        {
            numerically_sorted_glob (config_fname, &globbuf);
            fp=wopen(buf);
            fprintf (fp, "%d\n", AX_JPG_DEF_QUALITY);
            for (i=0; i<globbuf.gl_pathc; i++)
                fprintf (fp, "%s Jpg/%05d.jpg\n", globbuf.gl_pathv[i], i);
            globfree (&globbuf);
            fclose(fp);
            fp = ropen(buf);
        }
        else
        {
            xterm_release_focus(iw);
            return;
        }
    }
    if (!(ptr=fgets(buf,SCRIPT_LINE_SIZE,fp)))
    {
        printf ("\nThere is nothing in animation script \"%s\".\n", buf);
        fclose (fp);
        return;
    }
    for (hascontent=i=0; (buf[i]!=EOS) &&
             (ISDIGIT(buf[i]) || ISBLANK(buf[i]) || (buf[i]=='\n')); i++)
        if (ISALNUM(buf[i])) hascontent=1;
    if (!hascontent)
    {
        printf ("\nThere is no content in animation script \"%s\".\n", buf);
        fclose (fp);
        return;
    }
    if (buf[i] == EOS)
    {
        sscanf (buf, "%d", &quality);
        if ((quality<0) || (quality>100))
        {
            printf ("\nquality = %d is out of valid range ([0,100]).\n",
                    quality);
            return;
        }
        else printf ("\nquality = %d\n", quality);
        ptr = fgets(buf,SCRIPT_LINE_SIZE,fp);
    }
    else quality = AX_JPG_DEF_QUALITY;
    frames = 0;
    /* If bonds are not on now, there is no need to refresh */
    temporary_disable_bond = !n[iw].bond_mode;
    /* cylinder data structure during the rendering.        */
    while (ptr)
    {
        buf[SCRIPT_LINE_CHAR] = EOS;
        sscanf (buf, "%s %s", config_fname, output);
        reload_config (iw, FALSE);
        paint_scene(iw);
        AX_dump(iw); AX_show(iw);
        if (str_caseend_with(output,".png"))
            AX_save_pixmap_as_png
                (iw,AX_JPG_QUALITY_TO_PNG_LEVEL(quality),output);
        else if (str_caseend_with(output,".eps"))
            AX_save_pixmap_as_eps(iw,quality,output);
        else AX_save_pixmap_as_jpg(iw,quality,output);
        frames++;
        ptr = fgets(buf,SCRIPT_LINE_SIZE,fp);
    }
    fclose(fp);
    printf ("%d frames saved.\n\n", frames);
    if (temporary_disable_bond)
    {
        Config_to_3D_Bonds (n[iw].bond_radius);
        if (n[iw].bond_mode)
        {
            bond_xtal_origin_update (iw);
            bond_atom_color_update(iw);
        }
        else
        {
            n[iw].bond_xtal_origin_need_update = TRUE;
            n[iw].bond_atom_color_need_update = TRUE;
        }
        temporary_disable_bond = 0;
    }
    return;
} /* end script_animate() */