/**
 * Probe the file system for existing files. Determine
 * the first number which is unused, or the number of the oldest
 * file if all numbers are used.
 * @return the first file number to use (starting at 0), or -1 on failure
 */
intptr_t 
MM_VerboseWriterFileLogging::findInitialFile(MM_EnvironmentBase *env)
{
	OMRPORT_ACCESS_FROM_OMRPORT(env->getPortLibrary());
	MM_GCExtensionsBase *extensions = MM_GCExtensionsBase::getExtensions(env->getOmrVM());
	int64_t oldestTime = J9CONST64(0x7FFFFFFFFFFFFFFF); /* the highest possible time. */
	intptr_t oldestFile = 0;

	if (_mode != rotating_files) {
		/* nothing to do */
		return 0;
	}

	for (uintptr_t currentFile = 0; currentFile < _numFiles; currentFile++) {
		char *filenameToOpen = expandFilename(env, currentFile);
		if (NULL == filenameToOpen) {
			return -1;
		}

		int64_t thisTime = omrfile_lastmod(filenameToOpen);
		extensions->getForge()->free(filenameToOpen);
		
		if (thisTime < 0) {
			/* file doesn't exist, or some other problem reading the file */
			oldestFile = currentFile;
			break;
		} else if (thisTime < oldestTime) {
			oldestTime = thisTime;
			oldestFile = currentFile;
		}
	}
	
	return oldestFile; 
}
/**
 * Opens the file to log output to and prints the header.
 * @return true on sucess, false otherwise
 */
bool
MM_VerboseWriterFileLoggingSynchronous::openFile(MM_EnvironmentBase *env)
{
	OMRPORT_ACCESS_FROM_OMRPORT(env->getPortLibrary());
	MM_GCExtensionsBase* extensions = env->getExtensions();
	const char* version = omrgc_get_version(env->getOmrVM());
	
	char *filenameToOpen = expandFilename(env, _currentFile);
	if (NULL == filenameToOpen) {
		return false;
	}
	
	_logFileDescriptor = omrfile_open(filenameToOpen, EsOpenRead | EsOpenWrite | EsOpenCreate | EsOpenTruncate, 0666);
	if(-1 == _logFileDescriptor) {
		char *cursor = filenameToOpen;
		/**
		 * This may have failed due to directories in the path not being available.
		 * Try to create these directories and attempt to open again before failing.
		 */
		while ( (cursor = strchr(++cursor, DIR_SEPARATOR)) != NULL ) {
			*cursor = '\0';
			omrfile_mkdir(filenameToOpen);
			*cursor = DIR_SEPARATOR;
		}

		/* Try again */
		_logFileDescriptor = omrfile_open(filenameToOpen, EsOpenRead | EsOpenWrite | EsOpenCreate | EsOpenTruncate, 0666);
		if (-1 == _logFileDescriptor) {
			_manager->handleFileOpenError(env, filenameToOpen);
			extensions->getForge()->free(filenameToOpen);
			return false;
		}
	}

	extensions->getForge()->free(filenameToOpen);
	
	omrfile_printf(_logFileDescriptor, getHeader(env), version);
	
	return true;
}
Example #3
0
File: fselect.c Project: dyne/MuSE
/*
 * This function sets the information inside the file selector.
 */
void setCDKFselect (CDKFSELECT *fselect, char *directory, chtype fieldAttrib, chtype filler, chtype highlight, char *dirAttribute, char *fileAttribute, char *linkAttribute, char *sockAttribute, boolean Box GCC_UNUSED)
{
   /* Declare local variables. */
   CDKSCROLL *fscroll	= fselect->scrollField;
   CDKENTRY *fentry	= fselect->entryField;
   char *tempDir	= 0;
   char *mesg[10], newDirectory[2000], temp[100];
   int ret;

   /* Keep the info sent to us. */
   fselect->fieldAttribute	= fieldAttrib;
   fselect->fillerCharacter	= filler;
   fselect->highlight		= highlight;
   strcpy (newDirectory, directory);

   /* Set the attributes of the entry field/scrolling list. */
   setCDKEntryFillerChar (fentry, filler);
   setCDKScrollHighlight (fscroll, highlight);

   /* Only do the directory stuff if the directory is not null. */
   if (directory != 0)
   {
      /* Try to expand the directory if it starts with a ~ */
      if (directory[0] == '~')
      {
	 tempDir = expandFilename (directory);
	 if (tempDir != 0)
	 {
	    strcpy (newDirectory, tempDir);
	    freeChar (tempDir);
	 }
      }

      /* Change directories. */
      ret = chdir (newDirectory);
      if (ret != 0)
      {
	 /* Beep at them. */
	 Beep();

	 /* Couldn't get into the directory, pop up a little message. */
	 sprintf (temp, "<C>Could not change into %s", newDirectory);
	 mesg[0] = copyChar (temp);

#ifdef HAVE_STRERROR
	 sprintf (temp, "<C></U>%s", strerror(errno));
	 mesg[1] = copyChar (temp);
#else
	 sprintf (temp, "<C></U>Unknown reason.");
	 mesg[1] = copyChar (temp);
#endif

	 mesg[2] = " ";
	 mesg[3] = "<C>Press Any Key To Continue.";

	 /* Pop Up a message. */
	 popupLabel (ScreenOf(fselect), mesg, 4);

	 /* Clean up some memory. */
	 freeCharList (mesg, 4);

	 /* Get out of here. */
	 eraseCDKFselect (fselect);
	 drawCDKFselect (fselect, ObjOf(fselect)->box);
	 return;
      }
   }

   /*
    * If the information coming in is the same as the information
    * that is already there, there is no need to destroy it.
    */
   if (fselect->pwd != directory)
   {
      setPWD(fselect);
   }
   if (fselect->fileAttribute != fileAttribute)
   {
      /* Remove the old pointer and set the new value. */
      freeChar (fselect->fileAttribute);
      fselect->fileAttribute = copyChar (fileAttribute);
   }
   if (fselect->dirAttribute != dirAttribute)
   {
      /* Remove the old pointer and set the new value. */
      freeChar (fselect->dirAttribute);
      fselect->dirAttribute = copyChar (dirAttribute);
   }
   if (fselect->linkAttribute != linkAttribute)
   {
      /* Remove the old pointer and set the new value. */
      freeChar (fselect->linkAttribute);
      fselect->linkAttribute = copyChar (linkAttribute);
   }
   if (fselect->sockAttribute != sockAttribute)
   {
      /* Remove the old pointer and set the new value. */
      freeChar (fselect->sockAttribute);
      fselect->sockAttribute = copyChar (sockAttribute);
   }

   /* Set the contents of the entry field. */
   setCDKEntryValue (fentry, fselect->pwd);
   drawCDKEntry (fentry, ObjOf(fentry)->box);

   /* Get the directory contents. */
   if (setCDKFselectDirContents (fselect) == 0)
   {
      Beep();
      return;
   }

   /* Set the values in the scrolling list. */
   setCDKScrollItems (fscroll,
			fselect->dirContents,
			fselect->fileCounter,
			FALSE);
}
Example #4
0
void handleConnection(int socketfd)  {
	static char buffer[BUFFER_SIZE+1];
	static char* headers[HEADER_LIMIT+1];
	int i;
	int headerCount=0;
	//int requestSize = read(socketfd,buffer,BUFFER_SIZE);
	int requestSize = readUntil(socketfd,crlfcrlfCheck,buffer,BUFFER_SIZE);
	if (requestSize ==0 || requestSize == -1) {
		fail("failed to read browser request");		
	}
	logText(buffer);
	int done = 0;
	char mode = 0; /*  */
	for (i=0;i<requestSize;i++) {
		switch(mode) {
			case '\r':  
				if (buffer[i] == '\n') {
					buffer[i-1]=0;
					mode=0;
					done = (*headers[headerCount]==0) || (headerCount++ == HEADER_LIMIT);
				}
				break;
			case 0:
			  headers[headerCount]=&buffer[i]; 
			default:
			  mode=buffer[i];
			  if (mode==0) done=1;  /* catch headers containing zeros */
		}
		if (done) break;
	}
	int bodyStart=i+1;
  int bodyLength=requestSize-bodyStart;
  
	headers[headerCount]=NULL; /*null terminated list*/

  logFormat("%d header lines\n",headerCount);
	logText("we got some headers");
	for (i=0; i<headerCount;i++) {
		logFormat("%d: %s\n",i,headers[i]);
	}
	logText("That was them headers");
	
	/*
	logText("looking for User-Agent:");	
	char* userAgent=findHeader(0,headerCount,headers,"User-Agent:");
	if (userAgent==NULL) {logText("No User-Agent");} else	{logText(userAgent);}
	*/
	
	char* aCookie = findHeader(0,headerCount,headers,"Cookie:");
	int uid=getUserInfo(aCookie);
  logFormat("uid of %d\n",uid);
	
	if (uid <= 0) {
		if (strncmp("POST /login ",headers[0],12) == 0 ) {
			 //for a non-logged-in user POST to /login try and read user credentials.  
			logText("Login request received");
			char userpass[300];
			struct passwd* pwd = NULL;
			strncpy(userpass,&buffer[bodyStart],300);			
			if (userpass[299] == 0) {
				char* user = NULL;
				char* pass = NULL;
				user = strstr(userpass,"user="******"pass="******"I think the userName is '%s'\n",user);
				//logFormat("I think the passWord is '%s'\n",pass);				
				pwd = checkUserPass(user,pass);
				free(pass);				
			}
			char* resultPage;
			if (pwd != NULL) {
				logText("setting cookie");
				char token[33];
				token[32]='\0';
				makeAuthenticationToken(pwd->pw_uid,token,32); 
				
				char* pageHeaders;
				asprintf(&pageHeaders,"Set-Cookie: %s; Secure; HttpOnly\r\nLocation: %s\r\n",token,loginRedirect);
				logText(pageHeaders);
				resultPage=
				"<html><head></head><body"
					"<div>Login Successful</div>"
				"</body></html>";
				sendHTMLPage(socketfd,"303 See Other",pageHeaders,resultPage);
				free(pageHeaders);
			} else {
				resultPage=
				"<html><head></head><body"
					"<div>Login Failed</div>"
				"</body></html>";				
				sendSimpleHTMLPage(socketfd,"401 Unauthorised",resultPage);
			}			
		} else {
			sendLoginPage(socketfd);
		}
	}	else {			
		struct passwd *pw = getpwuid(uid);
		setgid(uid);
		setuid(uid);
		setenv("HOME",pw->pw_dir,1);
		setenv("USER",pw->pw_name,1);
		setenv("SHELL",pw->pw_shell,1);
		//if we get to here, the request sent a token identifying them as a 
		//valid user and we have dropped privileges to be that user.
		//now we can set about serving the user request.
#ifdef NOTANOS 
		//support for a notanos websocket server.  
		char* upgrade = findHeader(0,headerCount,headers,"Upgrade:");
		if (upgrade) {
			 //Try using websockets
			 char* websocket_key = findHeader(0,headerCount,headers,"Sec-WebSocket-Key:");
			 char* websocket_protocol = findHeader(0,headerCount,headers,"Sec-WebSocket-Protocol:");
			 char* websocket_version = findHeader(0,headerCount,headers,"Sec-WebSocket-Version:");
			 char* origin = findHeader(0,headerCount,headers,"Origin:");
			 webSocketUpgrade(socketfd,websocket_key,websocket_protocol,websocket_version,origin);
			 //webSocketUpgrade should never return
		} 
#endif		
		if (strncmp("GET ",headers[0],4) == 0 ) {
			char* nameStart=headers[0]+4;
			int nameLen = strcspn(nameStart," ");
			char* urlName=strndup(nameStart,nameLen);
			char* fileName=url_decode(urlName);
			char* queryStart=strchr(fileName,'?');
			if (queryStart != NULL) *queryStart++='\0';
			
			logFormat("url request '%s'\n",urlName);
			logFormat("filename request '%s'\n",fileName);
			char* newFileName=expandFilename(fileName);
			free(fileName); fileName=newFileName;
			char* contentType=getContentType(fileName);
			struct stat fileInfo;
			int res=stat(fileName,&fileInfo);
			if (res !=0)  {
				if (errno == EACCES) {
					sendSimpleHTMLPage(socketfd,"403 Forbidden","403: Forbidden");
				} else {
					sendSimpleHTMLPage(socketfd,"404 Not Found","404: Not Found");
				}
			}	else {
				if (S_ISREG(fileInfo.st_mode)) {
					int filefd=open(fileName,O_RDONLY);
					if (filefd < 0) {
						sendSimpleHTMLPage(socketfd,"403 Forbidden","403: Forbidden");
					} else {
						sendFileChunked(socketfd,"200 OK",filefd,contentType);
						close(filefd);
					}
				}
				else if (S_ISDIR(fileInfo.st_mode)) {
					char* command;
					char* awkline = "BEGIN {printf(\"{\\\"path\\\":\\\"%s\\\",\\n \\\"contents\\\":[\\n\",path)} END{print\"\\n  ]\\n};\\n\"}  NR > 2 { printf(\",\\n\") } NR >1 { printf(\"    {\\\"filename\\\":\\\"%s\\\", \\\"attributes\\\":\\\"%s\\\", \\\"owner\\\":\\\"%s\\\", \\\"size\\\":%s}\", $9, $1, $3, $5) }";
					//int commandLength = asprintf(&command,"ls -AlQ %s|  awk -v path=%s '%s'",fileName,fileName,awkline);
					int commandLength = asprintf(&command,"./jsondir '%s'",fileName);
					logText(command);
					if (commandLength>0) {
						FILE* commandPipe = popen(command,"r");
						if (commandPipe) { 
							int commandfd=(fileno(commandPipe));
							sendFileChunked(socketfd,"200 OK",commandfd,"application/json");
							pclose(commandPipe);
						} else {
							sendSimpleHTMLPage(socketfd,"500 Internal Server Error","popen failure");
						}
						free(command);
					} else {
						sendSimpleHTMLPage(socketfd,"200 OK","That's a directory");
					}  
				}

			}
			free(fileName);
			free(contentType);
			free(urlName);
		}
	}
	logText("done response, closing connection");
	sleep(1);
	close(socketfd);
	exit(1);
}