void* authorization() {
	char login[MAX_LOGIN_LINGTH];
	char password[MAX_PASSWORD_LINGTH];
	char userRole;
	int i;

	printf("Enter login: "******"Enter password: ");
	for (i = 0; i < MAX_PASSWORD_LINGTH; i++) {
		password[i] = _getch();
		if (password[i] == '\r') {
			password[i] = '\0';
			putchar('\n');
			break;
		}
		if (password[i] == 8) {
			if (i > 0) {
				i--;
			}
			_getch();
		}
		
	}
	userRole = authentication(login, password);
    
	for (i = 0; i < ROLES_NUMBER; ++i) {
		if (userRole == roles[i]) {
			return rolesFunctions[i];
		}
	}

	return *error;
}
Exemple #2
0
int PhoneMonitorVoiceInterface::start( PhoneMonitorVoiceReportBase *reportHandle )
{
	m_phoneStatus =PHONE_STATUS_NOT_INIT;
	m_callStatus  =CALL_IDLE;

	m_pCallback   =reportHandle;

	if(m_pPhoneConnection->openDev("/dev/ttyUSB2")<0)
		return -1;

	QThread::start();
#ifdef PHONE_MODULE_ZTEMF5200_AUTH	
	if(authentication() < 0)
	{
		printf("AUTH fail!!!\n");
		//m_pPhoneConnection->closeDev("/dev/ttyUSB2");
		return -1;
	}
#endif
	m_phoneStatus =PHONE_STATUS_INITTING;

	m_pInitThread->startInit(this);
	m_pWorkThread->init(this);
	m_ptcpThread->init(this);

//	m_videoPhone->init(reportHandle);
        getOperator();
	
	return PHONE_MONITOR_SUCCESS;
}
Exemple #3
0
DWORD WINAPI MailHandler::clientHandler(LPVOID param){
	SOCKET client_socket = (SOCKET)param;
	if (client_socket == INVALID_SOCKET) {
		printf("error with accept socket. GetLasterror= %d\n", GetLastError());
		return 1003;
	}
	char buf[SIZE_OF_BUF] = "/0";
	//пересылаем код ответа номер 2 (ready) через клиентский сокет
	//POP3-коды ответа отпределены в Responses.h как двумерный массив
	sendLine(client_socket, responses[2]);
	//значение устанавливается в answer(), по смыслу номер состояния после принятия запроса
	int status = 1;
	int aut;
	User curUs = User();
	do {
		aut = authentication(client_socket, status, curUs); //процесс аутентификации клиента
		if (status == 0) {
			break;//Проверка на выход
		}
	} while (aut < 0);
	while (recvLine(client_socket, buf, SIZE_OF_BUF)>0){
		//принимаем сообщения размером buf из клиентского сокета, записываем в buf
		//int len = recvLine(client_socket, buf, SIZE_OF_BUF);
		//if (len > 2){
			//если что-то пришло, отвечаем
			string request=string(buf);
			request.erase(request.size() - 1);
			if (request.find("STAT") != string::npos){
				MailHandler::status(client_socket, curUs);
			}
			else if (request.find("LIST") != string::npos){
				getList(client_socket, request, curUs);
			}
			else if (request.find("RETR") != string::npos){
				getMessage(client_socket, request, curUs);
			}
			else if (request.find("DELE") != string::npos){
				deleteMessage(client_socket, request, curUs);
			}
			else if (request.find("RSET") != string::npos){
				reset(client_socket, curUs);
			}
			else if (request.find("QUIT") != string::npos){
				disconnect(client_socket, status, curUs);
			}
		//}
		if (status == 0) {
			break;//Проверка на выход
		}
	}
	closesocket(client_socket);
}
Exemple #4
0
bool RemoteHost::connectServer()
{
   if (isConnected()) return true;

   QLOG_TRACE() << "Connecting to Server: " << name() << " at host " << hostAddress();

   m_connection = new SecureConnection::Connection(hostAddress(), userName(), port());

   bool connected(false);
   switch (authentication()) {

      case Server::None:
         connected = false;
         break;

      case Server::Agent: 
         connected = m_connection->connect(SecureConnection::Agent);
         break;

      case Server::PublicKey: 
         connected = getPassphraseFromUserAndConnect(SecureConnection::PublicKey);
         break;

      case Server::HostBased: 
         connected = getPassphraseFromUserAndConnect(SecureConnection::HostBased);
         break;

      case Server::KeyboardInteractive: 
         connected = m_connection->connect(SecureConnection::KeyboardInteractive);
         break;

      case Server::Vault: 
         connected = getPasswordFromVaultAndConnect();
         break;

      case Server::Prompt: 
         connected = getPasswordFromUserAndConnect();
         break;
   }

   if (!connected) {
      QString msg("Connection to server ");
      msg += name() + " falied";
      QMsgBox::warning(0, "IQmol", msg);
      delete m_connection;
      m_connection = 0;
   }

   return connected;
}
Exemple #5
0
void TCPServer::comunication()
{
	char message[BUFFER_SIZE];

	//to establish the fully infomation of the newest accpected client
	client_ds *this_client = new client_ds(client_socket, inet_ntoa(client_addr.sin_addr),\
					(int)ntohs(client_addr.sin_port), \
					(clients_n == 1)? RL_BLACK: \
					(clients_n == 2)? RL_WHITE: RL_MONITOR, \
					client_thread_id);
	printf("<<<< <connection from client, IP: %s, Port: %d, Role: %s>\n", \
			this_client->IP, ntohs(client_addr.sin_port), \
			(this_client->role == RL_BLACK)? "Agent_Black": \
			(this_client->role == RL_WHITE)? "Agent_White":"Monitor" );


	if( !authentication(this_client->socket)){
		fprintf(stderr, "illegal invasion\n");
		close(this_client->socket);
		delete this_client;
		return;
	}
	send_msg( this_client->socket, message, this_client->role);
	usleep(400000);
	send_msg( this_client->socket, message, board->layout);

	while(!stop)
		main_loop(this_client->role, this_client->socket, message);
	
	send_rslt(this_client->socket, this_client->role, board->winner());

	close(this_client->socket);
	delete this_client;
	
	if( !(--clients_n)){
		pthread_mutex_destroy( &mutex_update);
		pthread_cond_destroy(  &tell_to_update);
		close(server_socket);
		printf(">>>> Contest finished - ");
		switch(board->winner()){
			case RL_BLACK: printf("winner is BLACK\n"); break;
			case RL_WHITE: printf("winner is WHITE\n"); break;
			case '\0': printf("winner is NONE\n"); break;
		}
		exit(0);
	}
}
bool ServerConfigurationDialog::testSshConnection(ServerConfiguration const& configuration)
{
   bool okay(false);

   try {
      QString hostAddress(configuration.value(ServerConfiguration::HostAddress));
      QString userName(configuration.value(ServerConfiguration::UserName));
      Network::Connection::AuthenticationT authentication(configuration.authentication());

      int port(configuration.port());

      Network::SshConnection ssh(hostAddress, port);
      ssh.open();
      ssh.authenticate(authentication, userName);
      QLOG_TRACE() << "Authentication successful";

      QEventLoop loop;
      Network::Reply* reply(ssh.execute("ls"));
      QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
      loop.exec();

      okay = (reply->status() == Network::Reply::Finished);
      if (okay) {
         QLOG_DEBUG() << "----------------------------";
         QLOG_DEBUG() << reply->message();
         QLOG_DEBUG() << "----------------------------";
      }else {
         QString msg("Connection failed:\n");
         msg += reply->message();
         QMsgBox::warning(this, "IQmol", msg);
      }
      delete reply;

   }catch (Network::AuthenticationCancelled& err) {
      // don't do anything

   }catch (Network::AuthenticationError& err) {
      QMsgBox::warning(0, "IQmol", "Invalid username or password");

   }catch (Exception& err) {
      okay = false;
      QMsgBox::warning(0, "IQmol", err.what());
   }

   return okay;
}
Exemple #7
0
void SocketStreamHandle::addCONNECTCredentials(CFHTTPMessageRef proxyResponse)
{
    RetainPtr<CFHTTPAuthenticationRef> authentication(AdoptCF, CFHTTPAuthenticationCreateFromResponse(0, proxyResponse));

    if (!CFHTTPAuthenticationRequiresUserNameAndPassword(authentication.get())) {
        // That's all we can offer...
        m_client->didFail(this, SocketStreamError()); // FIXME: Provide a sensible error.
        return;
    }

    int port = 0;
    CFNumberGetValue(m_proxyPort.get(), kCFNumberIntType, &port);
    RetainPtr<CFStringRef> methodCF(AdoptCF, CFHTTPAuthenticationCopyMethod(authentication.get()));
    RetainPtr<CFStringRef> realmCF(AdoptCF, CFHTTPAuthenticationCopyRealm(authentication.get()));
    ProtectionSpace protectionSpace(String(m_proxyHost.get()), port, ProtectionSpaceProxyHTTPS, String(realmCF.get()), authenticationSchemeFromAuthenticationMethod(methodCF.get()));
    String login;
    String password;
    if (!m_sentStoredCredentials && getStoredCONNECTProxyCredentials(protectionSpace, login, password)) {
        // Try to apply stored credentials, if we haven't tried those already.
        RetainPtr<CFStringRef> loginCF(AdoptCF, login.createCFString());
        RetainPtr<CFStringRef> passwordCF(AdoptCF, password.createCFString());
        // Creating a temporary request to make CFNetwork apply credentials to it. Unfortunately, this cannot work with NTLM authentication.
        RetainPtr<CFHTTPMessageRef> dummyRequest(AdoptCF, CFHTTPMessageCreateRequest(0, CFSTR("GET"), m_httpsURL.get(), kCFHTTPVersion1_1));

        Boolean appliedCredentials = CFHTTPMessageApplyCredentials(dummyRequest.get(), authentication.get(), loginCF.get(), passwordCF.get(), 0);
        ASSERT_UNUSED(appliedCredentials, appliedCredentials);

        RetainPtr<CFStringRef> proxyAuthorizationString(AdoptCF, CFHTTPMessageCopyHeaderFieldValue(dummyRequest.get(), CFSTR("Proxy-Authorization")));

        if (!proxyAuthorizationString) {
            // Fails e.g. for NTLM auth.
            m_client->didFail(this, SocketStreamError()); // FIXME: Provide a sensible error.
            return;
        }

        // Setting the authorization results in a new connection attempt.
        wkSetCONNECTProxyAuthorizationForStream(m_readStream.get(), proxyAuthorizationString.get());
        m_sentStoredCredentials = true;
        return;
    }

    // FIXME: Ask the client if credentials could not be found.

    m_client->didFail(this, SocketStreamError()); // FIXME: Provide a sensible error.
}
Exemple #8
0
	void login() //пока текущий пользователь не установлен
	{
		while (!pCurrentUser_)
		{
			std::cout << "Username: "******"User '" << username << "' not found" << std::endl;
			}
			else
			{
				authentication(pUser); //попытка идентифицировать
			}
		}
	}
Exemple #9
0
void             update_pendings(t_server *server, fd_set *readfds)
{
    unsigned int     i;
    int              sd;

    i = 0;
    while (i < MAX_PENDINGS) 
    {
        sd = server->pending_sockets[i];

        if (FD_ISSET(sd , readfds)) 
        {
            //Launch authentication test
            if (!authentication(server, sd))
                close(sd);
            server->pending_sockets[i] = 0;
        }
        ++i;
    }
}
Exemple #10
0
NetworkManager::NetworkManager(QObject *parent)
    : QNetworkAccessManager(parent)
{
    // Create scheme handlers
    mApp->webProfile()->installUrlSchemeHandler(QByteArrayLiteral("qupzilla"), new QupZillaSchemeHandler());

    // Create url interceptor
    m_urlInterceptor = new NetworkUrlInterceptor(this);
    mApp->webProfile()->setRequestInterceptor(m_urlInterceptor);

    // Create cookie jar
    mApp->cookieJar();

    connect(this, &QNetworkAccessManager::authenticationRequired, this, [this](QNetworkReply *reply, QAuthenticator *auth) {
        authentication(reply->url(), auth);
    });

    connect(this, &QNetworkAccessManager::proxyAuthenticationRequired, this, [this](const QNetworkProxy &proxy, QAuthenticator *auth) {
        proxyAuthentication(proxy.hostName(), auth);
    });
}
Exemple #11
0
	bool executeUserCommand(const std::string& command, const std::vector<std::string>& commandArgs) //выполнить пользовательскую команду
	{
		if (command == "users")
		{
			listAvailableUsers();
		}
		else if (command == "user")
		{
			if (commandArgs.empty())
			{
				if (!pCurrentUser_)
				{
					std::cout << "Not authenticated" << std::endl;
				}
				else
				{
					std::cout << "Current user: '******'" << std::endl;
				}
			}
			else
			{
				const std::string& username = commandArgs.at(0);
				User* pUser = getObjectByName(username, users_);
				if (!pUser)
				{
					std::cout << "User '" << username << "' not found" << std::endl;
				}
				else
				{
					authentication(pUser);
				}
			}
		}
		else
		{
			return false;
		}

		return true;
	}
int main(int argc, char *argv[]) {
	if(argc<2){
printf("		      _    __                   ");
    printf("\n   \\      /  _ |     /    /   \\     /\\    /\\   __  !   0  0 \n");
	printf("    \\    / |_  |     |   |    |    /  \\  /  \\  |_  !    \\/  \n");
	printf("     \\/\\/  |_  |__   \\_   \\ __/   /    \\/    \\ |_  !   \\__/ \n");
	printf("\n Unfortunatly, there is more to his plan. \nDr. John Evil has contacted Microsoft Internet Explorer IT and the Adobe Flash team to help make a more \nsecure system to hide the rest of his plans\n"); 
	printf("\nDue to your great work before, the FBI has rehired you for this task!\n");
	printf("\nThings may seem similiar, but slight,slight...very slight, changes make a  HUGE difference\n"); 
	printf("\nUsage: ./authentication2 'password' \n");return -1 ;}	
	
	//proceeds if authentication is correct
	if(authentication(argv[1])) {
		printf(" \nHAXxED!!.\n Congrats!");
		printf("\n Make sure you understand exactly what happened and what you did\n");
		printf("\n Hopefully you've all learned something about secure programming and the importance of sanitizing input\n This will be a common theme throughout the semester.\n");
		printf("\n 'With power (of C) comes great responsibility' ");
	} else {
		printf("\nFailed!\n");
   }
	return 0;
}
Exemple #13
0
void main(int argc, char *argv[])
{
	if (getuid() != 0)
	{
		fprintf(stderr, "Require root privilege.\n");
		exit(-1);
	}
	if (argc < 3 || argc > 4)
	{
		fprintf(stderr, "Usage: h3clite username password [interface]\n");
		exit(-1);
	}
	g_username = argv[1];
	g_password = argv[2];
	if (argc == 4)
	{
		s_interface = argv[3];
	}
	signal(SIGINT, &signal_exit);
	signal(SIGTERM, &signal_exit);
	authentication();
}
Exemple #14
0
int main(int argc, char *argv[]) {
	WORD wVersionRequested = MAKEWORD(2, 2);       // Stuff for WSA functions
	WSADATA wsaData;
   int sock, portno, n=0;
   int aut;
   struct sockaddr_in serv_addr;
   struct hostent *server;
   char quit[]="quit";
   char show[]="show users";
   char wallet[]="check wallet";
   char transf[]="transfer";
   char buffer[bufSize+1];
   char buf[bufSize];

   WSAStartup(wVersionRequested, &wsaData);
   //portno=12345;
   if (argc < 3) {
      fprintf(stderr,"usage %s hostname port\n", argv[0]);
      exit(0);
   }

   portno = atoi(argv[2]);

   /* Create a socket point */
   sock = socket(AF_INET, SOCK_DGRAM, 0);

   if (sock == SOCKET_ERROR) {
      perror("ERROR opening socket");
      exit(1);
   }

   server = gethostbyname(argv[1]);
   if (server == NULL) {
      fprintf(stderr,"ERROR, no such host\n");
      exit(0);
   }

   memset((char *) &serv_addr, 0, sizeof(serv_addr));
   serv_addr.sin_family = AF_INET;
   serv_addr.sin_addr.s_addr = inet_addr(argv[1]);
   //strncpy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);
   serv_addr.sin_port = htons(portno);
   int len = sizeof(serv_addr);


	n = sendto(sock, "client", strlen("client"), 0, (struct sockaddr *) &serv_addr, len);
	if (n < 0) {
        perror("ERROR writing to socket");
        closesocket(sock);
        exit(1);
    }

	//recieve new port
	memset(buf, 0, bufSize);
	n = recvfrom(sock, buf, bufSize, 0, (struct sockaddr *) &serv_addr, &len);
	if (n < 0) {
      perror("ERROR reading from socket");
      closesocket(sock);
      exit(1);
    } 
	disconnect(sock, buf);
	//close old socket
	closesocket(sock);
	WSACleanup();

	int newport = atoi(buf);

	WSADATA wsa2;
	if (WSAStartup(MAKEWORD(2, 2), &wsa2) != 0) {
		exit(EXIT_FAILURE);
	}

	struct sockaddr_in new_addr;
	int sockfd, new_slen = sizeof(new_addr);

	//create socket
	if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == SOCKET_ERROR) {
		exit(EXIT_FAILURE);
	}

	//setup address structure
	memset((char *)&new_addr, 0, new_slen);
	new_addr.sin_family = AF_INET;
	new_addr.sin_port = htons(newport);
	new_addr.sin_addr.S_un.S_addr = inet_addr(argv[1]);
	
	n = sendto(sockfd, "newclient", strlen("newclient"), 0, (struct sockaddr *) &new_addr, new_slen);
	if (n < 0) {
      perror("ERROR reading from socket");
      closesocket(sockfd);
      exit(1);
    } 

	Uclient client;
	client.sockfd = sockfd;
	client.serv_addr = new_addr;
	client.clilen = sizeof(new_addr);

   do {
           aut = authentication(client); //процесс аутентификации клиента
       } while (aut < 0);
   while (1){
    printf("Enter the command: ");
    memset(buffer, 0, bufSize+1);
    fgets(buffer,bufSize+1,stdin);

    if(strncmp(buffer,quit,sizeof(quit)-1) == 0){
            n = sendto(client.sockfd, buffer, strlen(buffer),0, (struct sockaddr*)&client.serv_addr, client.clilen);
            if (n < 0) {
                perror("ERROR writing to socket");
                exit(1);
            }
            closesocket(client.sockfd);
            break;
    }
    else if(strncmp(buffer,show,sizeof(show)-1) == 0){
        showUsers(buffer, client);
    }
    else if(strncmp(buffer, wallet,sizeof(wallet)-1) == 0){
        checkWallet(client);
    }
    else if(strncmp(buffer, transf,sizeof(transf)-1) == 0){
        transfer(client);
    }
    else{
        printf("Undefined command\n");
    }
  }
    return 0;
}
Exemple #15
0
void
boot(int argc, char *argv[])
{
	int fd, afd;
	Method *mp;
	char *cmd, cmdbuf[64], *iargv[16];
	char rootbuf[64];
	int islocal, ishybrid;
	char *rp, *rsp, *rdparts;
	int iargc, n;
	char buf[32];
	AuthInfo *ai;

	fmtinstall('r', errfmt);

	/*
	 * we should inherit the standard fds all referring to /dev/cons,
	 * but we're being paranoid.
	 */
	close(0);
	close(1);
	close(2);
	bind("#c", "/dev", MBEFORE);
	open("/dev/cons", OREAD);
	open("/dev/cons", OWRITE);
	open("/dev/cons", OWRITE);
	/*
	 * init will reinitialize its namespace.
	 * #ec gets us plan9.ini settings (*var variables).
	 */
	bind("#ec", "/env", MREPL);
	bind("#e", "/env", MBEFORE|MCREATE);
	bind("#s", "/srv/", MREPL|MCREATE);
	if(getenv("debugboot"))
		debugboot = 1;
#ifdef DEBUG
	print("argc=%d\n", argc);
	for(fd = 0; fd < argc; fd++)
		print("%#p %s ", argv[fd], argv[fd]);
	print("\n");
#endif	/* DEBUG */

	ARGBEGIN{
	case 'k':
		kflag = 1;
		break;
	case 'm':
		mflag = 1;
		break;
	case 'f':
		fflag = 1;
		break;
	}ARGEND

	readfile("#e/cputype", cputype, sizeof(cputype));

	/*
	 *  set up usb keyboard & mouse, if any.
	 *  starts usbd, which mounts itself on /dev.
	 *  starts partfs on first disk, if any, to permit nvram on usb.
	 */
	usbinit(Dontpost);

	/*
	 *  pick a method and initialize it
	 */
	if(method[0].name == nil)
		fatal("no boot methods");
	mp = rootserver(argc ? *argv : 0);
	(*mp->config)(mp);
	islocal = strcmp(mp->name, "local") == 0;
	ishybrid = strcmp(mp->name, "hybrid") == 0;

	/*
	 *  load keymap if it's there.
	 */
	kbmap();

	/* don't trigger aoe until the network has been configured */
	bind("#æ", "/dev", MAFTER);	/* nvram could be here */
	bind("#S", "/dev", MAFTER);	/* nvram could be here */

	/*
	 * read disk partition tables here so that readnvram via factotum
	 * can see them.  ideally we would have this information in
	 * environment variables before attaching #S, which would then
	 * parse them and create partitions.
	 */
	rdparts = getenv("readparts");
	if(rdparts)
		readparts();
	free(rdparts);

	/*
 	 *  authentication agent
	 *  sets hostowner, creating an auth discontinuity
	 */
	if(debugboot)
		fprint(2, "auth...");
	authentication(cpuflag);

	/* leave existing subprocesses in their own namespace */
	rfork(RFNAMEG);

	/*
	 * restart partfs under the new hostowner id
	 */
	usbinit(Post);

	/*
	 *  connect to the root file system
	 */
	fd = (*mp->connect)();
	if(fd < 0)
		fatal("can't connect to file server");
	if(getenv("srvold9p"))
		fd = old9p(fd);
	if(!islocal && !ishybrid){
		if(cfs)
			fd = (*cfs)(fd);
	}
	print("version...");
	buf[0] = '\0';
	n = fversion(fd, 0, buf, sizeof buf);
	if(n < 0)
		fatal("can't init 9P");
	srvcreate("boot", fd);

	/*
	 *  create the name space, mount the root fs
	 */
	if(bind("/", "/", MREPL) < 0)
		fatal("bind /");
	rp = getenv("rootspec");
	if(rp == nil)
		rp = "";
	
	afd = fauth(fd, rp);
	if(afd >= 0){
		ai = auth_proxy(afd, auth_getkey, "proto=p9any role=client");
		if(ai == nil)
			print("authentication failed (%r), trying mount anyways\n");
	}
	if(mount(fd, afd, "/root", MREPL|MCREATE, rp) < 0)
		fatal("mount /");
	rsp = rp;
	rp = getenv("rootdir");
	if(rp == nil)
		rp = rootdir;
	if(bind(rp, "/", MAFTER|MCREATE) < 0){
		if(strncmp(rp, "/root", 5) == 0){
			fprint(2, "boot: couldn't bind $rootdir=%s to root: %r\n", rp);
			fatal("second bind /");
		}
		snprint(rootbuf, sizeof rootbuf, "/root/%s", rp);
		rp = rootbuf;
		if(bind(rp, "/", MAFTER|MCREATE) < 0){
			fprint(2, "boot: couldn't bind $rootdir=%s to root: %r\n", rp);
			if(strcmp(rootbuf, "/root//plan9") == 0){
				fprint(2, "**** warning: remove rootdir=/plan9 entry from plan9.ini\n");
				rp = "/root";
				if(bind(rp, "/", MAFTER|MCREATE) < 0)
					fatal("second bind /");
			}else
				fatal("second bind /");
		}
	}
	close(fd);
	setenv("rootdir", rp);

	settime(islocal, afd, rsp);
	if(afd > 0)
		close(afd);
	swapproc();

	cmd = getenv("init");
	if(cmd == nil){
		sprint(cmdbuf, "/%s/init -%s%s", cputype,
			cpuflag ? "c" : "t", mflag ? "m" : "");
		cmd = cmdbuf;
	}
	iargc = tokenize(cmd, iargv, nelem(iargv)-1);
	cmd = iargv[0];

	/* make iargv[0] basename(iargv[0]) */
	if(iargv[0] = strrchr(iargv[0], '/'))
		iargv[0]++;
	else
		iargv[0] = cmd;

	iargv[iargc] = nil;

	chmod("/srv/" PARTSRV, 0600);
	exec(cmd, iargv);
	fatal(cmd);
}
int main(int argc, char ** argv){
	
	state = WAITING;

	/* Mandatory arguments */
	if( !argv[1] || !argv[2] || !argv[3] ) {
		fprintf(stderr,"server [server->client fifo] [client->server fifo] [password file]\n");
		exit(1);
	}
	
	/* Open the server->client fifo */
	fprintf(stderr,"Opening server->client fifo...\n");
	outputChannel = openFifo(argv[1]);

	/* Open the client->server fifo */
	fprintf(stderr,"Opening client->server fifo...\n");
	inputChannel = openFifo(argv[2]);
	
	do{

		switch(state){
			
			case WAITING : state = handshake();

				if(state == ERROR)	//handshake error
					fprintf(stderr , "\n **** handshake falied **** \n\n");
				else 
					fprintf(stderr , "\n **** handshake succeded **** \n\n");
				break;
			
			case HANDSHAKE : state = authentication(); 
				
				break;
			
			case AUTHENTICATED : state = keyExchange();
				
				break;
				
			case COMMUNICATION : state = communication();
			
				break;
				
			case CLOSING	: state = closeConnection(); 
			
				outputChannel = openFifo(argv[1]);
				inputChannel = openFifo(argv[2]);
	
				if(state == ERROR)	//handshake error
					fprintf(stderr , "\n **** closing falied **** \n\n");
				else 
					fprintf(stderr , "\n **** closing succeded **** \n\n");
				break;

			case ERROR	 :
				
				fprintf(stderr , "\nError during the communication, force shutodown of the client\n\n");
				
				closeConnection(); 
				state = WAITING;
				
				outputChannel = openFifo(argv[1]);
				inputChannel = openFifo(argv[2]);
				
				fprintf(stderr , "\n **** closing succeded **** \n\n");
				
				break; //close connection
				
			default : break;
		
		}

	}while(1);
	

	exit(0);
}
Exemple #17
0
void
boot(int argc, char *argv[])
{
	int fd, afd, srvt;
	Method *mp;
	char *cmd, cmdbuf[64], *iargv[16];
	char rootbuf[64];
	int islocal, ishybrid;
	char *rp, *rsp;
	int iargc, n;
	char buf[32];
	AuthInfo *ai;

	fmtinstall('r', errfmt);

	bind("#c", "/dev", MBEFORE);
	open("/dev/cons", OREAD);
	open("/dev/cons", OWRITE);
	open("/dev/cons", OWRITE);

	/*
	 * init will reinitialize its namespace.
	 * #ec gets us plan9.ini settings (*var variables).
	 */
	bind("#ec", "/env", MREPL);
	bind("#e", "/env", MBEFORE|MCREATE);
	bind("#s", "/srv", MREPL|MCREATE);
	bind("#p", "/proc", MREPL|MCREATE);
	print("\nHello, I am Harvey :-)\n\n");
#ifdef DEBUG
	print("argc=%d\n", argc);
	for(fd = 0; fd < argc; fd++)
		print("%#p %s ", argv[fd], argv[fd]);
	print("\n");
#endif //DEBUG

	ARGBEGIN{
	case 'k':
		kflag = 1;
		break;
	case 'm':
		mflag = 1;
		break;
	case 'f':
		fflag = 1;
		break;
	}ARGEND
	readfile("#e/cputype", cputype, sizeof(cputype));
	readfile("#e/service", service, sizeof(service));

	/* Do the initial ACPI interrupt setup work.
	 * If we don't do this we may not get needed
	 * interfaces. */
	if (getenv("acpiirq"))
		acpiirq();

	/*
	 *  set up usb keyboard, mouse and disk, if any.
	 */
	usbinit();
	print("usbinit done\n");

	/*
	 *  pick a method and initialize it
	 */
	if(method[0].name == nil)
		fatal("no boot methods");
	mp = rootserver(argc ? *argv : 0);
	(*mp->config)(mp);
	islocal = strcmp(mp->name, "local") == 0;
	ishybrid = strcmp(mp->name, "hybrid") == 0;

	/*
	 *  load keymap if it is there.
	 */
	kbmap();

	/*
 	 *  authentication agent
	 */
	authentication(cpuflag);

	print("connect...");

	/*
	 *  connect to the root file system
	 */
	fd = (*mp->connect)();
	if(fd < 0)
		fatal("can't connect to file server");
	if(!islocal && !ishybrid){
		if(cfs)
			fd = (*cfs)(fd);
	}

	print("version...");
	buf[0] = '\0';
	n = fversion(fd, 0, buf, sizeof buf);
	if(n < 0)
		fatal("can't init 9P");
	srvcreate("boot", fd);

	/*
	 *  create the name space, mount the root fs
	 */
	if(bind("/", "/", MREPL) < 0)
		fatal("bind /");
	rp = getenv("rootspec");
	if(rp == nil)
		rp = "";

	afd = fauth(fd, rp);
	if(afd >= 0){
		ai = auth_proxy(afd, auth_getkey, "proto=p9any role=client");
		if(ai == nil)
			print("authentication failed (%r), trying mount anyways\n");
	}
	if(mount(fd, afd, "/root", MREPL|MCREATE, rp, 'M') < 0)
		fatal("mount /");
	rsp = rp;
	rp = getenv("rootdir");
	if(rp == nil)
		rp = rootdir;
	if(bind(rp, "/", MAFTER|MCREATE) < 0){
		if(strncmp(rp, "/root", 5) == 0){
			fprint(2, "boot: couldn't bind $rootdir=%s to root: %r\n", rp);
			fatal("second bind /");
		}
		snprint(rootbuf, sizeof rootbuf, "/root/%s", rp);
		rp = rootbuf;
		if(bind(rp, "/", MAFTER|MCREATE) < 0){
			fprint(2, "boot: couldn't bind $rootdir=%s to root: %r\n", rp);
			if(strcmp(rootbuf, "/root//plan9") == 0){
				fprint(2, "**** warning: remove rootdir=/plan9 entry from plan9.ini\n");
				rp = "/root";
				if(bind(rp, "/", MAFTER|MCREATE) < 0)
					fatal("second bind /");
			}else
				fatal("second bind /");
		}
	}
	close(fd);
	setenv("rootdir", rp);

	settime(islocal, afd, rsp);
	if(afd > 0)
		close(afd);

	cmd = getenv("init");
	srvt = strcmp(service, "terminal");
	if(cmd == nil){
		if(!srvt) {
			sprint(cmdbuf, "/%s/bin/init -%s%s", cputype,
				"t", mflag ? "m" : "");
			cmd = cmdbuf;
		} else {
			sprint(cmdbuf, "/%s/bin/init -%s%s", cputype,
				"c", mflag ? "m" : "");
			cmd = cmdbuf;
		}
	}
	iargc = tokenize(cmd, iargv, nelem(iargv)-1);
	cmd = iargv[0];

	/* make iargv[0] basename(iargv[0]) */
	if((iargv[0] = strrchr(iargv[0], '/')) != nil)
		iargv[0]++;
	else
		iargv[0] = cmd;

	iargv[iargc] = nil;

	exec(cmd, iargv);
	fatal(cmd);
}
Exemple #18
0
int cgiMain (void)
{
	int ret = OK;
	char name[512];
	char cmd[1024];
	char *keyName=NULL;
	char *ErrMsg = NULL;
	char *fileName=NULL;
	char *backName=NULL;
	char *p = NULL;
	char *directory= NULL;
	char *confFile=NULL;
	char *title=NULL;
	struct stat buf	;
	xmlDocPtr doc;
	xmlNodePtr pNode,pRoot;
  	//
	//	认证用户,并且获取用户名
	//
	ret = authentication(NULL,NULL);
	cgiHeaderContent("text/html");
	if (ret)
	{
		//
		//	认证失败
		//
		goto exit;
	}
	//
	//	获取属性文件名
	//
	ErrMsg = "propertyFile";
	ret = cgiGetString(&confFile,2,255,ErrMsg);
	if(ret)
		goto exit;	
	//
	//	获取要使用的属性记录主键
	//
	ErrMsg = "keyName";
	ret = cgiGetString(&keyName,1,255,ErrMsg);
	if (ret)
		goto exit;
	ErrMsg = NULL;
	//
	//	先在属性文件中获取cgi程序
	//
	doc = xmlParseFile(confFile);
	if (NULL == doc)
	{
		ret = NO_MESSAGE;
		ErrMsg="没有打开属性文件<p>或没有属性文件";
		goto exit;
	}
	//
	//	获取根节点
	//
	pRoot = xmlDocGetRootElement(doc);
	if (NULL == pRoot)
	{
		xmlFreeDoc(doc);
		ret = NO_MESSAGE;
		ErrMsg="空的属性文件";
		goto exit;
	}
	pNode = pRoot->xmlChildrenNode;
	//
	//	查找使用的配置树
	//
	while(pNode)
	{
		if (xmlStrcmp(pNode->name,"conf")==0)
		{
			xmlChar * keyValue = NULL;
			//
			//	查找使用的属性记录
			//
			keyValue = xmlGetProp(pNode,"name");
			if (xmlStrcmp(keyValue,(const xmlChar*)keyName)==0)
			{
				break;
			}
			xmlFree(keyValue);
		}
		pNode = pNode->next;
	}
	if (NULL == pNode)
	{
		xmlFreeDoc(doc);
		doc=NULL;
		ret = NO_MESSAGE;
		ErrMsg="没有找到指定的配置项";
		goto exit;
	}
	title = xmlGetProp(pNode,"title");
	if (strcmp(keyName,"systemLog")==0)
	{
		//
		//	系统日志处理部分。
		//
		time_t cur_time;
		struct tm *myTime;
		int i;
	 	cur_time = time(NULL);
		myTime = localtime(&cur_time);
		xmlFreeDoc(doc);
		doc = NULL;
		for(i=1;i<32;i++)
		{
			sprintf(name,"%s.%d",LOG_FILE_NAME,i);
			ret =  stat(name,&buf);
			if ((ret)||(buf.st_mode & S_IFDIR))
				continue;
			break;
		}
		if (i>=32)
		{
			cgiPrintf("<HTML><HEAD><meta http-equiv=\"refresh\" content=\"290;URL=/timeout.html\"></head></HEAD>"
				"<body background=\"/icons/bg01.gif\"><br><center><H2>%s</H2><P></center>"
				"<P><P><HR width=60%><br>"
				"<table align=center><tr><td>没有记录日志</td></tr></TABLE><P><P><HR width=60%><center></BODY></HTML>",title);
			dispOperateInfo(NULL,NO_DISP_MSG,"没有记录日志");
			return 0;		
		}
		//
		// 生成备份文件名
		//
		//snprintf(name,512,"../../htdocs/login/webadminLog.%d-%d-%d.tar.gz",myTime->tm_year+1900,myTime->tm_mon+1,myTime->tm_mday);
		snprintf(name,512,"../download/webadminLog.%d-%d-%d.tar.gz",myTime->tm_year+1900,myTime->tm_mon+1,myTime->tm_mday);
		snprintf(cmd,1024,"cd ./log ; tar -zcf %s sysLog.*",name);

		if (system(cmd)==-1)
			ret = EXEC_FAULT;
		else
		{
			//sprintf(name,"../htdocs/login/webadminLog.%d-%d-%d.tar.gz",myTime->tm_year+1900,myTime->tm_mon+1,myTime->tm_mday);
			sprintf(name,"./download/webadminLog.%d-%d-%d.tar.gz",myTime->tm_year+1900,myTime->tm_mon+1,myTime->tm_mday);
			ret =  stat(name,&buf);
			if (ret)
			{
				ret = BACK_FALSE;	
			}
			else
			{
				//sprintf(name,"/login/webadminLog.%d-%d-%d.tar.gz",myTime->tm_year+1900,myTime->tm_mon+1,myTime->tm_mday);
				sprintf(name,"webadminLog.%d-%d-%d.tar.gz",myTime->tm_year+1900,myTime->tm_mon+1,myTime->tm_mday);
				//sprintf(cmd,"请 <font size =\"14\" color=blue><a href=%s color=red>下载</a> </font>后,妥善保存。",name);
				sprintf(cmd,"请 <font size =\"14\" color=blue><a href=/cgi-bin/download.cgi?downloadFile=%s color=red>下载</a> </font>后,妥善保存。",name);
				cgiPrintf("<HTML><head><link href=\"/icons/all.css\" >"
					"<meta http-equiv=\"refresh\" content=\"290;URL=/timeout.html\"></head>"
					"<BODY background=\"/icons/bg01.gif\"><br><center><H2>备份%s</H2><P></center>"
					"<P><HR width=60%><br><center>%s",title,cmd);
				cgiPrintf("<br><HR width=60%></body></html>");
				dispOperateInfo(NULL,NO_DISP_OK_MSG,NULL);
				return 0;
			}
		}
		goto exit;
	}	
	fileName = xmlGetProp(pNode,"fileName");
	if (fileName)
	{
		ret =  stat(fileName,&buf);
		if ((ret)||(buf.st_mode & S_IFDIR))
		{
			ret = NO_MESSAGE;
			ErrMsg="日志文件不存在";
			goto exit;
		}
	}
	backName = xmlGetProp(pNode,"backName");
	if ((backName==NULL)||(strlen(backName)==0))
	{
		ret = NO_MESSAGE;
		ErrMsg = "没有给出备份文件名";
		goto exit;	
	}
	directory = xmlGetProp(pNode,"directory");
	xmlFree(doc);
	doc = NULL;
	//
	//	获取日志所在的目录
	//
	strncpy(name,fileName,512);
	p=strrchr(name,'/');
	if (p)
	{
		*p=0;
		//
		// 生成备份文件名
		//
		if (directory)
			snprintf(cmd,1023,"cd %s ; tar -zcf %s.tar.gz %s %s",name,backName,p+1,directory);
		else
			snprintf(cmd,1023,"cd %s ; tar -zcf %s.tar.gz %s",name,backName,p+1);
		
	}
	else
	{
		if (directory)
			snprintf(cmd,1023,"tar -zcf %s.tar.gz %s %s",backName,fileName,directory);
		else
			snprintf(cmd,1023,"tar -zcf %s.tar.gz %s",backName,fileName);
	}
	if (system(cmd)==-1)
		ret = EXEC_FAULT;
	else
	{
		sprintf(name,"%s.tar.gz",backName);
		ret =  stat(name,&buf);
		if (ret)
		{
			ret = BACK_FALSE;
		}
		else
		{
			p=strrchr(backName,'/');
			if (p)
				p++;
			else
				p = backName;
			//snprintf(name,512,"/%s.tar.gz",p);
			snprintf(name,512,"%s.tar.gz",p);
			//snprintf(cmd,1023,"请 <font size =\"14\" color=blue><a href=%s color=red>下载</a> </font>后,妥善保存。",name);
			snprintf(cmd,1023,"请 <font size =\"14\" color=blue><a href=/cgi-bin/download.cgi?downloadFile=%s color=red>下载</a> </font>后,妥善保存。",name);
			cgiPrintf("<HTML><head><link href=\"/icons/all.css\" >"
				"<meta http-equiv=\"refresh\" content=\"290;URL=/timeout.html\"></head>"
				"<BODY background=\"/icons/bg01.gif\"><br><center><H2>备份%s</H2><P></center>"
				"<P><HR width=60%><br><center>%s",title,cmd);
			cgiPrintf("<br><HR width=60%></body></html>");			
			snprintf(cmd,1024,"%s",fileName);
			dispOperateInfo(NULL,NO_DISP_MSG,cmd);
			return 0;
		}
	}
exit:
	if (doc) 	xmlFree(doc);
	if (fileName) free(fileName);
	if (backName) free(backName);
	if (directory) free(directory);
	dispOperateInfo(NULL,ret,ErrMsg);
	return ret;
}
Exemple #19
0
/**
 * \brief main function for the delagent
 *
 * There are 2 ways to use the delagent agent:
 *   1. Command Line :: delete/list upload/folder/license from the command line
 *   2. Agent Based  :: run from the scheduler
 *
 * \htmlonly <pre>
 * +-----------------------+
 * | Command Line Analysis |
 * +-----------------------+
 * </pre> \endhtmlonly
 * List or delete uploads.
 *  - -h            :: help (print this message), then exit.
 *  - -i            :: Initialize the DB
 *  - -u            :: List uploads IDs.
 *  - -U #          :: Delete upload ID.
 *  - -f            :: List folder IDs.
 *  - -F #          :: Delete folder ID and all uploads under this folder.
 *  - -T            :: TEST -- do not update the DB or delete any files (just pretend).
 *  - -v            :: Verbose (-vv for more verbose).
 *  - -V            :: print the version info, then exit.
 *  - -c SYSCONFDIR :: Specify the directory for the system configuration.
 *  - --user #      :: user name
 *  - --password #  :: password
 *
 * \htmlonly <pre>
 * +----------------------+
 * | Agent Based Analysis |
 * +----------------------+
 * </pre> \endhtmlonly
 *
 * To run the delagent as an agent
 *  - -s :: Run from the scheduler
 *
 *
 * \param argc the number of command line arguments
 * \param argv the command line arguments
 * \return 0 on a successful program execution
 */
int main (int argc, char *argv[])
{
  int  c;
  int  listProj=0, listFolder=0;
  long delUpload=0, delFolder=0, delFolderParent=0;
  int  scheduler=0; /* should it run from the scheduler? */
  int  gotArg=0;
  char *agentDesc = "Deletes upload.  Other list/delete options available from the command line.";
  char *commitHash;
  char *version;
  char agentRev[myBUFSIZ];
  int  optionIndex = 0;
  char *userName = NULL;
  char *password = NULL;
  int  userId = -1;
  int  userPerm = -1;
  int  returnedCode = 0;

  fo_scheduler_connect(&argc, argv, &pgConn);

  static struct option long_options[] =
  {
    {"user", required_argument, 0, 'n'},
    {"password", required_argument, 0, 'p'},
    {0, 0, 0, 0}
  };

  while ((c = getopt_long (argc, argv, "n:p:ifF:lL:sTuU:P:vVc:h",
         long_options, &optionIndex)) != -1)
  {
    switch (c)
    {
      case 'n':
        userName = optarg;
        break;
      case 'p':
        password = optarg;
        break;
      case 'i':
        PQfinish(pgConn);
        return(0);
      case 'f':
        listFolder=1;
        gotArg=1;
        break;
      case 'F':
        delFolder=atol(optarg);
        gotArg=1;
        break;
      case 'P':
        delFolderParent=atol(optarg);
        gotArg=1;
        break;
      case 's':
        scheduler=1;
        gotArg=1;
        break;
      case 'T':
        Test++;
        break;
      case 'u':
        listProj=1;
        gotArg=1;
        break;
      case 'U':
        delUpload=atol(optarg);
        gotArg=1;
        break;
      case 'v':
        Verbose++;
        break;
      case 'c':
        gotArg=1;
        break; /* handled by fo_scheduler_connect() */
      case 'V':
        printf("%s", BuildVersion);
        PQfinish(pgConn);
        return(0);
      default:
        usage(argv[0]);
        exitNow(-1);
    }
  }

  if (!gotArg)
  {
    usage(argv[0]);
    exitNow(-1);
  }

  if (scheduler != 1)
  {
    if (0 != authentication(userName, password, &userId, &userPerm))
    {
      LOG_FATAL("User name or password is invalid.\n");
      exitNow(-1);
    }

    commitHash = fo_sysconfig("delagent", "COMMIT_HASH");
    version = fo_sysconfig("delagent", "VERSION");
    sprintf(agentRev, "%s.%s", version, commitHash);
    /* Get the Agent Key from the DB */
    fo_GetAgentKey(pgConn, basename(argv[0]), 0, agentRev, agentDesc);

    if (listProj)
    {
      returnedCode = listUploads(userId, userPerm);
    }
    if (returnedCode < 0)
    {
      return returnedCode;
    }
    if (listFolder)
    {
      returnedCode = listFolders(userId, userPerm);
    }
    if (returnedCode < 0)
    {
      return returnedCode;
    }

    alarm(60);  /* from this point on, handle the alarm */
    if (delUpload)
    {
      returnedCode = deleteUpload(delUpload, userId, userPerm);

      writeMessageAfterDelete("upload", delUpload, userName, returnedCode);
    }
    if (delFolder)
    {
      returnedCode = deleteFolder(delFolder, delFolderParent, userId, userPerm);

      writeMessageAfterDelete("folder", delFolder, userName, returnedCode);
    }
  }
  else
  {
    /* process from the scheduler */
    doSchedulerTasks();
  }

  exitNow(0);
  return(returnedCode);
} /* main() */