bool Program::readCommandLine()
{
	std::wstring commandLine = GetCommandLineW();
	std::vector<std::wstring> splitCommandLine;
	if (commandLine.find(L"-c") != std::wstring::npos)
	{
		boost::algorithm::split(splitCommandLine, commandLine.substr(commandLine.find(L"-c")), boost::algorithm::is_any_of(L" "));
	}
	if (splitCommandLine.size() < 7)
	{
		logText("Error reading command line: Parameter count mismatch");
		return false;
	}
	for (std::vector<std::wstring>::iterator s = splitCommandLine.begin(); s != splitCommandLine.end(); ++s)
	{
		if (!s->compare(L"-n"))
		{
			std::advance(s, 1);
			name = core->wstrtostr(*s);
		}
		else if (!s->compare(L"-h"))
		{
			std::advance(s, 1);
			address = core->wstrtostr(*s);
		}
		else if (!s->compare(L"-p"))
		{
			std::advance(s, 1);
			port = core->wstrtostr(*s);
		}
	}
	if (name.empty())
	{
		logText("Error reading command line: Could not obtain player name");
		return false;
	}
	if (address.empty())
	{
		logText("Error reading command line: Could not obtain server address");
		return false;
	}
	if (port.empty())
	{
		logText("Error reading command line: Could not obtain server port");
		return false;
	}
	return true;
}
void tvNetworkControl::sendIDPacket(const QString &remoteIP, const QString &ID, const QString &name)
{
    const char packetStart[] = {
        0x00, 0x13, 0x00, 0x69, 0x70, 0x68, 0x6f, 0x6e, 0x65, 0x2e, 0x69, 0x61, 0x70, 0x70, 0x2e, 0x73,
        0x61, 0x6d, 0x73, 0x75, 0x6e, 0x67
    };

    const QByteArray remoteIPEncoded = encodeString(remoteIP);
    const QByteArray remoteIDEncoded = encodeString(ID);
    const QByteArray remoteNameEncoded = encodeString(name);

    const char payLoadStart[] = {
        0x64, 0x00
    };

    QByteArray payLoad;
    payLoad.append(QByteArray::fromRawData(payLoadStart, sizeof(payLoadStart)));
    payLoad.append(QByteArray::fromRawData(remoteIPEncoded.data(), remoteIPEncoded.size()));
    payLoad.append(QByteArray::fromRawData(remoteIDEncoded.data(), remoteIDEncoded.size()));
    payLoad.append(QByteArray::fromRawData(remoteNameEncoded.data(), remoteNameEncoded.size()));
    const qint16 payLoadSize = payLoad.size();

    QByteArray packet;
    QDataStream stream(&packet, QIODevice::WriteOnly);
    stream.writeRawData(packetStart, sizeof(packetStart));
    stream.setByteOrder(QDataStream::LittleEndian);
    stream << payLoadSize;
    stream.setByteOrder(QDataStream::BigEndian);
    stream.writeRawData(payLoad, payLoadSize);

    if (m_socket) {
        emit logText(tr("=========== <b>Send ID Datagram</b> ===========<br>%1").arg(byteArrayToHexaString(packet)));
        sendRaw(packet);
    }
}
Example #3
0
void MainWindow::handleResult(const QString *res)
{
    logText(res);
//    char buff[100];
//    sprintf_s(buff, "current dts : %d (%d)", vtools.getCurrentDts(), vtools.getCurrentTs());
//    QString* result = new QString(buff);
//    logText(result);
}
void tvNetworkControl::sltReadyRead()
{
    QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
    if (socket == 0)
        return;
    QByteArray recievedData = socket->readAll().toHex();
    emit logText(tr("============ <b>Recieved Datagram</b> =============<br>%1").arg(byteArrayToHexaString(recievedData, false)));
}
Example #5
0
bool loadThemeImage(char * path, char * description, int expectedWidth, int expectedHeight, u8 * alphaMask, int imageID, themeImage images[]) {
    themeImage * aThemeImage = &(images[imageID]);
    aThemeImage->exists = false;

    if (aThemeImage->spriteData) {
        free(aThemeImage->spriteData);
    }

    aThemeImage->spriteData = NULL;

//    free(aThemeImage->spriteData);

    if (!fileExists(path, &sdmcArchive)) {
        return false;
    }

    bool success = read_png_file(path);

    if (success) {
        if (pngWidth != expectedWidth || pngHeight != expectedHeight) {
            char error[256];
            sprintf(error, "%s must be %dx%d pixels", description, expectedWidth, expectedHeight);
            logText(error);
            return false;
        }
        else {
            u8 * out = process_png_file();

            if (out) {
                if (alphaMask) {
                    u8 * masked = malloc(expectedWidth*expectedHeight*4);
                    MAGFXApplyAlphaMask(out, alphaMask, masked, expectedWidth, expectedHeight, (bytesPerPixel==4));
                    aThemeImage->spriteData = masked;
                    free(out);
                    aThemeImage->hasAlpha = true;
                }
                else {
                    aThemeImage->spriteData = out;
                    aThemeImage->hasAlpha = (bytesPerPixel==4);
                }


                aThemeImage->exists = true;
                aThemeImage->w = expectedWidth;
                aThemeImage->h = expectedHeight;

                return true;
            }
            else {
                return false;
            }
        }
    }
    else {
        return false;
    }
}
Example #6
0
void RDSqlDatabaseStatus::sendRecon()
{
  if (discon){
    discon = false;
    emit reconnected();
    fprintf (stderr,"Database connection restored.\n");
    emit logText(RDConfig::LogErr,QString(tr("Database connection restored.")));
  }
}
Example #7
0
punchVisualiser::punchVisualiser(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::punchVisualiser)
{
    ui->setupUi(this);
    m_sportIdentModule = new SportIdentReader(this);
    connect(m_sportIdentModule, SIGNAL(logText(QString,SportIdentReader::MessageType)),
            this, SLOT(processMessage(QString,SportIdentReader::MessageType)));
    connect(m_sportIdentModule, SIGNAL(rawData(QByteArray)), this, SLOT(dataReceived(QByteArray)));
}
Example #8
0
void RDSqlDatabaseStatus::sendDiscon(QString query)
{
  if (!discon){
    emit connectionFailed();
    fprintf (stderr,"Database connection failed: %s\n",(const char *)query);
    emit logText(RDConfig::LogErr,
		 QString(tr("Database connection failed : ")) + query);
    discon = true;
  }
}
Example #9
0
	void CLogger::log(const c8* text, const wchar_t* hint, ELogLevel logLevel)
	{
		if (logLevel < m_logLevel)
		{
			return;
		}

		BSLib::stringc logText(text);
		BSLib::stringc logHint = ToNarrow(hint);
		return log(logText.c_str(), logHint.c_str(), logLevel);
	}
Example #10
0
	void CLogger::log(const c8* text, const c8* hits, ELogLevel logLevel)
	{
		if (logLevel < m_logLevel)
		{
			return;
		}

		BSLib::stringc logText(text);
		logText += ":";
		logText += hits;

		return log(logText.c_str(), logLevel);
	}
Example #11
0
int main (int argc, char **argv) {
	init();
	if (fork() !=0 ) return 0;
	
	(void) signal(SIGCLD, SIG_IGN);
	(void) signal(SIGHUP, SIG_IGN);
	
	scrub();
	
	logText("Starting");
	serverListen(8082);	
	fail("testing failure");
}
bool Program::initializeAudioDevice()
{
	BASS_Free();
	if (BASS_Init(-1, 44100, BASS_DEVICE_3D, NULL, NULL))
	{
		loadPlugins();
		BASS_SetConfig(BASS_CONFIG_NET_PLAYLIST, 1);
		BASS_SetConfig(BASS_CONFIG_NET_TIMEOUT, settings->connectTimeout);
		BASS_SetConfig(BASS_CONFIG_WMA_BASSFILE, 1);
		BASS_SetEAXParameters(-1, 0.0f, -1.0f, -1.0f);
		return true;
	}
	logText(boost::str(boost::format("Error initializing audio device: %1%") % core->getAudio()->getErrorMessage()));
	return false;
}
Example #13
0
void sendLoginPage(int socketfd) {
	char* loginPage="<html><head>"
								"<style>"
										"body{background-color:grey; font-family: sans-serif}"
										"input{background-color:white}"
										"#loginBox{position:absolute;top:40%; left:0px; right:0px;}"
										"input{float:right;width:16em;}"
										"#loginBox>form>div{padding: 8px}"
										"#loginBox>form{background-color: #dfd;margin: 0 auto; box-shadow:0px 0px 0px 2px black,3px 3px 12px 2px black;width:20em; padding: 40px; border-radius: 8px 64px 8px 64px}"
								"</style></head>"
								"<body><div id=\"loginBox\">"
									 "<form action=\"/login\" method=\"post\"><div><label for=\"user\">User Name</label><input type=\"text\" id=\"user\" name=\"user\" /></div><div><label for=\"pass\">Password</label><input type=\"password\" id=\"pass\" name=\"pass\"/></div><div><input type=\"submit\" value=\"login\"></div></form>"
								"</div></body></html>";
	char* headers = "";
	logText("Sending login page");

	sendHTMLPage(socketfd,"200 ok",headers,loginPage);	
}
Example #14
0
bool reloadConfig(int argc, char **argv, bool firstTime)
{
  if (!firstTime) {
    logText("reloading config...\n");
  }

  if (ReadConfig(&g_config, argv[1]) != 0) {
    return false;
  }

  int p;
  for (p = 2; p < argc; p ++)
  {
      if (!strcmp(argv[p],"-pidfile"))
      {
        if (++p >= argc) usage(argv[0]);
        g_config.pidFilename.Set(argv[p]);
      }
      else if (!strcmp(argv[p],"-logfile"))
      {
        if (++p >= argc) usage(argv[0]);
        g_config.logFilename.Set(argv[p]);
      }
      else if (!strcmp(argv[p],"-archive"))
      {
        if (++p >= argc) usage(argv[0]);
        g_config.logPath.Set(argv[p]);
      }
      else if (!strcmp(argv[p],"-setuid"))
      {
        if (++p >= argc) usage(argv[0]);
        g_config.setuid=atoi(argv[p]);
      }
      else if (!strcmp(argv[p],"-port"))
      {
        if (++p >= argc) usage(argv[0]);
        g_config.port=atoi(argv[p]);
      }
      else usage(argv[0]);
  }

  return g_server->setConfig(&g_config);
}
void Program::loadPlugins()
{
	const char *pluginNames[] =
	{
		"bass_aac.dll",
		"bass_ac3.dll",
		"bass_alac.dll",
		"bass_ape.dll",
		"bass_mpc.dll",
		"bass_spx.dll",
		"bass_tta.dll",
		"bassflac.dll",
		"bassmidi.dll",
		"basswma.dll",
		"basswv.dll"
	};
	HPLUGIN pluginHandles[sizeof(pluginNames) / sizeof(const char*)];
	unsigned int size = sizeof(pluginHandles) / sizeof(HPLUGIN);
	for (unsigned int i = 0; i < size; ++i)
	{
		pluginHandles[i] = BASS_PluginLoad(boost::str(boost::format("plugins\\%1%") % pluginNames[i]).c_str(), 0);
		if (pluginHandles[i])
		{
			const BASS_PLUGININFO *info = BASS_PluginGetInfo(pluginHandles[i]);
			for (unsigned int j = 0; j < info->formatc; ++j)
			{
				std::string extensions = info->formats[j].exts;
				boost::algorithm::erase_all(extensions, "*");
				std::vector<std::string> splitExtensions;
				boost::algorithm::split(splitExtensions, extensions, boost::algorithm::is_any_of(";"));
				for (std::vector<std::string>::iterator e = splitExtensions.begin(); e != splitExtensions.end(); ++e)
				{
					acceptedFileExtensions.insert(*e);
				}
			}
		}
		else
		{
			logText(boost::str(boost::format("Error loading plugin \"%1%\": %2%") % pluginNames[i] % core->getAudio()->getErrorMessage()));
		}
	}
}
Example #16
0
void MainWindow::handleTimeout()
{
    //routines
    if(imageEater != NULL) {
        ui->pbBuffer->setValue(imageEater->getBufferUtilization());
        logText(&QString("current ts : %1").arg(vtools.getCurrentTs()));
    }

    if(spline != NULL) {
        spline->setplayposition(vtools.getCurrentTs());
    } else {
        //try applying value
        spline = (SplineDrawer*)QMLRegister::getQMLObject("spline");
        if(spline == 0) {
            spline = NULL;
        }
    }
    //too heavy
//    SplineDrawer* spline = (SplineDrawer*)QMLRegister::getQMLObject("spline");
    //    spline->update();
}
void tvNetworkControl::sendKey(const QString &key)
{

#ifdef QT5
    QByteArray keyByteArray(key.toLatin1());
#else
    QByteArray keyByteArray(key.toAscii());
#endif

    keyByteArray = keyByteArray.toBase64();

    const char rawKeyPacketStart[] = {
        0x00, 0x13, 0x00, 0x69, 0x70, 0x68, 0x6f, 0x6e, 0x65, 0x2e, 0x69, 0x61, 0x70, 0x70, 0x2e, 0x73,
        0x61, 0x6d, 0x73, 0x75, 0x6e, 0x67
    };

    const char payloadStart[] = {0x00, 0x00, 0x00};

    const qint16 keySize = keyByteArray.size();
    const qint16 payloadSize = keyByteArray.size() + 5; // 5 is 3 0x00 bytes + 2 bytes for the key code size

    QByteArray keyPacket;
    QDataStream stream(&keyPacket, QIODevice::WriteOnly);
    stream.writeRawData(rawKeyPacketStart, sizeof(rawKeyPacketStart));
    stream.setByteOrder(QDataStream::LittleEndian);
    stream << payloadSize;
    stream.setByteOrder(QDataStream::BigEndian);
    stream.writeRawData(payloadStart, sizeof(payloadStart));
    stream.setByteOrder(QDataStream::LittleEndian);
    stream << keySize;
    stream.setByteOrder(QDataStream::BigEndian);
    stream.writeRawData(keyByteArray, keyByteArray.size());

    if (m_socket) {
        emit logText(tr("============ <b>Send Datagram</b> =============<br>%1").arg(byteArrayToHexaString(keyPacket)));
        sendRaw(keyPacket);
    }
}
Example #18
0
int main(int argc, char **argv)
{
  QCoreApplication app(argc, argv);

  if (argc < 2)
  {
    usage(argv[0]);
  }

  g_server = new Server(myCreateUserLookup);

  printf("%s", startupmessage);

  if (!reloadConfig(argc, argv, true)) {
    printf("Error loading config file!\n");
    exit(1);
  }

#ifdef _WIN32
  DWORD v=GetTickCount();
  WDL_RNG_addentropy(&v,sizeof(v));
  v=(DWORD)time(NULL);
  WDL_RNG_addentropy(&v,sizeof(v));
#else
  time_t v=time(NULL);
  WDL_RNG_addentropy(&v,sizeof(v));
  int pid=getpid();
  WDL_RNG_addentropy(&pid,sizeof(pid));

  if (g_config.setuid != -1) setuid(g_config.setuid);

  if (g_config.pidFilename.Get()[0])
  {
    FILE *fp=fopen(g_config.pidFilename.Get(),"w");
    if (fp)
    {
      fprintf(fp,"%d\n",pid);
      fclose(fp);
    }
    else printf("Error opening PID file '%s'\n", g_config.pidFilename.Get());
  }
#endif

  if (g_config.logFilename.Get()[0])
  {
    g_logfp=fopen(g_config.logFilename.Get(),"at");
    if (!g_logfp)
      printf("Error opening log file '%s'\n",g_config.logFilename.Get());
    else
      logText("Opened log. Wahjam Server %s built on %s at %s\n",VERSION,__DATE__,__TIME__);

  }

  logText("Server starting up...\n");

#ifndef _WIN32
  SignalHandler *sigHandler = new SignalHandler(argc, argv);
#endif

  app.exec();

#ifndef _WIN32
  delete sigHandler;
#endif

  logText("Shutting down server\n");

  /* Explicitly delete before closing log */
  delete g_server;

  if (g_logfp)
  {
    fclose(g_logfp);
    g_logfp=0;
  }

	return 0;
}
void tvNetworkControl::sltConnected()
{
    emit logText(tr("<b>Connected!</b><br>"));
    m_connected = true;
}
Example #20
0
void fail(char* text) {
	char msgBuffer[16384];
	sprintf(msgBuffer,"ERROR: %s  (errno=%d) exiting process %d",text,errno,getpid());
	logText(msgBuffer);
	exit(3);
}
Example #21
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);
}
Example #22
0
static int ConfigOnToken(LineParser *lp)
{
  const char *t=lp->gettoken_str(0);
  if (!stricmp(t,"Port"))
  {
    if (lp->getnumtokens() != 2) return -1;
    int p=lp->gettoken_int(1);
    if (!p) return -2;
    g_config_port=p;
  }
  else if (!stricmp(t,"StatusUserPass"))
  {
    if (lp->getnumtokens() != 3) return -1;
    g_status_user.Set(lp->gettoken_str(1));
    g_status_pass.Set(lp->gettoken_str(2));
  }
  else if (!stricmp(t,"MaxUsers"))
  {
    if (lp->getnumtokens() != 2) return -1;
    int p=lp->gettoken_int(1);
    m_group->m_max_users=p;
  }  
  else if (!stricmp(t,"PIDFile"))
  {
    if (lp->getnumtokens() != 2) return -1;
    g_pidfilename.Set(lp->gettoken_str(1));    
  }
  else if (!stricmp(t,"LogFile"))
  {
    if (lp->getnumtokens() != 2) return -1;
    g_logfilename.Set(lp->gettoken_str(1));    
  }
  else if (!stricmp(t,"SessionArchive"))
  {
    if (lp->getnumtokens() != 3) return -1;
    g_config_logpath.Set(lp->gettoken_str(1));    
    g_config_log_sessionlen = lp->gettoken_int(2);
  }
  else if (!stricmp(t,"SetUID"))
  {
    if (lp->getnumtokens() != 2) return -1;
    g_set_uid = lp->gettoken_int(1);
  }
  else if (!stricmp(t,"DefaultBPI"))
  {
    if (lp->getnumtokens() != 2) return -1;
    g_default_bpi=lp->gettoken_int(1);
    if (g_default_bpi<MIN_BPI) g_default_bpi=MIN_BPI;
    else if (g_default_bpi > MAX_BPI) g_default_bpi=MAX_BPI;
  }
  else if (!stricmp(t,"DefaultBPM"))
  {
    if (lp->getnumtokens() != 2) return -1;
    g_default_bpm=lp->gettoken_int(1);
    if (g_default_bpm<MIN_BPM) g_default_bpm=MIN_BPM;
    else if (g_default_bpm > MAX_BPM) g_default_bpm=MAX_BPM;
  }
  else if (!stricmp(t,"DefaultTopic"))
  {
    if (lp->getnumtokens() != 2) return -1;
    if (!m_group->m_topictext.Get()[0])
      m_group->m_topictext.Set(lp->gettoken_str(1));    
  }
  else if (!stricmp(t,"MaxChannels"))
  {
    if (lp->getnumtokens() != 2 && lp->getnumtokens() != 3) return -1;
    
    g_config_maxch_user=lp->gettoken_int(1);
    g_config_maxch_anon=lp->gettoken_int(lp->getnumtokens()>2?2:1);
  }
  else if (!stricmp(t,"SetKeepAlive"))
  {
    if (lp->getnumtokens() != 2) return -1;
    m_group->m_keepalive=lp->gettoken_int(1);
    if (m_group->m_keepalive < 0 || m_group->m_keepalive > 255)
      m_group->m_keepalive=0;
  }
  else if (!stricmp(t,"SetVotingThreshold"))
  {
    if (lp->getnumtokens() != 2) return -1;
    m_group->m_voting_threshold=lp->gettoken_int(1);
  }
  else if (!stricmp(t,"SetVotingVoteTimeout"))
  {
    if (lp->getnumtokens() != 2) return -1;
    m_group->m_voting_timeout=lp->gettoken_int(1);
  }
  else if (!stricmp(t,"ServerLicense"))
  {
    if (lp->getnumtokens() != 2) return -1;
    FILE *fp=fopen(lp->gettoken_str(1),"rt");
    if (!fp) 
    {
      printf("Error opening license file %s\n",lp->gettoken_str(1));
      if (g_logfp)
        logText("Error opening license file %s\n",lp->gettoken_str(1));
      return -2;
    }
    g_config_license.Set("");
    for (;;)
    {
      char buf[1024];
      buf[0]=0;
      fgets(buf,sizeof(buf),fp);
      if (!buf[0]) break;
      g_config_license.Append(buf);
    }

    fclose(fp);
    
  }
  else if (!stricmp(t,"ACL"))
  {
    if (lp->getnumtokens() != 3) return -1;
    int suc=0;
    char *v=lp->gettoken_str(1);
    char *t=strstr(v,"/");
    if (t)
    {
      *t++=0;
      unsigned long addr=JNL::ipstr_to_addr(v);
      if (addr != INADDR_NONE)
      {
        int maskbits=atoi(t);
        if (maskbits >= 0 && maskbits <= 32)
        {
          int flag=lp->gettoken_enum(2,"allow\0deny\0reserve\0");
          if (flag >= 0)
          {
            suc=1;
            unsigned long mask=~(0xffffffff>>maskbits);
            aclAdd(addr,mask,flag);
          }
        }
      }
Example #23
0
  int Run()
  {
    // perform lookup here

    user_valid=0;

    if (!strncmp(username.Get(),"anonymous",9) && (!username.Get()[9] || username.Get()[9] == ':'))
    {
      logText("got anonymous request (%s)\n",g_config_allowanonymous?"allowing":"denying");
      if (!g_config_allowanonymous) return 1;

      user_valid=1;
      reqpass=0;

      WDL_String tmp(username.Get());

      if (tmp.Get()[9] == ':' && tmp.Get()[10])
      {
        username.Set(tmp.Get()+10);

        int cnt=16;
        char *p=username.Get();
        while (*p)
        {
          if (!cnt--)
          {
            *p=0;
            break;
          }
          if (*p == '@' || *p == '.') *p='_';
          p++;
        }
      }
      else username.Set("anon");

      username.Append("@");
      username.Append(hostmask.Get());

      if (g_config_anonymous_mask_ip)
      {
        char *p=username.Get();
        while (*p) p++;
        while (p > username.Get() && *p != '.' && *p != '@') p--;
        if (*p == '.' && p[1])
        {
          p[1]='x';
          p[2]=0;
        }
      }

      privs=(g_config_allow_anonchat?PRIV_CHATSEND:0) | (g_config_allowanonymous_multi?PRIV_ALLOWMULTI:0) | PRIV_VOTE;
      max_channels=g_config_maxch_anon;
    }
    else
    {
      int x;
      logText("got login request for '%s'\n",username.Get());
      if (g_status_user.Get()[0] && !strcmp(username.Get(),g_status_user.Get()))
      {
        user_valid=1;
        reqpass=1;
        is_status=1;
        privs=0; 
        max_channels=0;

        WDL_SHA1 shatmp;
        shatmp.add(username.Get(),strlen(username.Get()));
        shatmp.add(":",1);
        shatmp.add(g_status_pass.Get(),strlen(g_status_pass.Get()));

        shatmp.result(sha1buf_user);
      }
      else for (x = 0; x < g_userlist.GetSize(); x ++)
      {
        if (!strcmp(username.Get(),g_userlist.Get(x)->name.Get()))
        {
          user_valid=1;
          reqpass=1;

          char *pass=g_userlist.Get(x)->pass.Get();
          WDL_SHA1 shatmp;
          shatmp.add(username.Get(),strlen(username.Get()));
          shatmp.add(":",1);
          shatmp.add(pass,strlen(pass));

          shatmp.result(sha1buf_user);

          privs=g_userlist.Get(x)->priv_flag; 
          max_channels=g_config_maxch_user;
          break;
        }
      }
    }

    return 1;
  }
Example #24
0
void logInt(int i, char * label) {
    char s[strlen(label)+8];
    sprintf(s, "%s: %d", label, i);
    logText(s);
}
void tvNetworkControl::sltError(QAbstractSocket::SocketError error)
{
    Q_UNUSED(error);
    emit logText(tr("<b>Network error: %1</b><br>").arg(m_socket->errorString()));
}
Program::Program()
{
	wchar_t savePathBuffer[MAX_PATH];
	if (SHGetFolderPathW(NULL, CSIDL_APPDATA, NULL, 0, savePathBuffer) >= 0)
	{
		PathAppendW(savePathBuffer, L"\\SA-MP Audio Plugin");
		if (!boost::filesystem::exists(savePathBuffer))
		{
			boost::filesystem::create_directories(savePathBuffer);
		}
		savePath = savePathBuffer;
	}
	else
	{
		savePath = L".";
	}
	const char *defaultAcceptedFileExtensions[] =
	{
		".afc",
		".aif",
		".aifc",
		".aiff",
		".it",
		".mo3",
		".mod",
		".mp1",
		".mp2",
		".mp3",
		".mtm",
		".oga",
		".ogg",
		".s3m",
		".umx",
		".wav",
		".wave",
		".xm"
	};
	for (std::size_t i = 0; i < sizeof(defaultAcceptedFileExtensions) / sizeof(const char*); ++i)
	{
		acceptedFileExtensions.insert(defaultAcceptedFileExtensions[i]);
	}
	const char *defaultIllegalCharacters[] =
	{
		"\"",
		"*",
		"..",
		"/",
		":",
		"<",
		">",
		"?",
		"\\",
		"|"
	};
	for (std::size_t i = 0; i < sizeof(defaultIllegalCharacters) / sizeof(const char*); ++i)
	{
		illegalCharacters.insert(defaultIllegalCharacters[i]);
	}
	settings.reset(new Settings);
	loadSettings();
	logText("SA-MP Audio Plugin loaded");
}
Example #27
0
static int ConfigOnToken(ServerConfig *config, LineParser *lp)
{
  QString token = QString(lp->gettoken_str(0)).toLower();
  if (token == QString("Port").toLower())
  {
    if (lp->getnumtokens() != 2) return -1;
    int p=lp->gettoken_int(1);
    if (!p) return -2;
    config->port=p;
  }
  else if (token == QString("StatusUserPass").toLower())
  {
    if (lp->getnumtokens() != 3) return -1;
    config->statusUser.Set(lp->gettoken_str(1));
    config->statusPass.Set(lp->gettoken_str(2));
  }
  else if (token == QString("MaxUsers").toLower())
  {
    if (lp->getnumtokens() != 2) return -1;
    int p=lp->gettoken_int(1);
    config->maxUsers=p;
  }
  else if (token == QString("PIDFile").toLower())
  {
    if (lp->getnumtokens() != 2) return -1;
    config->pidFilename.Set(lp->gettoken_str(1));
  }
  else if (token == QString("LogFile").toLower())
  {
    if (lp->getnumtokens() != 2) return -1;
    config->logFilename.Set(lp->gettoken_str(1));
  }
  else if (token == QString("SessionArchive").toLower())
  {
    if (lp->getnumtokens() != 3) return -1;
    config->logPath.Set(lp->gettoken_str(1));
    config->logSessionLen = lp->gettoken_int(2);
  }
  else if (token == QString("SetUID").toLower())
  {
    if (lp->getnumtokens() != 2) return -1;
    config->setuid = lp->gettoken_int(1);
  }
  else if (token == QString("DefaultBPI").toLower())
  {
    if (lp->getnumtokens() != 2) return -1;
    int p = lp->gettoken_int(1);
    if (p < MIN_BPI) {
      p = MIN_BPI;
    } else if (p > MAX_BPI) {
      p = MAX_BPI;
    }
    config->defaultBPI=lp->gettoken_int(1);
  }
  else if (token == QString("DefaultBPM").toLower())
  {
    if (lp->getnumtokens() != 2) return -1;
    int p = lp->gettoken_int(1);
    if (p < MIN_BPM) {
      p = MIN_BPM;
    } else if (p > MAX_BPM) {
      p = MAX_BPM;
    }
    config->defaultBPM = p;
  }
  else if (token == QString("DefaultTopic").toLower())
  {
    if (lp->getnumtokens() != 2) return -1;
    config->defaultTopic.Set(lp->gettoken_str(1));
  }
  else if (token == QString("MaxChannels").toLower())
  {
    if (lp->getnumtokens() != 2 && lp->getnumtokens() != 3) return -1;

    config->maxchUser=lp->gettoken_int(1);
    config->maxchAnon=lp->gettoken_int(lp->getnumtokens()>2?2:1);
  }
  else if (token == QString("SetKeepAlive").toLower())
  {
    if (lp->getnumtokens() != 2) return -1;
    int p = lp->gettoken_int(1);
    if (p < 0 || p > 255) {
      p = 0;
    }
    config->keepAlive = p;
  }
  else if (token == QString("SetVotingThreshold").toLower())
  {
    if (lp->getnumtokens() != 2) return -1;
    config->votingThreshold = lp->gettoken_int(1);
  }
  else if (token == QString("SetVotingVoteTimeout").toLower())
  {
    if (lp->getnumtokens() != 2) return -1;
    config->votingTimeout = lp->gettoken_int(1);
  }
  else if (token == QString("ServerLicense").toLower())
  {
    if (lp->getnumtokens() != 2) return -1;
    FILE *fp=fopen(lp->gettoken_str(1),"rt");
    if (!fp) 
    {
      printf("Error opening license file %s\n",lp->gettoken_str(1));
      if (g_logfp)
        logText("Error opening license file %s\n",lp->gettoken_str(1));
      return -2;
    }
    config->license.Set("");
    for (;;)
    {
      char buf[1024];
      buf[0]=0;
      fgets(buf,sizeof(buf),fp);
      if (!buf[0]) break;
      config->license.Append(buf);
    }

    fclose(fp);
    
  }
  else if (token == QString("ACL").toLower())
  {
    if (lp->getnumtokens() != 3) return -1;
    int suc=0;
    char *v=lp->gettoken_str(1);
    char *t=strstr(v,"/");
    if (t)
    {
      *t++=0;
      QHostAddress hostaddr(v);
      if (hostaddr != QHostAddress::Null)
      {
        int maskbits=atoi(t);
        if (maskbits >= 0 && maskbits <= 32)
        {
          int flag=lp->gettoken_enum(2,"allow\0deny\0reserve\0");
          if (flag >= 0)
          {
            suc=1;
            unsigned long mask = 0xffffffff << maskbits;
            config->acl.add(hostaddr.toIPv4Address(), mask, flag);
          }
        }
      }
    }

    if (!suc)
    {
      if (g_logfp)
        logText("Usage: ACL xx.xx.xx.xx/X [ban|allow|reserve]\n");
      printf("Usage: ACL xx.xx.xx.xx/X [ban|allow|reserve]\n");
      return -2;
    }
  }
  else if (token == QString("User").toLower())
  {
    if (lp->getnumtokens() != 3 && lp->getnumtokens() != 4) return -1;
    UserPassEntry *p=new UserPassEntry;
    p->name.Set(lp->gettoken_str(1));
    p->pass.Set(lp->gettoken_str(2));
    if (lp->getnumtokens()>3)
    {
      char *ptr=lp->gettoken_str(3);
      while (*ptr)
      {
        if (*ptr == '*') p->priv_flag|=~PRIV_HIDDEN; // everything but hidden if * used
        else if (*ptr == 'T' || *ptr == 't') p->priv_flag |= PRIV_TOPIC;
        else if (*ptr == 'B' || *ptr == 'b') p->priv_flag |= PRIV_BPM;
        else if (*ptr == 'C' || *ptr == 'c') p->priv_flag |= PRIV_CHATSEND;
        else if (*ptr == 'K' || *ptr == 'k') p->priv_flag |= PRIV_KICK;        
        else if (*ptr == 'R' || *ptr == 'r') p->priv_flag |= PRIV_RESERVE;        
        else if (*ptr == 'M' || *ptr == 'm') p->priv_flag |= PRIV_ALLOWMULTI;
        else if (*ptr == 'H' || *ptr == 'h') p->priv_flag |= PRIV_HIDDEN;       
        else if (*ptr == 'V' || *ptr == 'v') p->priv_flag |= PRIV_VOTE;               
        else 
        {
          if (g_logfp)
            logText("Warning: Unknown user priviledge flag '%c'\n",*ptr);
          printf("Warning: Unknown user priviledge flag '%c'\n",*ptr);
        }
        ptr++;
      }
    }
    else p->priv_flag=PRIV_CHATSEND|PRIV_VOTE;// default privs
    config->userlist.Add(p);
  }
  else if (token == QString("AllowHiddenUsers").toLower())
  {
    if (lp->getnumtokens() != 2) return -1;

    int x=lp->gettoken_enum(1,"no\0yes\0");
    if (x <0)
    {
      return -2;
    }
    config->allowHiddenUsers = x;
  }
  else if (token == QString("AnonymousUsers").toLower())
  {
    if (lp->getnumtokens() != 2) return -1;

    int x=lp->gettoken_enum(1,"no\0yes\0multi\0");
    if (x <0)
    {
      return -2;
    }
    config->allowAnonymous = x;
    config->allowAnonymousMulti = x == 2;
  }
  else if (token == QString("AnonymousMaskIP").toLower())
  {
    if (lp->getnumtokens() != 2) return -1;

    int x=lp->gettoken_enum(1,"no\0yes\0");
    if (x <0)
    {
      return -2;
    }
    config->anonymousMaskIP = x;
  }
  else if (token == QString("AnonymousUsers").toLower())
  {
    if (lp->getnumtokens() != 2) return -1;

    int x=lp->gettoken_enum(1,"no\0yes\0");
    if (x <0)
    {
      return -2;
    }
    config->allowAnonymous = x;
  }
  else if (token == QString("AnonymousUsersCanChat").toLower())
  {
    if (lp->getnumtokens() != 2) return -1;

    int x=lp->gettoken_enum(1,"no\0yes\0");
    if (x <0)
    {
      return -2;
    }
    config->allowAnonChat = x;
  }
  else return -3;
  return 0;
}
void tvNetworkControl::sltDisconnected()
{
    emit logText(tr("<b>Disconnected!</b><br>"));
    m_socket->abort();
    m_connected = false;
}
void Program::stop()
{
	core->getNetwork()->closeConnection();
	core->io_service.stop();
	logText("SA-MP Audio Plugin unloaded");
}
Example #30
0
static int ReadConfig(ServerConfig *config, char *configfile)
{
  bool comment_state=0;
  int linecnt=0;
  WDL_String linebuild;
  if (g_logfp) logText("[config] reloading configuration file\n"); // TODO move this elsewhere
  FILE *fp=strcmp(configfile,"-")?fopen(configfile,"rt"):stdin; 
  if (!fp)
  {
    printf("[config] error opening configfile '%s'\n",configfile);
    if (g_logfp) logText("[config] error opening config file (console request)\n"); // TODO move this elsewhere
    return -1;
  }

  config->allowAnonChat = true;
  config->allowAnonymous = false;
  config->allowAnonymousMulti = false;
  config->anonymousMaskIP = false;
  config->allowHiddenUsers = false;
  config->setuid = -1;
  config->defaultBPM = 120;
  config->defaultBPI = 8;
  config->port = 2049;
  config->keepAlive = 0;
  config->maxUsers = 0; // unlimited users
  config->maxchAnon = 2;
  config->maxchUser = 32;
  config->logSessionLen = 10; // ten minute default, tho the user will need to specify the path anyway
  config->votingThreshold = 110;
  config->votingTimeout = 120;
  config->logPath.Set("");
  config->pidFilename.Set("");
  config->logFilename.Set("");
  config->statusPass.Set("");
  config->statusUser.Set("");
  config->license.Set("");
  config->defaultTopic.Set("");
  config->acl.clear();

  int x;
  for(x=0; x < config->userlist.GetSize(); x++)
  {
    delete config->userlist.Get(x);
  }
  config->userlist.Empty();

  for (;;)
  {
    char buf[8192];
    buf[0]=0;
    fgets(buf,sizeof(buf),fp);
    linecnt++;
    if (!buf[0]) break;
    if (buf[strlen(buf)-1]=='\n') buf[strlen(buf)-1]=0;

    LineParser lp(comment_state);

    if (buf[0] && buf[strlen(buf)-1]=='\\')
    {
      buf[strlen(buf)-1]=0;
      linebuild.Append(buf);
      continue;
    }
    linebuild.Append(buf);

    int res=lp.parse(linebuild.Get());

    linebuild.Set("");

    if (res)
    {
      if (res==-2) 
      {
        if (g_logfp) logText("[config] warning: unterminated string parsing line %d of %s\n",linecnt,configfile);
        printf("[config] warning: unterminated string parsing line %d of %s\n",linecnt,configfile);
      }
      else 
      {
        if (g_logfp) logText("[config] warning: error parsing line %d of %s\n",linecnt,configfile);
        printf("[config] warning: error parsing line %d of %s\n",linecnt,configfile);
      }
    }
    else
    {
      comment_state = lp.InCommentBlock();

      if (lp.getnumtokens()>0)
      {
        int err = ConfigOnToken(config, &lp);
        if (err)
        {
          if (err == -1)
          {
            if (g_logfp) logText("[config] warning: wrong number of tokens on line %d of %s\n",linecnt,configfile);
            printf("[config] warning: wrong number of tokens on line %d of %s\n",linecnt,configfile);
          }
          if (err == -2)
          {
            if (g_logfp) logText("[config] warning: invalid parameter on line %d of %s\n",linecnt,configfile);
            printf("[config] warning: invalid parameter on line %d of %s\n",linecnt,configfile);
          }
          if (err == -3)
          {
            if (g_logfp) logText("[config] warning: invalid config command \"%s\" on line %d of %s\n",lp.gettoken_str(0),linecnt,configfile);
            printf("[config] warning: invalid config command \"%s\" on line %d of %s\n",lp.gettoken_str(0),linecnt,configfile);
          }
        }
      }
    }
  }

  if (g_logfp) logText("[config] reload complete\n");

  if (fp != stdin) fclose(fp);
  return 0;
}