Пример #1
0
static void *server_routine(void *arg)
{
	static int status = 0;
	static int started = 0;
	if (started)
	{
		output_error("server routine is already running");
		return NULL;
	}
	started = 1;
	sockfd = (SOCKET)arg;
	// repeat forever..
	while (!shutdown_server)
	{
		struct sockaddr_in cli_addr;
		SOCKET newsockfd;

		int clilen = sizeof(cli_addr);

		/* accept client request and get client address */
		newsockfd = accept(sockfd,(struct sockaddr *)&cli_addr,&clilen);
		if ((int)newsockfd<0 && errno!=EINTR)
		{
			status = GetLastError();
			output_error("server accept error on fd=%d: code %d", sockfd, status);
			goto Done;
		}
		else if ((int)newsockfd > 0)
		{
#ifdef WIN32
			output_verbose("accepting incoming connection from %d.%d.%d.%d on port %d", cli_addr.sin_addr.S_un.S_un_b.s_b1,cli_addr.sin_addr.S_un.S_un_b.s_b2,cli_addr.sin_addr.S_un.S_un_b.s_b3,cli_addr.sin_addr.S_un.S_un_b.s_b4,cli_addr.sin_port);
#else
			output_verbose("accepting incoming connection from on port %d",cli_addr.sin_port);
#endif

			if ( pthread_create(&thread_id,NULL, http_response,(void*)newsockfd)!=0 )
				output_error("unable to start http response thread");
			if (global_server_quit_on_close)
				shutdown_now();
			else
				gui_wait_status(0);
		}
#ifdef NEVER
		{
			handleRequest(newsockfd);
#ifdef WIN32
			closesocket(newsockfd);
#else
			close(newsockfd);
#endif
		}
#endif
	}
	output_verbose("server shutdown");
Done:
	started = 0;
	return (void*)&status;
}
Пример #2
0
STATUS server_startup(int argc, char *argv[])
{
	int portNumber = global_server_portnum;
	SOCKET sockfd;
	struct sockaddr_in serv_addr;
	pthread_t thread;

#ifdef WIN32
	WSADATA wsaData;
	if (WSAStartup(MAKEWORD(2,0),&wsaData)!=0)
	{
		output_error("socket library initialization failed");
		return FAILED;	
	}
#endif

	/* create a new socket */
	if ((sockfd = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP)) == INVALID_SOCKET)
	{
		output_error("can't create stream socket: %s",GetLastError());
		return FAILED;
	}
	atexit(shutdown_now);

	memset(&serv_addr,0,sizeof(serv_addr));

	serv_addr.sin_family = AF_INET;
	serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
	serv_addr.sin_port = htons(portNumber);

	/* bind socket to server address */
	if (bind(sockfd,(struct sockaddr *)&serv_addr,sizeof(serv_addr)) < 0)
	{
#ifdef WIN32
		output_error("can't bind to %d.%d.%d.%d",serv_addr.sin_addr.S_un.S_un_b.s_b1,serv_addr.sin_addr.S_un.S_un_b.s_b2,serv_addr.sin_addr.S_un.S_un_b.s_b3,serv_addr.sin_addr.S_un.S_un_b.s_b4);
#else
		output_error("can't bind address");
#endif
		return FAILED;
	}
#ifdef WIN32
	output_verbose("bind ok to %d.%d.%d.%d",serv_addr.sin_addr.S_un.S_un_b.s_b1,serv_addr.sin_addr.S_un.S_un_b.s_b2,serv_addr.sin_addr.S_un.S_un_b.s_b3,serv_addr.sin_addr.S_un.S_un_b.s_b4);
#else
	output_verbose("bind ok to address");
#endif	
	/* listen for connection */
	listen(sockfd,5);
	output_verbose("server listening to port %d", portNumber);

	/* start the server thread */
	if (pthread_create(&thread,NULL,server_routine,(void*)sockfd))
	{
		output_error("server thread startup failed");
		return FAILED;
	}

	return SUCCESS;
}
Пример #3
0
/** Callback function to shut server down
 
    This process halts both the server and the simulator.
	
	@return Nothing
 **/
static void shutdown_now(void)
{
	output_verbose("server shutdown on exit in progress...");
	exec_setexitcode(XC_SVRKLL);
	shutdown_server = 1;
	if (sockfd!=(SOCKET)0)
#ifdef WIN32
		shutdown(sockfd,SD_BOTH);
#else
		shutdown(sockfd,SHUT_RDWR);
#endif
	sockfd = (SOCKET)0;
	gui_wait_status(GUIACT_HALT);
	output_verbose("server shutdown on exit done");
}
Пример #4
0
/** Shuffle an index to avoid excessive lock contention in models 
	where topologically adjacent objects are loaded sequentially
 **/
void index_shuffle(INDEX *index)	/**< the index to shuffle */
{
	int i, size = index->last_used - index->first_used;
	for (i=0; i<size; i++)
		list_shuffle(index->ordinal[i]);
	output_verbose("shuffled %d lists in index %d", size, index->id);
}
Пример #5
0
/** Callback function to shut server down
 
    This process halts both the server and the simulator.
	
	@return Nothing
 **/
static void shutdown_now(void)
{
	extern int stop_now;
	output_verbose("server shutdown on exit in progress...");
	stop_now = 1;
	shutdown_server = 1;
	if (sockfd!=(SOCKET)0)
#ifdef WIN32
		shutdown(sockfd,SD_BOTH);
#else
		shutdown(sockfd,SHUT_RDWR);
#endif
	sockfd = (SOCKET)0;
	gui_wait_status(GUIACT_HALT);
	output_verbose("server shutdown on exit done");
}
Пример #6
0
int enduse_test(void)
{
	int failed = 0;
	int ok = 0;
	int errorcount = 0;

	/* tests */
	struct s_test {
		char *name;
	} *p, test[] = {
		"TODO",
	};

	output_test("\nBEGIN: enduse tests");
	for (p=test;p<test+sizeof(test)/sizeof(test[0]);p++)
	{
	}

	/* report results */
	if (failed)
	{
		output_error("endusetest: %d enduse tests failed--see test.txt for more information",failed);
		output_test("!!! %d enduse tests failed, %d errors found",failed,errorcount);
	}
	else
	{
		output_verbose("%d enduse tests completed with no errors--see test.txt for details",ok);
		output_test("endusetest: %d schedule tests completed, %d errors found",ok,errorcount);
	}
	output_test("END: enduse tests");
	return failed;
}
Пример #7
0
void msghandler(void *param)
{
	char name[32];
	HANDLE hEvent;
	unsigned int sig = (unsigned int)(int64)param;
	pid_t pid = (pid_t)_getpid();
	sprintf(name,"gridlabd.%u.%u",pid,sig);
	hEvent = CreateEventA(NULL,TRUE,FALSE,name);
	output_verbose("creating gridlabd signal handler %u for process %u",sig,pid);
	while (WaitForSingleObject(hEvent,INFINITE)==WAIT_OBJECT_0)
	{
		output_verbose("windows signal handler activated");
		raise(sig);
		ResetEvent(hEvent);
	}
}
Пример #8
0
void kill_starthandler(void)
{
	if (_beginthread(&msghandler, 0, (void*)SIGINT)==1 || _beginthread(&msghandler, 0, (void*)SIGTERM)==1)
		output_error("kill handler failed to start");
	else
		output_verbose("windows message signal handlers started");
}
Пример #9
0
/** Process an incoming R data request
	@returns non-zero on success, 0 on failure (errno set)
 **/
int http_run_r(HTTP *http,char *uri)
{
	char script[1024];
	char command[1024];
	char output[1024];
	char *mime = strchr(uri,'?');
	char *ext = mime?strchr(mime,'/'):NULL;
	char *r = strrchr(uri,'.');
	int rc = 0;

	/* find mime and extension */
	if (mime==NULL)
	{
		output_error("R request does not include mime type");
		return 0;
	}
	else
		*mime++ = '\0'; /* mime type actually start at next character */
	if (ext) ext++;

	/* if not a plot request */
	if (r==NULL || strcmp(r,".r")!=0)
	{
		output_error("R request does not specify an R script filename with extension .r");
		return 0;
	}

	/* setup gnuplot command */
	sprintf(script,"%s",uri);
#ifdef WIN32
	sprintf(command,"r CMD BATCH %s",script);
#else
	sprintf(command,"R --vanilla CMD BATCH %s",script);
#endif

	/* temporary cut off of plt extension to build output file */
	*r = '\0'; sprintf(output,"%s.%s",uri,ext); *r='.';

	/* run gnuplot */
	output_verbose("%s", command);
	if ((rc=system(command))!=0)
	{
		switch (rc)
		{
		case -1: /* an error occurred */
			output_error("unable to run R on '%s': %s", uri, strerror(errno));
			break;
		default:
			output_error("R return error code %d on '%s'", rc, uri);
			break;
		}
		return 0;
	}

	/* copy output to http */
	return http_copy(http,"R",output);
}
Пример #10
0
/**	endDocument() is called when the end of the file is reached.  Any post-processing within the parser should occur here.
*/
void gld_loadHndl::endDocument(){
	OBJECT *tempobj = object_get_first();

	/* resolve_list(); */
	if(load_resolve_all() == FAILED){
		output_error("XML_Load: unable to resolve object linkings!");
		load_state = false;
	}
	/* "establish ranks" */

	for (; obj!=NULL; obj=obj->next)
		object_set_parent(obj,obj->parent);
	output_verbose("XML_Load: %d object%s loaded.", object_get_count(), object_get_count() > 0 ? "s" : "");
	if(object_count > 0)
		if(object_get_count() != this->object_count)
			output_warning("XML_Load: we expected %i objects instead!", this->object_count);
	output_verbose("XML_Load: %d class%s loaded.", class_get_count(), class_get_count() > 0 ? "es" : "");
	if(class_count > 0)
		if(class_get_count() != this->class_count)
			output_warning("XML_Load: we expected %i classes instead!", this->class_count);
}
Пример #11
0
STATUS test_init(void)
{
	OBJECT *obj;
	output_verbose("initializing objects...");
	for (obj=object_get_first(); obj!=NULL; obj=object_get_next(obj))
	{
		if (object_init(obj)==FAILED)
		{
			output_error("object %s initialization failed", object_name(obj));
			return FAILED;
		}
	}
	return SUCCESS;
}
Пример #12
0
void Channel::event(uint8_t a, uint8_t b, uint8_t c)
{
	switch(a & 0xF0)
	{
		case 0x80: note_off(b); break;
		case 0x90: note_on(b,c); break;
		case 0xA0: break; //IMPLEMENTME: polyphonic aftertouch (note, dynamic)
		case 0xB0: set_controller(b,c); break;
		case 0xC0: set_program(b); break;
		case 0xD0: break; //IMPLEMENTME: monotonic aftertouch (dynamic)
		case 0xE0: set_pitch_bend( ( (((b&0x7F) + ((c&0x7F)<<7)) - 8192) / 8192.0 ) * max_pitchbend ); break;
		case 0xF0: break; //own controls/sysex (to be implemented) IMPLEMENTME
		default: output_verbose("NOTE: got unknown command "+ IntToStrHex(a&0xF0) +", ignoring it\n");
		;
	}
}
Пример #13
0
static void http_send(HTTP *http)
{
	char header[4096];
	int len=0;
	len += sprintf(header+len, "HTTP/1.1 %s", http->status?http->status:HTTP_INTERNALSERVERERROR);
	output_verbose("%s (len=%d)",header,http->len);
	len += sprintf(header+len, "\nContent-Length: %d\n", http->len);
	if (http->type)
		len += sprintf(header+len, "Content-Type: %s\n", http->type);
	len += sprintf(header+len, "Cache-Control: no-cache\n");
	len += sprintf(header+len, "Cache-Control: no-store\n");
	len += sprintf(header+len,"\n");
	send_data(http->s,header,len);
	if (http->len>0)
		send_data(http->s,http->buffer,http->len);
	http->len = 0;
}
Пример #14
0
/** Create an index
	@return a pointer to the index structure
 **/
INDEX *index_create(int first_ordinal, /**< the first ordinal */
					int last_ordinal) /**< the last ordinal */
{
	int size = (unsigned int)(last_ordinal - first_ordinal + 1);
	INDEX *index = malloc(sizeof(INDEX));
	if (index!=NULL)
	{
		if (size<1)
		{
			errno = EINVAL;
			goto Undo;
		}
		index->ordinal = malloc(sizeof(GLLIST*)*size);
		if (index->ordinal==NULL)
		{
			errno = ENOMEM;
			goto Undo;
		}
		index->id = next_index_id++;
		index->first_ordinal = first_ordinal;
		index->last_ordinal = last_ordinal;
		memset(index->ordinal,0,sizeof(GLLIST*)*size);
		output_verbose("creating index %d", index->id);
	}
	else
	{
		errno = ENOMEM;
		return NULL;
	}

	/* reversal forces adjustment when first item is received */
	index->first_used=last_ordinal;
	index->last_used=first_ordinal;
	return index;
Undo:
	free(index);
	index = NULL;
	return NULL;
}
Пример #15
0
/** Send a kill signal to a windows version of GridLAB-D
    @return 0 on successfull completion, -1 on error (e.g., no such signal, no such process)
 **/
int kill(pid_t pid,	/**< the window process id */
		 int sig)				/**< the signal id (see signal.h) */
{
	char name[32];
	HANDLE hEvent;
	sprintf(name,"gridlabd.%u.%u",pid,sig==0?SIGINT:sig); /* use INT for sig==0 just to check */
	hEvent = OpenEventA(EVENT_MODIFY_STATE,FALSE,name);
	
	/* existence check only */
	if ( sig==0 )
	{
		if ( hEvent!=NULL )
		{
			CloseHandle(hEvent);
			return 0;
		}
		else
		{
			errno = ESRCH;
			return -1;
		}
	}

	/* valid signal needs to be sent */
	else if (hEvent==NULL)
	{
		errno = EINVAL; // TODO distinguish between bad signal and bad pid
		output_error("unable to signal gridlabd process %d with signal %d (error %d)", pid, sig, GetLastError());
		return -1;
	}
	else 
	{
		SetEvent(hEvent);
		output_verbose("signal %d sent to gridlabd process %d", sig, pid);
		CloseHandle(hEvent);
		return 0;
	}
}
Пример #16
0
void gld_loadHndl::ignorableWhitespace(const XMLCh* const chars, const unsigned int length){
	output_verbose("XML_Load: ignored: %i spaces.", length);
}
Пример #17
0
/**	characters() is where the raw text between the tags is handled.
*/
void gld_loadHndl::characters(const XMLCh* const chars, const unsigned int length){
    char buffer[1024];
	char tbuff[1024];
	wchar_t wbuff[1024];
	SAXParseException *e = NULL;
	char *unit_ptr = NULL;
	unsigned int i = 0;
	size_t len = 0;
	char *retval = NULL;	//	negative logic
	switch(stack_state){
		case MODULE_PROP:
		case GLOBAL_PROP:
		case OBJECT_PROP:
		case CLOCK_PROP:
			//	get prop
			if((len = wcslen((const wchar_t *)chars)) < 1){
				sprintf(tbuff, "Unable to get length of characters in characters()");
				mbstowcs(wbuff, tbuff, 1024);
				e = new SAXParseException((const XMLCh *)wbuff, *(this->locator));
				error(*e);
				delete e;
				return;
			}
			if(len != wcstombs(buffer, (const wchar_t *)chars, 1024)){
				sprintf(tbuff, "Unable to convert wcs to char in characters()");
				mbstowcs(wbuff, tbuff, 1024);
				e = new SAXParseException((const XMLCh *)wbuff, *(this->locator));
				error(*e);
				delete e;
				return;
			}
			break;
		default:
			return;	//	ignore whatever characters we read, we don't use them here.
	}
	if(len > 0){
		int j = 0;
		int i = 0;
		for(i = 0; i < (int)len; ++i){
			if(isspace(buffer[i])){
				++j;
			}
		}
		if(i == j){
			output_verbose("XML_Load: ignored: %i spaces.", length);
			retval = 0;
			return;
		}
	} else {
		output_verbose("XML_Load: ignored empty characters() call");
		retval = 0;
		return;
	}
	if(buffer[0] == '"' && buffer[1] == '"'){
		output_verbose("XML_Load: ignored empty doublequote characters() call");
		retval = 0;
		return;
	}
	switch(stack_state){
		case MODULE_PROP:
			retval = this->read_module_prop(buffer, len);
			break;
		case GLOBAL_PROP:
			retval = this->read_global_prop(buffer, len);
			break;
		case OBJECT_PROP:
			retval = this->read_object_prop(buffer, len);
			//	get prop
			break;
		case CLOCK_PROP:
			retval = this->read_clock_prop(buffer, len);
	}
	if(retval != NULL){
		stack_state = EMPTY;	//	stop processing
		output_error("Error reading the XML file");
		mbstowcs(wbuff, errmsg, 1024);
		e = new SAXParseException((const XMLCh *)wbuff, *(this->locator));
		error(*e);
		delete e;
		load_state = 0;
	}

}
Пример #18
0
/** Test the daylight saving time calculations
	@return the number of test the failed
 **/
int timestamp_test(void)
{
#define NYEARS 50
	int year;
	static DATETIME last_t;
	TIMESTAMP step = SECOND;
	TIMESTAMP ts;
	char buf1[64], buf2[64];
	char steptxt[32];
	TIMESTAMP *event[]={dststart,dstend};
	int failed=0, succeeded=0;

	output_test("BEGIN: daylight saving time event test for TZ=%s...", current_tzname);
	convert_from_timestamp(step,steptxt,sizeof(steptxt));
	for (year=0; year<NYEARS; year++)
	{
		int test;
		for (test=0; test<2; test++)
		{
			for (ts=(event[test])[year]-2*step; ts<(event[test])[year]+2*step;ts+=step)
			{
				DATETIME t;
				if (local_datetime(ts,&t))
				{
					if (last_t.is_dst!=t.is_dst)
						output_test("%s + %s = %s", strdatetime(&last_t,buf1,sizeof(buf1))?buf1:"(invalid)", steptxt, strdatetime(&t,buf2,sizeof(buf2))?buf2:"(invalid)");
					last_t = t;
					succeeded++;
				}
				else
				{
					output_test("FAILED: unable to convert ts=%"FMT_INT64"d to local time", ts);
					failed++;
				}
			}
		}
	}
	output_test("END: daylight saving time event test");

	step=HOUR;
	convert_from_timestamp(step,steptxt,sizeof(steptxt));
	output_test("BEGIN: round robin test at %s timesteps",steptxt);
	for (ts=DAY+tzoffset; ts<DAY*365*NYEARS; ts+=step)
	{
		DATETIME t;
		if (local_datetime(ts,&t))
		{
			TIMESTAMP tt = mkdatetime(&t);
			convert_from_timestamp(ts,buf1,sizeof(buf1));
			convert_from_timestamp(tt,buf2,sizeof(buf2));
			if (tt==TS_INVALID)
			{
				output_test("FAILED: unable to extract %04d-%02d-%02d %02d:%02d:%02d %s (dow=%s, doy=%d)", t.year,t.month,t.day,t.hour,t.minute,t.second,t.tz,dow[t.weekday],t.yearday);
				failed++;
			}
			else if (tt!=ts)
			{
				output_test("FAILED: unable to match %04d-%02d-%02d %02d:%02d:%02d %s (dow=%s, doy=%d)\n    from=%s, to=%s", t.year,t.month,t.day,t.hour,t.minute,t.second,t.tz,dow[t.weekday],t.yearday,buf1,buf2);
				failed++;
			}
			else if (convert_to_timestamp(buf1)!=ts)
			{
				output_test("FAILED: unable to convert %04d-%02d-%02d %02d:%02d:%02d %s (dow=%s, doy=%d) back to a timestamp\n    from=%s, to=%s", t.year,t.month,t.day,t.hour,t.minute,t.second,t.tz,dow[t.weekday],t.yearday,buf1,buf2);
				output_test("        expected %" FMT_INT64 "d but got %" FMT_INT64 "d", ts, convert_to_timestamp(buf1));
				failed++;
			}
			else
				succeeded++;
		}
		else
		{
			output_test("FAILED: timestamp_test: unable to convert ts=%"FMT_INT64"d to local time", ts);
			failed++;
		}
	}
	output_test("END: round robin test",steptxt);
	output_test("END: daylight saving time tests for %d to %d", YEAR0, YEAR0+NYEARS);
	output_verbose("daylight saving time tests: %d succeeded, %d failed (see '%s' for details)", succeeded, failed, global_testoutputfile);
	return failed;
}
Пример #19
0
void *check_version_proc(void *ptr)
{
	int patch, build;
	char *url = "http://gridlab-d.svn.sourceforge.net/viewvc/gridlab-d/trunk/core/versions.txt";
	HTTPRESULT *result = http_read(url,0x1000);
	char target[32];
	char *pv = NULL, *nv = NULL;
	int rc = 0;
	int mypatch = REV_PATCH;
	int mybuild = atoi(BUILDNUM);

	/* if result not found */
	if ( result==NULL || result->body.size==0 )
	{
		output_warning("check_version: unable to read %s", url);
		rc=CV_NOINFO;
		goto Done;
	}

	/** @todo check the version against latest available **/
	if ( result->status>0 && result->status<400 )
	{
		output_warning("check_version: '%s' error %d", url, result->status);
		rc=CV_BADURL;
		goto Done;
	}

	/* read version data */
	sprintf(target,"%d.%d:",REV_MAJOR,REV_MINOR);
	pv = strstr(result->body.data,target);
	if ( pv==NULL )
	{
		output_warning("check_version: '%s' has no entry for version %d.%d", url, REV_MAJOR, REV_MINOR);
		rc=CV_NODATA;
		goto Done;
	}
	if ( sscanf(pv,"%*d.%*d:%d:%d", &patch, &build)!=2 )
	{
		output_warning("check_version: '%s' entry for version %d.%d is bad", url, REV_MAJOR, REV_MINOR);
		rc=CV_NODATA;
		goto Done;
	}

	nv = strchr(pv,'\n');
	if ( nv!=NULL )
	{
		while ( *nv!='\0' && isspace(*nv) ) nv++;
		if ( *nv!='\0' )
		{
			output_warning("check_version: newer versions than %s (Version %d.%d) are available", BRANCH, REV_MAJOR, REV_MINOR);
			rc|=CV_NEWVER;
		}
		/* not done yet */
	}
	if ( mypatch<patch )
	{
		output_warning("check_version: a newer patch of %s (Version %d.%d.%d-%d) is available", BRANCH, REV_MAJOR, REV_MINOR, patch, build);
		rc|=CV_NEWPATCH;
		/* not done yet */
	}
	if ( mybuild>0 && mybuild<build )
	{
		output_warning("check_version: a newer build of %s (Version %d.%d.%d-%d) is available", BRANCH, REV_MAJOR, REV_MINOR, patch, build);
		rc|=CV_NEWBUILD;
	}
	if ( rc==0 )
		output_verbose("this version is current");

	/* done */
Done:
	http_delete_result(result);
	return (void*)rc;
}
Пример #20
0
MODULE *module_load(const char *file, /**< module filename, searches \p PATH */
							   int argc, /**< count of arguments in \p argv */
							   char *argv[]) /**< arguments passed from the command line */
{
	/* check for already loaded */
	MODULE *mod = module_find((char *)file);
	char buffer[FILENAME_MAX+1];
	char *fmod;
	bool isforeign = false;
	char pathname[1024];
	char *tpath = NULL;
#ifdef WIN32
	char from='/', to='\\';
#else
	char from='\\', to='/';
#endif
	char *p = NULL;
	void *hLib = NULL;
	LIBINIT init = NULL;
	int *pMajor = NULL, *pMinor = NULL;
	CLASS *previous = NULL;
	CLASS *c;

#ifdef NEVER /* this shouldn't ever be necessary but sometimes for debugging purposes it is helpful */
	/* if LD_LIBRARY_PATH is not set, default to current directory */
	if (getenv("LD_LIBRARY_PATH")==NULL)
	{
		putenv("LD_LIBRARY_PATH=.");
		output_verbose("Setting default LD_LIBRARY_DEFAULT to current directory");
	}
#endif

	if (mod!=NULL)
	{
		output_verbose("%s(%d): module '%s' already loaded", __FILE__, __LINE__, file);
		return mod;
	}
	else
	{
		output_verbose("%s(%d): module '%s' not yet loaded", __FILE__, __LINE__, file);
	}

	/* check for foreign modules */
	strcpy(buffer,file);
	fmod = strtok(buffer,"::");
	if (fmod!=NULL && strcmp(fmod, file) != 0)
	{
		char *modname = strtok(NULL,"::");
		MODULE *parent_mod = module_find(fmod);
		if(parent_mod == NULL)
			parent_mod = module_load(fmod, 0, NULL);
		previous = class_get_last_class();
		if(parent_mod != NULL && parent_mod->subload != NULL)
		{	/* if we've defined a subload routine and already loaded the parent module*/
			MODULE *child_mod;
			if(module_find(fmod) == NULL)
				module_load(fmod, 0, NULL);
			child_mod = parent_mod->subload(modname, &mod, (previous ? &(previous->next) : &previous), argc, argv);
			if(child_mod == NULL)
			{	/* failure */
				output_error("module_load(file='%s::%s'): subload failed", fmod, modname);
				return NULL;
			}
			if (mod != NULL)
			{	/* if we want to register another module */
				last_module->next = mod;
				last_module = mod;
				mod->oclass = previous ? previous->next : class_get_first_class();
			}
			return last_module;
		} else {
			struct {
				char *name;
				LOADER loader;
			} fmap[] = {
				{"matlab",NULL},
				{"java",load_java_module},
				{"python",load_python_module},
				{NULL,NULL} /* DO NOT DELETE THIS TERMINATOR ENTRY */
			}, *p;
			for (p=fmap; p->name!=NULL; p++)
			{
				if (strcmp(p->name, fmod)==0)
				{
					static char *args[1];
					isforeign = true;
					if (p->loader!=NULL)
						/* use external loader */
						return p->loader(modname,argc,argv);

					/* use a module with command args */
					argv = args;
					argc=1;
					argv[0] = modname;
					file=buffer;
					break;
				}
			}
			if (p==NULL)
			{
				output_error("module_load(file='%s',...): foreign module type %s not recognized or supported", fmod);
				return NULL;
			}
		}
	}

	/* create a new module entry */
	mod = (MODULE *)malloc(sizeof(MODULE));
	if (mod==NULL)
	{
		output_verbose("%s(%d): module '%s' memory allocation failed", __FILE__, __LINE__, file);
		errno=ENOMEM;
		return NULL;
	}
	else
		output_verbose("%s(%d): module '%s' memory allocated", __FILE__, __LINE__, file);

	/* locate the module */
	snprintf(pathname, 1024, "%s" DLEXT, file);
	tpath = find_file(pathname, NULL, X_OK|R_OK);
	if(tpath == NULL)
	{
		output_verbose("unable to locate %s in GLPATH, using library loader instead", pathname);
		tpath=pathname;
	}
	else
	{
#ifndef WIN32
		/* if the path is a relative path */
		struct stat buf;
		if (tpath[0]!='/' && stat(tpath,&buf)==0) 
		{
			char buffer[1024];

			/* add ./ to the beginning of the path */
			sprintf(buffer,"./%s", tpath);
			strcpy(tpath,buffer);
		}
#endif
		output_verbose("full path to library '%s' is '%s'", file, tpath);
	}

	/* convert path delims based on OS preference */
	for (p=strchr(tpath,from); p!=NULL; p=strchr(p,from))
		*p=to;

	/* ok, let's do it */
	hLib = DLLOAD(tpath);
	if (hLib==NULL)
	{
#if defined WIN32 && ! defined MINGW
		output_error("%s(%d): module '%s' load failed - %s (error code %d)", __FILE__, __LINE__, file, strerror(errno), GetLastError());
#else
		output_error("%s(%d): module '%s' load failed - %s", __FILE__, __LINE__, file, dlerror());
		output_debug("%s(%d): path to module is '%s'", __FILE__, __LINE__, tpath);
#endif
		dlload_error(pathname);
		errno = ENOENT;
		free(mod);
		return NULL;
	}
	else
		output_verbose("%s(%d): module '%s' loaded ok", __FILE__, __LINE__, file);

	/* get the initialization function */
	init = (LIBINIT)DLSYM(hLib,"init");
	if (init==NULL)
	{
		output_error("%s(%d): module '%s' does not export init()", __FILE__, __LINE__, file);
		dlload_error(pathname);
		errno = ENOEXEC;
		free(mod);
		return NULL;
	}
	else
		output_verbose("%s(%d): module '%s' exports init()", __FILE__, __LINE__, file);

	/* connect the module's exported data & functions */
	mod->hLib = (void*)hLib;
	pMajor = (int*)DLSYM(hLib, "major");
	pMinor = (int*)DLSYM(hLib, "minor");
	mod->major = pMajor?*pMajor:0;
	mod->minor = pMinor?*pMinor:0;
	mod->import_file = (int(*)(char*))DLSYM(hLib,"import_file");
	mod->export_file = (int(*)(char*))DLSYM(hLib,"export_file");
	mod->setvar = (int(*)(char*,char*))DLSYM(hLib,"setvar");
	mod->getvar = (void*(*)(char*,char*,unsigned int))DLSYM(hLib,"getvar");
	mod->check = (int(*)())DLSYM(hLib,"check");
#ifndef _NO_CPPUNIT
	mod->module_test = (int(*)(TEST_CALLBACKS*,int,char*[]))DLSYM(hLib,"module_test");
#endif
	mod->cmdargs = (int(*)(int,char**))DLSYM(hLib,"cmdargs");
	mod->kmldump = (int(*)(FILE*,OBJECT*))DLSYM(hLib,"kmldump");
	mod->subload = (MODULE *(*)(char *, MODULE **, CLASS **, int, char **))DLSYM(hLib, "subload");
	mod->test = (void(*)(int,char*[]))DLSYM(hLib,"test");
	mod->globals = NULL;
	strcpy(mod->name,file);
	mod->next = NULL;

	/* call the initialization function */
	mod->oclass = (*init)(&callbacks,(void*)mod,argc,argv);
	if (mod->oclass==NULL)
		return NULL;

	/* connect intrinsic functions */
	for (c=mod->oclass; c!=NULL; c=c->next) {
		char fname[1024];
		struct {
			FUNCTIONADDR *func;
			char *name;
			int optional;
		} map[] = {
			{&c->create,"create",FALSE},
			{&c->init,"init",TRUE},
			{&c->sync,"sync",TRUE},
			{&c->commit,"commit",TRUE},
			{&c->notify,"notify",TRUE},
			{&c->isa,"isa",TRUE},
			{&c->plc,"plc",TRUE},
			{&c->recalc,"recalc",TRUE},
		};
		int i;
		for (i=0; i<sizeof(map)/sizeof(map[0]); i++)
		{
			snprintf(fname, 1024,"%s_%s",map[i].name,isforeign?fmod:c->name);
			if ((*(map[i].func) = (FUNCTIONADDR)DLSYM(hLib,fname))==NULL && !map[i].optional)
			{
				output_fatal("intrinsic %s is not defined in class %s", fname,file);
				/*	TROUBLESHOOT
					A required intrinsic function was not found.  Please review and modify the class definition.
				 */
				errno=EINVAL;
				return NULL;
			}
			else
				if(!map[i].optional)
					output_verbose("%s(%d): module '%s' intrinsic %s found", __FILE__, __LINE__, file, fname);
		}
	}

	/* attach to list of known modules */
	if (first_module==NULL)
		first_module = mod;
	else
		last_module->next = mod;
	last_module = mod;
	return last_module;
}
Пример #21
0
STATUS original_test_start(int argc, char *argv[])
{
	OBJECT *obj[6];
	MODULE *network;
	CLASS *node, *link;
	MODULE *tape;
	CLASS *player, *recorder, *collector;

	network = module_load("network",argc,argv);
	if (network==NULL)
	{
#ifndef WIN32
		fprintf(stderr,"%s\n",dlerror());
#else
		perror("network module load failed");
#endif
		return FAILED;
	}
	output_verbose("network module loaded ok");

	node = class_get_class_from_classname("node");
	if (node==NULL)
	{
		output_fatal("network module does not implement class node");
		/*	TROUBLESHOOT
			The <b>network</b> module test can't find the <b>node</b>
			class definition.  This is probably caused by either
			an internal system error or a version of the network module
			that doesn't implement node object as expected (or at all).
		 */
		return FAILED;
	}
	output_verbose("class node implementation loaded ok");

	link = class_get_class_from_classname("link");
	if (node==NULL || link==NULL)
	{
		output_fatal("network module does not implement class link");
		/*	TROUBLESHOOT
			The <b>network</b> module test can't find the <b>link</b>
			class definition.  This is probably caused by either
			an internal system error or a version of the network module
			that doesn't implement link object as expected (or at all).
		 */
		return FAILED;
	}
	output_verbose("class link implementation loaded ok");

	tape = module_load("tape",argc,argv);
	if (tape==NULL)
	{
#ifndef WIN32
		fprintf(stderr,"%s\n",dlerror());
#else
		perror("tape module load failed");
#endif
		return FAILED;
	}

	player = class_get_class_from_classname("player");
	if (player==NULL)
	{
		output_fatal("tape module does not implement class player");
		/*	TROUBLESHOOT
			The <b>tape</b> module test can't find the <b>player</b>
			class definition.  This is probably caused by either
			an internal system error or a version of the tape module
			that doesn't implement player object as expected (or at all).
		 */
		return FAILED;
	}
	recorder = class_get_class_from_classname("recorder");
	if (recorder==NULL)
	{
		output_fatal("tape module does not implement class recorder");
		/*	TROUBLESHOOT
			The <b>tape</b> module test can't find the <b>recorder</b>
			class definition.  This is probably caused by either
			an internal system error or a version of the tape module
			that doesn't implement recorder object as expected (or at all).
		 */
		return FAILED;
	}
	collector = class_get_class_from_classname("collector");
	if (collector==NULL)
	{
		output_fatal("tape module does not implement class collector");
		/*	TROUBLESHOOT
			The <b>tape</b> module test can't find the <b>collector</b>
			class definition.  This is probably caused by either
			an internal system error or a version of the tape module
			that doesn't implement collector object as expected (or at all).
		 */
		return FAILED;
	}

	if (module_import(network,"../test/pnnl2bus.cdf")<=0)
		return FAILED;

	/* tape player */
	if ((*player->create)(&obj[3],object_get_first())==FAILED)
	{
		output_fatal("player creation failed");
		/*	TROUBLESHOOT
			The <b>tape</b> module test can't create a <b>player</b>
			object.  This is probably caused by either
			an internal system error or a version of the tape module
			that doesn't implement player object as expected (or at all).
		 */
		return FAILED;
	}
	object_set_value_by_name(obj[3],"loop","3600"); /* 18000 is about 12y at 1h steps */
	object_set_value_by_name(obj[3],"property","S");

	/* tape recorder */
	if ((*recorder->create)(&obj[4],object_get_first())==FAILED)
	{
		output_fatal("recorder creation failed");
		/*	TROUBLESHOOT
			The <b>tape</b> module test can't create a <b>recorder</b>
			object.  This is probably caused by either
			an internal system error or a version of the tape module
			that doesn't implement recorder object as expected (or at all).
		 */
		return FAILED;
	}
	object_set_value_by_name(obj[4],"property","V,S");
	object_set_value_by_name(obj[4],"interval","0");
	object_set_value_by_name(obj[4],"limit","1000");

	/* tape collector */
	if ((*collector->create)(&obj[5],NULL)==FAILED)
	{
		output_fatal("collector creation failed");
		/*	TROUBLESHOOT
			The <b>tape</b> module test can't create a <b>collector</b>
			object.  This is probably caused by either
			an internal system error or a version of the tape module
			that doesn't implement collector object as expected (or at all).
		 */
		return FAILED;
	}
	object_set_value_by_name(obj[5],"property","count(V.mag),min(V.mag),avg(V.mag),std(V.mag),max(V.mag),min(V.ang),avg(V.ang),std(V.ang),max(V.ang)");
	object_set_value_by_name(obj[5],"interval","0");
	object_set_value_by_name(obj[5],"limit","1000");
	object_set_value_by_name(obj[5],"group","class=node;");

	module_check(network);

	return SUCCESS;
}
Пример #22
0
void http_response(SOCKET fd)
{
	HTTP *http = http_create(fd);
	size_t len;
	int content_length = 0;
	char *user_agent = NULL;
	char *host = NULL;
	int keep_alive = 0;
	char *connection = NULL;
	char *accept = NULL;
	struct s_map {
		char *name;
		enum {INTEGER,STRING} type;
		void *value;
		int sz;
	} map[] = {
		{"Content-Length", INTEGER, (void*)&content_length, 0},
		{"Host", STRING, (void*)&host, 0},
		{"Keep-Alive", INTEGER, (void*)&keep_alive, 0},
		{"Connection", STRING, (void*)&connection, 0},
		{"Accept", STRING, (void*)&accept, 0},
	};

	while ( (int)(len=recv_data(fd,http->query,sizeof(http->query)))>0 )
	{
		/* first term is always the request */
		char *request = http->query;
		char method[32];
		char uri[1024];
		char version[32];
		char *p = strchr(http->query,'\r');
		int v;

		/* read the request string */
		if (sscanf(request,"%s %s %s",method,uri,version)!=3)
		{
			http_status(http,HTTP_BADREQUEST);
			http_format(http,HTTP_BADREQUEST);
			http_type(http,"text/html");
			http_send(http);
			break;
		}

		/* read the rest of the header */
		while (p!=NULL && (p=strchr(p,'\r'))!=NULL) 
		{
 			*p = '\0';
			p+=2;
			for ( v=0 ; v<sizeof(map)/sizeof(map[0]) ; v++ )
			{
				if (map[v].sz==0) map[v].sz = strlen(map[v].name);
				if (strnicmp(map[v].name,p,map[v].sz)==0 && strncmp(p+map[v].sz,": ",2)==0)
				{
					if (map[v].type==INTEGER) { *(int*)(map[v].value) = atoi(p+map[v].sz+2); break; }
					else if (map[v].type==STRING) { *(char**)map[v].value = p+map[v].sz+2; break; }
				}
			}
		}
		output_verbose("%s (host='%s', len=%d)",http->query,host?host:"???",content_length);

		/* reject anything but a GET */
		if (stricmp(method,"GET")!=0)
		{
			http_status(http,HTTP_METHODNOTALLOWED);
			http_format(http,HTTP_METHODNOTALLOWED);
			http_type(http,"text/html");
			/* technically, we should add an Allow entry to the response header */
			http_send(http);
			break;
		}

		/* handle request */
		if (strncmp(uri,"/gui/",5)==0 )
		{
			if ( http_gui_request(http,uri+5) )
				http_status(http,HTTP_OK);
			else
				http_status(http,HTTP_NOTFOUND);
			http_send(http);
		}
		else if (strncmp(uri,"/output/",8)==0 )
		{
			if ( http_output_request(http,uri+8) )
				http_status(http,HTTP_OK);
			else
				http_status(http,HTTP_NOTFOUND);
			http_send(http);
		}
		else if (strncmp(uri,"/action/",8)==0) 
		{
			if ( http_action_request(http,uri+8) )
				http_status(http,HTTP_ACCEPTED);
			else
				http_status(http,HTTP_NOTFOUND);
			http_send(http);
		}
		else if ( strcmp(uri,"/favicon.ico")==0 )
		{
			if ( http_favicon(http) )
				http_status(http,HTTP_OK);
			else
				http_status(http,HTTP_NOTFOUND);
			http_send(http);
		}
		else if (strncmp(uri,"/",1)==0 )
		{
			if ( http_xml_request(http,uri+1) )
				http_status(http,HTTP_OK);
			else
				http_status(http,HTTP_NOTFOUND);
			http_send(http);
		}
		else 
		{
			http_status(http,HTTP_NOTFOUND);
			http_format(http,HTTP_NOTFOUND);
			http_type(http,"text/html");
			http_send(http);
		}

		/* keep-alive not desired*/
		if (connection && stricmp(connection,"close")==0)
			break;
	}
	http_close(http);
	output_verbose("socket %d closed",http->s);
}
Пример #23
0
/** The main entry point of GridLAB-D
    @returns Exit codes XC_SUCCESS, etc. (see gridlabd.h)
 **/
int main(int argc, /**< the number entries on command-line argument list \p argv */
		 char *argv[]) /**< a list of pointers to the command-line arguments */
{
	char *pd1, *pd2;
	int i, pos=0;
	
	char *browser = getenv("GLBROWSER");

	/* set the default timezone */
	timestamp_set_tz(NULL);

	exec_clock(); /* initialize the wall clock */
	realtime_starttime(); /* mark start */
	
	/* set the process info */
	global_process_id = getpid();

	/* specify the default browser */
	if ( browser!= NULL )
		strncpy(global_browser,browser,sizeof(global_browser)-1);

#if defined WIN32 && _DEBUG 
	atexit(pause_at_exit);
#endif

#ifdef WIN32
	kill_starthandler();
	atexit(kill_stophandler);
#endif

	/* capture the execdir */
	strcpy(global_execname,argv[0]);
	strcpy(global_execdir,argv[0]);
	pd1 = strrchr(global_execdir,'/');
	pd2 = strrchr(global_execdir,'\\');
	if (pd1>pd2) *pd1='\0';
	else if (pd2>pd1) *pd2='\0';

	/* determine current working directory */
	getcwd(global_workdir,1024);

	/* capture the command line */
	for (i=0; i<argc; i++)
	{
		if (pos < (int)(sizeof(global_command_line)-strlen(argv[i])))
			pos += sprintf(global_command_line+pos,"%s%s",pos>0?" ":"",argv[i]);
	}

	/* main initialization */
	if (!output_init(argc,argv) || !exec_init())
		exit(XC_INIERR);

	/* set thread count equal to processor count if not passed on command-line */
	if (global_threadcount == 0)
		global_threadcount = processor_count();
	output_verbose("detected %d processor(s)", processor_count());
	output_verbose("using %d helper thread(s)", global_threadcount);

	/* process command line arguments */
	if (cmdarg_load(argc,argv)==FAILED)
	{
		output_fatal("shutdown after command line rejected");
		/*	TROUBLESHOOT
			The command line is not valid and the system did not
			complete its startup procedure.  Correct the problem
			with the command line and try again.
		 */
		exit(XC_ARGERR);
	}

	/* stitch clock */
	global_clock = global_starttime;

	/* initialize scheduler */
	sched_init(0);

	/* recheck threadcount in case user set it 0 */
	if (global_threadcount == 0)
	{
		global_threadcount = processor_count();
		output_verbose("using %d helper thread(s)", global_threadcount);
	}

	/* see if newer version is available */
	if ( global_check_version )
		check_version(1);

	/* setup the random number generator */
	random_init();

	/* pidfile */
	if (strcmp(global_pidfile,"")!=0)
	{
		FILE *fp = fopen(global_pidfile,"w");
		if (fp==NULL)
		{
			output_fatal("unable to create pidfile '%s'", global_pidfile);
			/*	TROUBLESHOOT
				The system must allow creation of the process id file at
				the location indicated in the message.  Create and/or
				modify access rights to the path for that file and try again.
			 */
			exit(XC_PRCERR);
		}
#ifdef WIN32
#define getpid _getpid
#endif
		fprintf(fp,"%d\n",getpid());
		output_verbose("process id %d written to %s", getpid(), global_pidfile);
		fclose(fp);
		atexit(delete_pidfile);
	}

	/* do legal stuff */
#ifdef LEGAL_NOTICE
	if (strcmp(global_pidfile,"")==0 && legal_notice()==FAILED)
		exit(XC_USRERR);
#endif
	
	/* start the processing environment */
	output_verbose("load time: %d sec", realtime_runtime());
	output_verbose("starting up %s environment", global_environment);
	if (environment_start(argc,argv)==FAILED)
	{
		output_fatal("environment startup failed: %s", strerror(errno));
		/*	TROUBLESHOOT
			The requested environment could not be started.  This usually
			follows a more specific message regarding the startup problem.
			Follow the recommendation for the indicated problem.
		 */
		if ( exec_getexitcode()==XC_SUCCESS )
			exec_setexitcode(XC_ENVERR);
	}

	/* save the model */
	if (strcmp(global_savefile,"")!=0)
	{
		if (saveall(global_savefile)==FAILED)
			output_error("save to '%s' failed", global_savefile);
	}

	/* do module dumps */
	if (global_dumpall!=FALSE)
	{
		output_verbose("dumping module data");
		module_dumpall();
	}

	/* KML output */
	if (strcmp(global_kmlfile,"")!=0)
		kml_dump(global_kmlfile);

	/* terminate */
	module_termall();

	/* wrap up */
	output_verbose("shutdown complete");

	/* profile results */
	if (global_profiler)
	{
		class_profiles();
		module_profiles();
	}

#ifdef DUMP_SCHEDULES
	/* dump a copy of the schedules for reference */
	schedule_dumpall("schedules.txt");
#endif

	/* restore locale */
	locale_pop();

	/* if pause enabled */
#ifndef WIN32
        if (global_pauseatexit) {
                output_verbose("pausing at exit");
		while (true) {
                        sleep(5);
                }
        }
#endif

	/* compute elapsed runtime */
	output_verbose("elapsed runtime %d seconds", realtime_runtime());
	output_verbose("exit code %d", exec_getexitcode());
	exit(exec_getexitcode());
}
Пример #24
0
void
isiout_write( fields *f, FILE *fp, param *p, unsigned long refnum )
{
        int type = get_type( f );

	if ( p->format_opts & BIBL_FORMAT_VERBOSE )
		output_verbose( f, refnum );

        output_type( fp, type );
	output_people( fp, f, "AUTHOR", "AU", 0 );
	output_easyall( fp, f, "AUTHOR:CORP", "AU", 0 );
	output_easyall( fp, f, "AUTHOR:ASIS", "AU", 0 );
/*      output_people( fp, f, "AUTHOR", "A2", 1 );
        output_people( fp, f, "AUTHOR:CORP", "A2", 1 );
        output_people( fp, f, "AUTHOR:ASIS", "A2", 1 );
        output_people( fp, f, "AUTHOR", "A3", 2 );
        output_people( fp, f, "AUTHOR:CORP", "A3", 2 );
        output_people( fp, f, "AUTHOR:ASIS", "A3", 2 );
        output_people( fp, f, "EDITOR", "ED", -1 );
	output_people( fp, f, "EDITOR:CORP", "ED", -1 );
        output_people( fp, f, "EDITOR:ASIS", "ED", -1 );*/
/*        output_date( fp, f, refnum );*/

        output_title( fp, f, "TI", 0 );
        if ( type==TYPE_ARTICLE ) {
		output_title( fp, f, "SO", 1 );
		output_abbrtitle( fp, f, "JI", 1 );
		output_title( fp, f, "SE", 2 );
	} else if ( type==TYPE_INBOOK ) {
		output_title( fp, f, "BT", 1 );
		output_title( fp, f, "SE", 2 );
	} else { /* type==BOOK */
		output_title( fp, f, "SE", 1 );
	}

	output_date( fp, f );
/*	output_easy( fp, f, "PARTMONTH", "PD", -1 );
	output_easy( fp, f, "PARTYEAR", "PY", -1 );*/

	output_easy( fp, f, "PAGESTART", "BP", -1 );
	output_easy( fp, f, "PAGEEND",   "EP", -1 );
        output_easy( fp, f, "ARTICLENUMBER", "AR", -1 );
        /* output article number as pages */
	output_easy( fp, f, "TOTALPAGES","PG", -1 );

        output_easy( fp, f, "VOLUME",    "VL", -1 );
        output_easy( fp, f, "ISSUE",     "IS", -1 );
        output_easy( fp, f, "NUMBER",    "IS", -1 );
	output_easy( fp, f, "DOI",       "DI", -1 );
	output_easy( fp, f, "ISIREFNUM", "UT", -1 );
	output_easy( fp, f, "LANGUAGE",  "LA", -1 );
	output_easy( fp, f, "ISIDELIVERNUM", "GA", -1 );
	output_keywords( fp, f );
	output_easy( fp, f, "ABSTRACT",  "AB", -1 );
	output_easy( fp, f, "TIMESCITED", "TC", -1 );
	output_easy( fp, f, "NUMBERREFS", "NR", -1 );
	output_easy( fp, f, "CITEDREFS",  "CR", -1 );
	output_easy( fp, f, "ADDRESS",    "PI", -1 );

/*        output_easy( fp, f, "PUBLISHER", "PB", -1 );
        output_easy( fp, f, "DEGREEGRANTOR", "PB", -1 );
        output_easy( fp, f, "ADDRESS", "CY", -1 );
        output_easy( fp, f, "ABSTRACT", "AB", -1 );
        output_easy( fp, f, "ISSN", "SN", -1 );
        output_easy( fp, f, "ISBN", "SN", -1 );
        output_easyall( fp, f, "URL", "UR", -1 );
        output_easyall( fp, f, "FILEATTACH", "UR", -1 );
        output_pubmed( fp, f, refnum );
        output_easyall( fp, f, "NOTES", "N1", -1 );
        output_easyall( fp, f, "REFNUM", "ID", -1 );*/
        fprintf( fp, "ER\n\n" );
        fflush( fp );
}
Пример #25
0
/** Process an incoming request
	@returns nothing
 **/
void http_response(SOCKET fd)
{
	HTTP *http = http_create(fd);
	size_t len;
	int content_length = 0;
	char *user_agent = NULL;
	char *host = NULL;
	int keep_alive = 0;
	char *connection = NULL;
	char *accept = NULL;
	struct s_map {
		char *name;
		enum {INTEGER,STRING} type;
		void *value;
		size_t sz;
	} map[] = {
		{"Content-Length", INTEGER, (void*)&content_length, 0},
		{"Host", STRING, (void*)&host, 0},
		{"Keep-Alive", INTEGER, (void*)&keep_alive, 0},
		{"Connection", STRING, (void*)&connection, 0},
		{"Accept", STRING, (void*)&accept, 0},
	};

	while ( (int)(len=recv_data(fd,http->query,sizeof(http->query)))>0 )
	{
		/* first term is always the request */
		char *request = http->query;
		char method[32];
		char uri[1024];
		char version[32];
		char *p = strchr(http->query,'\r');
		int v;
		
		/* initialize the response */
		http_reset(http);

		/* read the request string */
		if (sscanf(request,"%s %s %s",method,uri,version)!=3)
		{
			http_status(http,HTTP_BADREQUEST);
			http_format(http,HTTP_BADREQUEST);
			http_type(http,"text/html");
			http_send(http);
			break;
		}

		/* read the rest of the header */
		while (p!=NULL && (p=strchr(p,'\r'))!=NULL) 
		{
 			*p = '\0';
			p+=2;
			for ( v=0 ; v<sizeof(map)/sizeof(map[0]) ; v++ )
			{
				if (map[v].sz==0) map[v].sz = strlen(map[v].name);
				if (strnicmp(map[v].name,p,map[v].sz)==0 && strncmp(p+map[v].sz,": ",2)==0)
				{
					if (map[v].type==INTEGER) { *(int*)(map[v].value) = atoi(p+map[v].sz+2); break; }
					else if (map[v].type==STRING) { *(char**)map[v].value = p+map[v].sz+2; break; }
				}
			}
		}
		output_verbose("%s (host='%s', len=%d)",http->query,host?host:"???",content_length);

		/* reject anything but a GET */
		if (stricmp(method,"GET")!=0)
		{
			http_status(http,HTTP_METHODNOTALLOWED);
			http_format(http,HTTP_METHODNOTALLOWED);
			http_type(http,"text/html");
			/* technically, we should add an Allow entry to the response header */
			http_send(http);
			break;
		}

		/* handle request */
		if ( strcmp(uri,"/favicon.ico")==0 )
		{
			if ( http_favicon(http) )
				http_status(http,HTTP_OK);
			else
				http_status(http,HTTP_NOTFOUND);
			http_send(http);
		}
		else {
			static struct s_map {
				char *path;
				int (*request)(HTTP*,char*);
				char *success;
				char *failure;
			} map[] = {
				/* this is the map of recognize request types */
				{"/xml/",		http_xml_request,		HTTP_OK, HTTP_NOTFOUND},
				{"/gui/",		http_gui_request,		HTTP_OK, HTTP_NOTFOUND},
				{"/output/",	http_output_request,	HTTP_OK, HTTP_NOTFOUND},
				{"/action/",	http_action_request,	HTTP_ACCEPTED,HTTP_NOTFOUND},
				{"/rt/",		http_get_rt,			HTTP_OK, HTTP_NOTFOUND},
				{"/perl/",		http_run_perl,			HTTP_OK, HTTP_NOTFOUND},
				{"/gnuplot/",	http_run_gnuplot,		HTTP_OK, HTTP_NOTFOUND},
				{"/java/",		http_run_java,			HTTP_OK, HTTP_NOTFOUND},
				{"/python/",	http_run_python,		HTTP_OK, HTTP_NOTFOUND},
				{"/r/",			http_run_r,				HTTP_OK, HTTP_NOTFOUND},
				{"/scilab/",	http_run_scilab,		HTTP_OK, HTTP_NOTFOUND},
				{"/octave/",	http_run_octave,		HTTP_OK, HTTP_NOTFOUND},
			};
			int n;
			for ( n=0 ; n<sizeof(map)/sizeof(map[0]) ; n++ )
			{
				size_t len = strlen(map[n].path);
				if (strncmp(uri,map[n].path,len)==0)
				{
					if ( map[n].request(http,uri+len) )
						http_status(http,map[n].success);
					else
						http_status(http,map[n].failure);
					http_send(http);
					goto Next;
				}
			}
		}
		/* deprecated XML usage */
		if (strncmp(uri,"/",1)==0 )
		{
			if ( http_xml_request(http,uri+1) )
			{	
				output_warning("deprecate XML usage in request '%s'", uri);
				http_status(http,HTTP_OK);
			}
			else
				http_status(http,HTTP_NOTFOUND);
			http_send(http);
		}
		else 
		{
			http_status(http,HTTP_NOTFOUND);
			http_format(http,HTTP_NOTFOUND);
			http_type(http,"text/html");
			http_send(http);
		}

		/* keep-alive not desired*/
Next:
		if (connection && stricmp(connection,"close")==0)
			break;
	}
	http_close(http);
	output_verbose("socket %d closed",http->s);
}
Пример #26
0
glxlink::glxlink(char *filename)
{
	bool ok = true;
	globals = NULL;
	imports = NULL;
	exports = NULL;
	objects = NULL;
	handle = NULL;
	settag = NULL;
	init = NULL;
	sync = NULL;
	term = NULL;
	glxflags = 0;
	valid_to = 0;
	last_t = 0;

	FILE *fp = fopen(filename,"rt");
	if ( fp==NULL )
		throw "file open failed";
	output_debug("opened link '%s'", filename);

	char line[1024];
	int linenum=0;
	while ( fgets(line,sizeof(line),fp)!=NULL )
	{
		linenum++;
		if ( line[0]=='#' ) continue;
		char tag[64], data[1024]="";
		if ( sscanf(line,"%s %[^\r\n]",tag,data)>0 )
		{
			output_debug("%s(%d): %s %s", filename, linenum, tag,data);
			if ( settag!=NULL )
			{
				if ( strcmp(tag,"global")==0 )
				{
					add_global(data);
				}
				else if ( strcmp(tag,"object")==0 )
				{
					add_object(data);
				}
				else if ( strcmp(tag,"export")==0 )
				{
					add_export(data);
				}
				else if ( strcmp(tag,"import")==0 )
				{
					add_import(data);
				}
				else if ( !(*settag)(this,tag,data) )
					output_error("%s(%d): tag '%s' not accepted", filename, linenum, tag);
			}
			else if ( strcmp(tag,"target")==0)
			{
				if ( !set_target(data) )
				{
					output_error("%s(%d): target '%s' is not valid", filename, linenum, data);
					ok = false;
				}
			}
			else
				output_warning("%s(%d): tag '%s' cannot be processed until target module is loaded", filename, linenum, tag);
		}
	}

	fclose(fp);

	// append to link list
	next = first;
	first = this;

	if ( ok )
		output_verbose("link '%s' ok", filename);
	else
		throw "cannot establish link";
}
Пример #27
0
/** Insert an item into an index
	@return STATUS on SUCCESS, FAILED otherwise
 **/
STATUS index_insert(INDEX *index,	/**< the index to which the item is added */
					void *data,		/**< a pointer to the item to be added */
					int ordinal)	/**< the ordinal to which the item belongs */
{
	int pos = ordinal - index->first_ordinal;

	if (ordinal<index->first_ordinal) /* grow on bottom end */
	{
		/** @todo allow resizing indexes when ordinal is before first (ticket #28) */
		/* (this is very unusual and shouldn't happen the way things are now) */
		output_fatal("ordinal %d is too small (first is %d)",ordinal, index->first_ordinal);
		/*	TROUBLESHOOT
			This is an internal error caused by an attempt to index something improperly.
			Because the indexing system start at index 0, this means a negative index
			number was attempting, which is most likely a bug.  This usually occurs
			during object initialization and might be caused by invalid object numbers,
			either negative or greater than about 2 billion.  If your model is using a
			the <b><i>class</i>:<i>id</i></b> naming convention, check the object id numbers
			to make sure they are correct.
		*/
		errno = EINVAL;
		return FAILED;
	}
	else if (ordinal>=index->last_ordinal) /* grow on to end */
	{	
		int oldsize = index->last_ordinal - index->first_ordinal;
		int newsize = oldsize;
		GLLIST **newblock = NULL;
		while (ordinal >= index->first_ordinal + newsize)
			newsize *= 2;	/* double until it fits */
		newblock = malloc(sizeof(GLLIST*)*newsize);
		if (newblock==NULL)
		{
			output_fatal("unable to grow index %d: %s",index->id, strerror(errno));
			/*	TROUBLESHOOT
				An internal memory allocation error cause an index operation to fail.
				The message will usually include some explanation as to what cause
				the failure.  Remedy the indicated memory problem to fix the indexing problem.
			*/
			return FAILED;
		}
		output_verbose("growing index %d to %d ordinals", index->id, newsize);
		memset(newblock,0,sizeof(GLLIST*)*newsize);
		memcpy(newblock,index->ordinal,sizeof(GLLIST*)*oldsize);
		free(index->ordinal);
		index->ordinal = newblock;
		index->last_ordinal = index->first_ordinal + newsize;
	
	}
	if (index->ordinal[pos]==NULL) /* new list at ordinal */
	{
		index->ordinal[pos] = list_create();
		if (index->ordinal[pos]==NULL)
			return FAILED;
	}
	if (list_append(index->ordinal[pos],data)==NULL)
		return FAILED;
	if (ordinal<index->first_used) index->first_used=ordinal;
	if (ordinal>index->last_used) index->last_used=ordinal;
	return SUCCESS;
}
Пример #28
0
/** Load a timezone from the timezone info file
 **/
void load_tzspecs(char *tz){
	char filepath[1024];
	char *pTzname = 0;
	FILE *fp = NULL;
	char buffer[1024];
	int linenum = 0;
	int year = YEAR0;
	int y;
	int found;

	found = 0;
	tzvalid = 0;
	pTzname = tz_name(tz);

	if(pTzname == 0){
		THROW("timezone '%s' was not understood by tz_name.", tz);
		/* TROUBLESHOOT
			The specific timezone is not valid.
			Try using a valid timezone or add the desired timezone to the timezone file <code>.../etc/tzinfo.txt</code> and try again.
		 */
	}

	strncpy(current_tzname, pTzname, sizeof(current_tzname));
	tzoffset = tz_offset(current_tzname);
	strncpy(tzstd, tz_std(current_tzname), sizeof(tzstd));
	strncpy(tzdst, tz_dst(current_tzname), sizeof(tzdst));

	if(find_file(TZFILE, NULL, R_OK,filepath,sizeof(filepath)) == NULL){
		THROW("timezone specification file %s not found in GLPATH=%s: %s", TZFILE, getenv("GLPATH"), strerror(errno));
		/* TROUBLESHOOT
			The system could not locate the timezone file <code>tzinfo.txt</code>.
			Check that the <code>etc</code> folder is included in the '''GLPATH''' environment variable and try again.
		 */
	}

	fp = fopen(filepath,"r");

	if(fp == NULL){
		THROW("%s: access denied: %s", filepath, strerror(errno));
		/* TROUBLESHOOT
			The system was unable to read the timezone file.  Check that the file has the correct permissions and try again.
		 */
	}

	// zero previous DST start/end times
	for (y = 0; y < sizeof(tszero) / sizeof(tszero[0]); y++){
		dststart[y] = dstend[y] = -1;
	}

	while(fgets(buffer,sizeof(buffer),fp)){
		char *p = NULL;
		char tzname[32];
		SPEC start, end;
		int form = -1;

		linenum++;

		/* wipe comments */
		p = strchr(buffer,';');

		if(p != NULL){
			*p = '\0';
		}

		/* remove trailing whitespace */
		p = buffer + strlen(buffer) - 1;

		while (iswspace(*p) && p > buffer){
			*p-- = '\0';
		}

		/* ignore blank lines or lines starting with white space*/
		if (buffer[0] == '\0' || iswspace(buffer[0])){
			continue;
		}

		/* year section */
		if(sscanf(buffer, "[%d]", &year) == 1){
			continue;
		}

		/* TZ spec */
		form = sscanf(buffer, "%[^,],M%d.%d.%d/%d:%d,M%d.%d.%d/%d:%d", tzname,
			&start.month, &start.nth, &start.day, &start.hour, &start.minute,
			&end.month, &end.nth, &end.day, &end.hour, &end.minute);

		/* load only TZ requested */
		pTzname = tz_name(tzname);

		if (tz != NULL && pTzname != NULL && strcmp(pTzname,current_tzname) != 0){
			continue;
		}

		if(form == 1){ /* no DST */
			set_tzspec(year, current_tzname, NULL, NULL);
			found = 1;
		} else if(form == 11) { /* full DST spec */
			set_tzspec(year, current_tzname, &start, &end);
			found = 1;
		} else {
			THROW("%s(%d): %s is not a valid timezone spec", filepath, linenum, buffer);
			/* TROUBLESHOOT
				The timezone specification is not valid.  Verify the syntax of the timezone spec and that it is defined in the timezone file
				<code>.../etc/tzinfo.txt</code> or add it, and try again.
			 */
		}
	}

	if(found == 0){
		output_warning("%s(%d): timezone spec '%s' not found in 'tzinfo.txt', will include no DST information", filepath, linenum, current_tzname);
	}

	if(ferror(fp)){
		output_error("%s(%d): %s", filepath, linenum, strerror(errno));
	} else {
		output_verbose("%s loaded ok", filepath);
	}

	fclose(fp);
	tzvalid = 1;
}
Пример #29
0
/** The main entry point of GridLAB-D
 Exit codes
 - \b 0 run completed ok
 - \b 1 command-line processor stopped
 - \b 2 environment startup failed
 - \b 3 test procedure failed
 - \b 4 user rejects conditions of use
 - \b 5 simulation stopped before completing
 - \b 6 initialization failed
 **/
int main(int argc, /**< the number entries on command-line argument list \p argv */
		 char *argv[]) /**< a list of pointers to the command-line arguments */
{
	int rv = 0;
	time_t t_load = time(NULL);
	global_process_id = getpid();
#if defined WIN32 && _DEBUG 
	atexit(pause_at_exit);
#endif
	/* main initialization */
	if (!output_init(argc,argv) || !exec_init())
		exit(6);

	/* process command line arguments */
	if (cmdarg_load(argc,argv)==FAILED)
	{
		output_fatal("shutdown after command line rejected");
		/*	TROUBLESHOOT
			The command line is not valid and the system did not
			complete its startup procedure.  Correct the problem
			with the command line and try again.
		 */
		exit(1);
	}

	/* setup the random number generator */
	random_init();

	/* pidfile */
	if (strcmp(global_pidfile,"")!=0)
	{
		FILE *fp = fopen(global_pidfile,"w");
		if (fp==NULL)
		{
			output_fatal("unable to create pidfile '%s'", global_pidfile);
			/*	TROUBLESHOOT
				The system must allow creation of the process id file at
				the location indicated in the message.  Create and/or
				modify access rights to the path for that file and try again.
			 */
			exit(1);
		}
#ifdef WIN32
#define getpid _getpid
#endif
		fprintf(fp,"%d\n",getpid());
		output_verbose("process id %d written to %s", getpid(), global_pidfile);
		fclose(fp);
		atexit(delete_pidfile);
	}

	/* do legal stuff */
#ifdef LEGAL_NOTICE
	if (strcmp(global_pidfile,"")==0 && legal_notice()==FAILED)
		exit(4);
#endif

	/* set up the test */
	if (global_test_mode)
	{
#ifndef _NO_CPPUNIT
		output_message("Entering test mode");
		if (test_start(argc,argv)==FAILED)
		{
			output_fatal("shutdown after startup test failed");
			/*	TROUBLESHOOT
				A self-test procedure failed and the system stopped.
				Check the output of the test stream and correct the 
				indicated problem.  If the test stream is not redirected
				so as to save the output, try using the <b>--redirect</b>
				command line option.
			 */
			exit(3);
		}
		exit(0); /* There is no environment to speak of, so exit. */
#else
		output_message("Unit Tests not enabled.  Recompile with _NO_CPPUNIT unset");
#endif
	}
	
	/* start the processing environment */
	output_verbose("load time: %d sec", time(NULL) - t_load);
	output_verbose("starting up %s environment", global_environment);
	if (environment_start(argc,argv)==FAILED)
	{
		output_fatal("environment startup failed: %s", strerror(errno));
		/*	TROUBLESHOOT
			The requested environment could not be started.  This usually
			follows a more specific message regarding the startup problem.
			Follow the recommendation for the indicated problem.
		 */
		rv = 2;
	}

	/* post process the test */
	if (global_test_mode)
	{
#ifndef _NO_CPPUNIT
		output_message("Exiting test mode");
		if (test_end(argc,argv)==FAILED)
		{
			output_error("shutdown after end test failed");
			exit(3);
		}
#endif
	}

	/* save the model */
	if (strcmp(global_savefile,"")!=0)
	{
		if (saveall(global_savefile)==FAILED)
			output_error("save to '%s' failed", global_savefile);
	}

	/* do module dumps */
	if (global_dumpall!=FALSE)
	{
		output_verbose("dumping module data");
		module_dumpall();
	}

	/* KML output */
	if (strcmp(global_kmlfile,"")!=0)
		kml_dump(global_kmlfile);

	/* wrap up */
	output_verbose("shutdown complete");

	/* profile results */
	if (global_profiler)
		class_profiles();

	/* restore locale */
	locale_pop();

	/* compute elapsed runtime */
	output_verbose("elapsed runtime %d seconds", realtime_runtime());

	exit(rv);
}
Пример #30
0
void cmex_module(int nlhs, mxArray *plhs[], /**< () */
				   int nrhs, const mxArray *prhs[] ) /**< (modulename) */
{
	if (nrhs>0)
	{
		char fname[1024];
		MODULE *mod;
		if (!mxIsChar(prhs[0]))
			output_error("Module name is not a string");
		else if (nlhs>1)
			output_error("Only one return value is possible");
		else if (mxGetString(prhs[0],fname,sizeof(fname))!=0)
			output_error("Module name too long");
		else if ((mod=module_find(fname))==NULL && (mod=module_load(fname,0,NULL))==NULL)
			output_error("Module load failed");
		else if (nlhs=0)
			output_message("Module '%s(%d.%d)' loaded ok", mod->name, mod->major, mod->minor);
		else
		{
			/* set the standard info */
			char *fnames[256] = {"handle","name","major","minor"};
			mxArray *name = mxCreateString(mod->name);
			mxArray *handle = mxCreateNumericMatrix(1,1,sizeof(int32)==sizeof(int)?mxUINT32_CLASS:mxUINT64_CLASS,mxREAL);
			mxArray *major = mxCreateNumericMatrix(1,1,mxUINT8_CLASS,mxREAL);
			mxArray *minor = mxCreateNumericMatrix(1,1,mxUINT8_CLASS,mxREAL);
			mxArray *value[256];
			unsigned int64 *pHandle = mxGetData(handle);
			unsigned char *pMajor = mxGetData(major);
			unsigned char *pMinor = mxGetData(minor);
			char32 varname="";
			int nFields=4;
			char vnames[256][32];
			*pHandle = (unsigned int64)mod->hLib;
			*pMajor = (unsigned char)mod->major;
			*pMinor = (unsigned char)mod->minor;

			/* get the module data */
			while (module_getvar(mod,varname,NULL,0))
			{
				char32 buffer;
				if (module_getvar(mod,varname,buffer,sizeof(buffer)) && nFields<sizeof(fname)/sizeof(fname[0]))
				{
					double *pVal;
					output_verbose("module variable %s = '%s'", varname, buffer);
					value[nFields] = mxCreateDoubleMatrix(1,1,mxREAL);
					pVal = mxGetPr(value[nFields]);
					*pVal = atof(buffer);
					strcpy(vnames[nFields],varname);
					fnames[nFields] = vnames[nFields];
					nFields++;
				}
			}

			/* construct the result */
			plhs[0] = mxCreateStructMatrix(1,1,nFields,fnames);
			mxSetFieldByNumber(plhs[0],0,0,handle);
			mxSetFieldByNumber(plhs[0],0,1,name);
			mxSetFieldByNumber(plhs[0],0,2,major);
			mxSetFieldByNumber(plhs[0],0,3,minor);
			while (nFields-->4)
				mxSetFieldByNumber(plhs[0],0,nFields,value[nFields]);

		}
	}
	else
		output_error("Module not specified");
	return;
}