示例#1
0
文件: userserv.c 项目: Lerc/userserv
char* expandFilename(const char* original) {
	char* home = getenv("HOME");
	logFormat("$HOME is %s\n",home);
	if (strcmp(original,"/~")==0) return strdup(home);
	if (strncmp(original,"/~/",3)==0) {
		char* result;
		int len=asprintf(&result,"%s%s",home,original+2);
		return(result);
	}
	return strdup(original);	
}
示例#2
0
文件: log.cpp 项目: whztt07/Magic3D-2
void Magic3D::Log::logMatrix(LOG type, float* matrix)
{
    float* value = matrix;
    for (int r = 0; r < 4; r++)
    {
        float v0 = *value; value++;
        float v1 = *value; value++;
        float v2 = *value; value++;
        float v3 = *value; value++;
        logFormat(type, "%8.9f, %8.9f, %8.9f, %8.9f", v0, v1, v2, v3);
    }
}
示例#3
0
文件: engine.cpp 项目: eledot/Plum
    void Engine::Impl::quit(const std::string& message)
    {
        if(message.length())
        {
            fprintf(stderr, "Exit Requested: %s", message.c_str());
            logFormat("Exit Requested: %s", message.c_str());
#ifdef _WIN32
            MessageBoxA(nullptr, message.c_str(), "Exit Requested", MB_SYSTEMMODAL);
#endif
            throw SystemExit(1);
        }
        throw SystemExit(0);
    }
            VerificationContext::VerificationContext()
            {
                interventionOnErrorColor_ = VVL_GUI_RED;
                interventionOnSuccessColor_ = VVL_GUI_BLUE;
                interventionOnError_ = VVL_GUI_HIGHLIGHT_ERROR | VVL_GUI_SHOW_ERROR_RULES;
                interventionOnSuccess_ = VVL_GUI_CLEAR;
                triggerStopEvents_=csu::vvl::framework::VVL_EVENT_MOUSECLICK;
                triggerWatchEvents_=csu::vvl::framework::VVL_EVENT_FOCUSOUT;
                updateRuleTime_=4;

                //log stuff
                //addLogOutputStream(std::cout);
                logFiles_.clear();
                logFormat("[%tm] %wi at %en: %vr");

            }
示例#5
0
// Main program loop
int Convertor::start()
{
    out << tr("Contact convertor by Mikhail Y. Zvyozdochkin\n");
    // Parse command line
    if (arguments().count()<2) {
        printUsage();
        return 1;
    }
    QString inPath, outPath, outFormat;
    bool forceOverwrite = false;
    bool forceSingleFile = false;
    bool forceDirectory = false;
    for (int i=1; i<arguments().count(); i++) {
        if (arguments()[i]=="-i") {
            i++;
            if (i==arguments().count()) {
                out << tr("linvert error: -i option present, but file path is missing\n");
                printUsage();
                return 2;
            }
            inPath = arguments()[i];
            continue;
        }
        else if (arguments()[i]=="-o") {
            i++;
            if (i==arguments().count()) {
                out << tr("linvert error: -o option present, but file path is missing\n");
                printUsage();
                return 3;
            }
            outPath = arguments()[i];
            continue;
        }
        else if (arguments()[i]=="-f") {
            i++;
            if (i==arguments().count()) {
                out << tr("linvert error: -f option present, but format name is missing\n");
                printUsage();
                return 4;
            }
            outFormat = arguments()[i];
            if (outFormat!="vcf21" && outFormat!="vcf30" && outFormat!="vcfauto" && outFormat!="udx" && outFormat!="copy") {
                out << tr("Unknown output format: %1\n").arg(outFormat);
                printUsage();
                return 5;
            }
            continue;
        }
        else if (arguments()[i]=="-w")
            forceOverwrite = true;
        else if (arguments()[i]=="-s")
            forceSingleFile = true;
        else if (arguments()[i]=="-d")
            forceDirectory = true;
        else {
            out << tr("Unknown option: %1\n").arg(arguments()[i]);
            printUsage();
            return 6;
        }
    }
    // Check input data completion
    if (inPath.isEmpty()) {
        out << tr("Input path is missing\n");
        printUsage();
        return 7;
    }
    if (outPath.isEmpty()) {
        out << tr("Output path is missing\n");
        printUsage();
        return 8;
    }
    if (outFormat.isEmpty()) {
        out << tr("Output format name is missing\n");
        printUsage();
        return 9;
    }
    if (forceSingleFile && forceDirectory) {
        out << tr("Options -s and -d are not compatible\n");
        printUsage();
        return 10;
    }
    if (forceDirectory && !outFormat.contains("vcf") && outFormat!="copy") {
        out << tr("-d option applicable only for vCard format");
        return 11;
    }
    // Check if output file exists
    QFile of(outPath);
    if (of.exists() && !forceOverwrite && !QFileInfo(outPath).isDir()) {
        out << tr("Output file already exists, use -w if necessary\n");
        printUsage();
        return 12;
    }
    // Define, create file or directory at output
    // (default: as input)
    FormatType ift = QFileInfo(inPath).isDir() ? ftDirectory : ftFile;
    FormatType oft = ift;
    if (forceSingleFile)
        oft = ftFile;
    else if (forceDirectory)
        oft = ftDirectory;
    // Read
    IFormat* iFormat = 0;
    FormatFactory factory;
    if (ift==ftFile)
        iFormat = factory.createObject(inPath);
    else
        iFormat = new VCFDirectory();
    if (!iFormat) {
        out << factory.error << "\n";
        return 13;
    }
    ContactList items;
    bool res = iFormat->importRecords(inPath, items, false);
    logFormat(iFormat);
    delete iFormat;
    if (!res)
        return 14;
    out << tr("%1 records read\n").arg(items.count());
    //Define output format
    gd.preferredVCFVersion = GlobalConfig::VCF21;
    IFormat* oFormat = 0;
    if (oft==ftDirectory)
        oFormat = new VCFDirectory();
    else if (outFormat.contains("vcf")) {
        if (outFormat=="vcf30")
            gd.preferredVCFVersion = GlobalConfig::VCF30;
        gd.useOriginalFileVersion = (outFormat=="vcfauto");
        oFormat = new VCFFile();
    }
    else if (outFormat.contains("udx"))
        oFormat = new UDXFile();
    else { // copy input format
        if (VCFFile::detect(inPath)) {
            gd.useOriginalFileVersion = true;
            oFormat = new VCFFile();
        }
        else if (UDXFile::detect(inPath))
            oFormat = new UDXFile();
        // else if (MPBFile::detect(inPath)) { TODO m.b. implement?
        else if (inPath.contains(".mpb", Qt::CaseInsensitive)) { // temp hack
            out << "MPB format is read-only and incompatible with 'copy' option. Use VCF or UDX for output file\n";
            return 15;
        }
        else {
            out << "Can't autodetect input format\n";
            return 16;
        }
    }
    // Write
    res = oFormat->exportRecords(outPath, items);
    logFormat(oFormat);
    delete oFormat;
    out << "Output file successfully written\n";
    return res ? 0 : 17;
}
示例#6
0
文件: log.cpp 项目: whztt07/Magic3D-2
void Magic3D::Log::debug(const char* file, int line) {
    logFormat(eLOG_FAILURE, "File: %s - Line: %d", file, line);
}
示例#7
0
文件: userserv.c 项目: Lerc/userserv
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);
}