예제 #1
0
/*
** 'emulate_vdustr' is called to print a string via the 'VDU driver'
*/
void emulate_vdustr(char string[], int32 length) {
  int32 n;
  if (length==0) length = strlen(string);
  echo_off();
  for (n=0; n<length; n++) emulate_vdu(string[n]);	/* Send the string to the VDU driver */
  echo_on();
}
예제 #2
0
파일: n5.c 프로젝트: aksr/heirloom
int 
rdtty(void)
{
	char	onechar;
#if defined (EUC)
	int	i, n;

loop:
#endif /* EUC */

	onechar = 0;
	if (read(0, &onechar, 1) == 1) {
		if (onechar == '\n')
			tty++;
		else 
			tty = 1;
#if !defined (EUC)
		if (tty != 3)
			return(onechar);
#else	/* EUC */
		if (tty != 3) {
			if (!multi_locale)
				return(onechar);
			i = onechar & 0377;
			*mbbuf1p++ = i;
			*mbbuf1p = 0;
			if ((*mbbuf1&~(wchar_t)0177) == 0) {
				twc = 0;
				mbbuf1p = mbbuf1;
			}
			else if ((n = mbtowc(&twc, mbbuf1, mb_cur_max)) <= 0) {
				if (mbbuf1p >= mbbuf1 + mb_cur_max) {
					illseq(-1, mbbuf1, mbbuf1p-mbbuf1);
					twc = 0;
					mbbuf1p = mbbuf1;
					*mbbuf1p = 0;
					i &= 0177;
				} else {
					goto loop;
				}
			} else {
				i = twc | COPYBIT;
				twc = 0;
				mbbuf1p = mbbuf1;
			}
			return(i);
		}
#endif /* EUC */
	}
	popi();
	tty = 0;
#ifdef	NROFF
	if (quiet)
		echo_on();
#endif	/* NROFF */
	return(0);
}
예제 #3
0
void pki_generate(const char *cmd)
{
	arglist *args;
	char buf[2048];
	args = librouter_make_args(cmd);
	char in;



	if (!strcmp(args->argv[1], "privkey")) {
		if (!librouter_pki_get_privkey(buf, sizeof(buf))) {
			printf("%% Private key already exists.\n"
					"%% Continuing will invalidate any "
					"certificate derived from the "
					"current key.\n"
					"%% Do you wish to continue?[y/N]\n");

			/* FIXME Do this in a library function ! */
			/* Wait for input in non-canonical mode */
			canon_off();
			echo_off();
			in = fgetc(stdin);
			canon_on();
			echo_on();
			cish_timeout = 0;
			printf("\n");

			if ((in != 'y') && (in != 'Y'))
				goto free_args;
			/* End of FIXME */
		}

		printf("%% Please wait... computation may take long time!\n");
		if (librouter_pki_gen_privkey(atoi(args->argv[2])) < 0) {
			printf("%% Not possible to generate private key!\n");
			goto free_args;
		}
	} else if (!strcmp(args->argv[1], "csr")) {
		struct pki_dn dn;

		_dn_prompt(&dn);

		if (librouter_pki_gen_csr(&dn) < 0) {
			printf("%% Not possible to generate csr!\n");
			goto free_args;
		}

		librouter_pki_dn_free(&dn);
	}

	if (librouter_ipsec_is_running())
		librouter_ipsec_exec(RESTART);
free_args:
	librouter_destroy_args(args);
}
예제 #4
0
int db_prepare(sqlite3 **db){
    char query[DIM];
    char name[DIM] = {0};
    char password[DIM] = {0};
    char aux1[DIM] = {0};
    char pass[MD5_DIGEST_LENGTH];
    int nbytes = 0;

    sprintf(query, 
            "CREATE TABLE IF NOT EXISTS users(userID INTEGER PRIMARY KEY AUTOINCREMENT, user TEXT, password TEXT, ROL INTEGER);");
    if(db_exec(db, query, CREATE_TABLE) < 0){
        sqlite3_close(*db);
        PDEBUG("DB: Error al crear la tabla\n");
        return -1;
    }

    printf("Nombre del administrador: \n");
    nbytes = read(0, &query, DIM);
    query[nbytes - 1] = '\0'; // eliminamos el intro
    addslahses(query, DIM, name); // escapamos las comillas simples
    printf("Contraseña del administrador: \n");
    echo_off();
    bzero(query, DIM);
    nbytes = read(0, &query, DIM);
    query[nbytes - 1] = '\0'; // eliminamos el intro
    echo_on();

    // creamos la suma
    PDEBUG("DB: Caluclando la suma MD5\n");
    MD5((unsigned char*) query, DIM, (unsigned char*)pass);
    // obtenemos la suma MD5 en caracteres ascii
    md5_sum((unsigned char*) pass, MD5_DIGEST_LENGTH, DIM, aux1);
    addslahses((char *)aux1, DIM, password);

    //creamos la query
    PDEBUG("DB: Insertando al administrador del sistema\n");
    sprintf(query,
            "INSERT INTO users (user, password, rol) VALUES ('%s', '%s', %i);",
            name, password, ADMIN);
    if(db_exec(db, query, INSERT) <0){
        sqlite3_close(*db);
        PDEBUG("DB: Error al insertar el usuario administrador\n");
        return -1;
    }

    PDEBUG("DB: Creando la tabla del log\n");
    sprintf(query,
            "CREATE TABLE IF NOT EXISTS log(postID INTEGER PRIMARY KEY AUTOINCREMENT, author TEXT, text TEXT, time LONG);");
    if(db_exec(db, query, CREATE_TABLE) < 0){
        sqlite3_close(*db);
        PDEBUG("DB: Error al crear la tabla\n");
        return -1;
    }
    return 0;
}
예제 #5
0
std::string prompt_pass()
{
    std::string pass;
    std::cout << "enter password: ";
    echo_off();
    std::getline(std::cin, pass);
    echo_on();
    std::cout << std::endl;

    return pass;
}
예제 #6
0
/*
** 'emulate_printf' provides a more flexible way of displaying formatted
** output than calls to 'emulate_vdustr'. It is used in the same way as
** 'printf' and can take any number of parameters. The text is sent directly
** to the screen
*/
void emulate_printf(char *format, ...) {
  int32 length;
  va_list parms;
  char text [MAXSTRING];
  va_start(parms, format);
  length = vsprintf(text, format, parms);
  va_end(parms);
  echo_off();
  for (n = 0; n < length; n++) emulate_vdu(text[n]);
  echo_on();
}
예제 #7
0
int getnstr(char* buf, int max)
{
  echo_on();
  memset(buf, 0, max);
  int ret=read(pipes[out_fd][0], buf, max);
  if(ret!=0)
    {
      /* prevent buffer underflow */
      if(strlen(buf)-2>=0)
        /* remove the newline */
        buf[strlen(buf)-2]='\0';
    }
  if(ret<0)
    return ERR;
  return OK;
  echo_off();
}
예제 #8
0
static void prompt_passwd(char passwd[])
{
	char		fstr[FSTR_LEN];
	char		tmp[MAX_LEN + 1]; /* +1 for \n from fgets */
	char		*fgets_ret;
	int			echo_off_status;

	memset(tmp, 0, MAX_LEN + 1);
	printf("Enter Password: ");
	echo_off_status = echo_off();
	fgets_ret = fgets(tmp, MAX_LEN + 1, stdin);
	tmp[strlen(tmp) - 1] = '\0'; /* remove the /n that fgets gives */
	strncpy(passwd, tmp, MAX_LEN);
	/* Since echo_on depends on whether echo_off succeeded or not, do echo_on only if echo_off went fine */
	if (0 == echo_off_status)
		echo_on();
}
예제 #9
0
파일: burp.c 프로젝트: sxdtxl/burp
static char *read_stdin(char *buf, int len, bool echo) {
  char *r;

  if (!echo)
    echo_off();

  r = fgets(buf, len, stdin);

  if (!echo) {
    putc('\n', stdout);
    echo_on();
  }

  if (r == NULL)
    return NULL;

  buf[strlen(buf) - 1] = '\0';

  return r;
}
예제 #10
0
파일: cursorpos.c 프로젝트: masui/GitHelp
int main(){
    char buf[10];
    char *p = buf;
    char c;

    echo_off();
    
    write(0,"\x1b[6n",4);

    for (int i=0;;i++){
        read(0,&c,1);
        if(c >= 0x30 && c <= 0x39) *p++ = c;
        if(c == ';') *p++ = ' ';
        if(c == 'R') break;
    }
    *p = '\0';

    echo_on();

    printf("%s\n",buf);
}
예제 #11
0
void pprintf(const char *fmt, ...)
{
	char key;
	va_list ap;
	char buf[1024];

	buf[0] = 0;
	if (PAGER.skip)
		return;

	va_start(ap, fmt);
	vsnprintf(buf, 1023, fmt, ap);
	va_end(ap);
	buf[1023] = 0;

	printf("%s", buf);

	if ((PAGER.tsize) && (strchr(buf, '\n'))) {
		++PAGER.numlines;
		if (PAGER.numlines >= PAGER.tsize) {
			printf("<more>");
			fflush(stdout);
			canon_off();
			echo_off();
			cish_timeout = router_cfg->terminal_timeout;
			key = fgetc(stdin);
			cish_timeout = 0;
			echo_on();
			canon_on();
			printf("\r      \r");
			fflush(stdout);
			if (key == 'q')
				PAGER.skip = 1;
			if (key == '\n')
				PAGER.numlines = PAGER.tsize - 1;
			else
				PAGER.numlines = 1;
		}
	}
}
int main(int argc, char *argv[])
{
    int sockfd, portno, n;
    struct sockaddr_in serv_addr;
    struct hostent *server;

    char buffer[256];
    struct timeval tv;
    fd_set read_set, write_set;

    if (argc < 3) {
        fprintf(stderr,"usage %s hostname port\n", argv[0]);
        exit(0);
    }
    portno = atoi(argv[2]);
    /* Create a socket point */
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if (sockfd < 0)
    {
        perror("ERROR opening socket");
        exit(1);
    }
    server = gethostbyname(argv[1]);
    if (server == NULL) {
        fprintf(stderr,"ERROR, no such host\n");
        exit(0);
    }

    bzero((char *) &serv_addr, sizeof(serv_addr));
    serv_addr.sin_family = AF_INET;
    bcopy((char *)server->h_addr,
          (char *)&serv_addr.sin_addr.s_addr,
          server->h_length);
    serv_addr.sin_port = htons(portno);

    /* Now connect to the server */
    if (connect(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr)) < 0)
    {
        perror("ERROR connecting");
        exit(1);
    }
    struct pollfd fds[2];
    fds[0].fd = STDIN_FILENO;
    fds[1].fd = sockfd;
    fds[0].events = POLLIN;
    fds[1].events = POLLIN | POLLRDHUP;
    int poll_result;
    while (1 && !sig_term) {
        poll_result = poll(fds, 2, 1000 * 3);
        if (fds[1].revents & POLLRDHUP) {
            break;
        }
        if (fds[1].revents & POLLIN) {
            bzero(buffer,256);
            readline(sockfd, buffer, 256);
            if (strcmp(buffer, "[ECHO_OFF]\r\n") == 0) {
                echo_off();
                continue;
            }
            if (strcmp(buffer, "[ECHO_ON]\r\n") == 0) {
                echo_on();
                continue;
            }
            fputs(buffer, stdout);
        }
        if (fds[0].revents & POLLIN) {
            bzero(buffer,256);
            readline(STDIN_FILENO, buffer, 256);
            writeline(sockfd, buffer, strlen(buffer));
        }
    }
    shutdown(sockfd, SHUT_RDWR);
    return 0;
}
예제 #13
0
파일: handler.c 프로젝트: Testla/h3c
void exit_with_echo_on(int arg) {
	putchar('\n');
	echo_on();
	exit(0);
}
예제 #14
0
// reads at most maxlength chars without echoing to the terminal into buf
bool
read_from_keyboard(char* buf, int maxlength, bool echo) {
#if !defined(WIN32)
	int ch, ch_count;

	ch = ch_count = 0;
	fflush(stdout);

	const char end_char = '\n';
	if (!echo) echo_off();
			
	while ( ch_count < maxlength-1 ) {
		ch = getchar();
		if ( ch == end_char ) {
			break;
		} else if ( ch == '\b') { // backspace
			if ( ch_count > 0 ) { ch_count--; }
			continue;
		} else if ( ch == '\003' ) { // CTRL-C
			return FALSE;
		}
		buf[ch_count++] = (char) ch;
	}
	buf[ch_count] = '\0';

	if (!echo) echo_on();
#else
	/*
	The Windows method for getting keyboard input is very different due to
	issues encountered by British users trying to use the pound character in their
	passwords.  _getch did not accept any input from using the alt+#### method of
	inputting characters nor the pound symbol when using a British keyboard layout.
	The solution was to explicitly use ReadConsoleW, the unicode version of ReadConsole,
	to take in the password and down convert it into ascii.
	See Ticket #1639
	*/
	HANDLE hStdin = GetStdHandle(STD_INPUT_HANDLE);

	/*
	There is a difference between the code page the console is reporting and
	the code page that needs to be used for the ascii conversion.  Below code
	acts to provide additional debug information should the need arise.
	*/
	//UINT cPage = GetConsoleCP();
	//printf("Console CP: %d\n", cPage);

	//Preserve the previous console mode and switch back once input is complete.
	DWORD oldMode;
	GetConsoleMode(hStdin, &oldMode);
	//Default entry method is to not echo back what is entered.
	DWORD newMode = ENABLE_LINE_INPUT | ENABLE_PROCESSED_INPUT;
	if(echo)
	{
		newMode |= ENABLE_ECHO_INPUT;
	}

	SetConsoleMode(hStdin, newMode);

	int cch;
	//maxlength is passed in even though it is a fairly constant value, so need to dynamically allocate.
	wchar_t *wbuffer = new wchar_t[maxlength];
	if(!wbuffer)
	{
		return FALSE;
	}
	ReadConsoleW(hStdin, wbuffer, maxlength, (DWORD*)&cch, NULL);
	SetConsoleMode(hStdin, oldMode);
	//Zero terminate the input.
	cch = min(cch, maxlength-1);
	wbuffer[cch] = '\0';

	--cch;
	//Strip out the newline and return that ReadConsoleW appends and zero terminate again.
	while (cch >= 0)
	{
		if(wbuffer[cch] == '\r' || wbuffer[cch] == '\n')
			wbuffer[cch] = '\0';
		else
			break;
		--cch;
	}

	//Down convert the input into ASCII.
	int converted = WideCharToMultiByte(CP_ACP, WC_COMPOSITECHECK, wbuffer, -1, buf, maxlength, NULL, NULL);

	delete[] wbuffer;
#endif

	return TRUE;
}
예제 #15
0
/*
 * This routine implements the 'print' command.  It displays the data
 * buffer in hexadecimal.  It is only useful for checking the disk for
 * a specific set of data (by reading it then printing it).
 */
int
a_print()
{
	int	i, j, lines, nomore = 0;
	int	c, one_line = 0;
	int	tty_lines = get_tty_lines();

	/*
	 * If we are running out of command file, don't page the output.
	 * Otherwise we are running with a user.  Turn off echoing of
	 * input characters so we can page the output.
	 */
	if (option_f || (!isatty(0)) || (!isatty(1)))
		nomore++;
	else {
		enter_critical();
		echo_off();
		charmode_on();
		exit_critical();
	}
	/*
	 * Loop through the data buffer.
	 */
	lines = 0;
	for (i = 0; i < scan_size * SECSIZE / sizeof (int); i += 6) {
		/*
		 * Print the data.
		 */
		for (j = 0; j < 6; j++)
			if (i + j < scan_size * SECSIZE / sizeof (int))
				fmt_print("0x%08x  ",
				*((int *)((int *)cur_buf + i + j)));
		fmt_print("\n");
		lines++;

		/*
		 * If we are paging and hit the end of a page, wait for
		 * the user to hit either space-bar, "q", return,
		 * or ctrl-C before going on.
		 */
		if (one_line ||
		    (!nomore && (lines % (tty_lines - 1) == 0))) {
			/*
			 * Print until first screenfull
			 */
			if (lines < (tty_lines -1))
				continue;
			/*
			 * Get the next character.
			 */
			(void) printf("- hit space for more - ");
			c = getchar();
			(void) printf("\015");
			one_line = 0;
			/*
			 * Handle display one line command (return key)
			 */
			if (c == '\012') {
				one_line++;
			}
			/* Handle Quit command */
			if (c == 'q') {
				(void) printf(
				"                       \015");
				goto PRINT_EXIT;
			}
			/* handle ^D */
			if (c == '\004')
				fullabort();
		}
	}
	/*
	 * If we were doing paging, turn echoing back on.
	 */
PRINT_EXIT:
	if (!nomore) {
		enter_critical();
		charmode_off();
		echo_on();
		exit_critical();
	}
	return (0);
}
예제 #16
0
void canon_on(void)
{
	echo_on();
}
예제 #17
0
void str_cli(FILE *fp, int sockfd) {

	int			i, j, maxfdp1, n, logined;
	fd_set		rset, wset;
	char		sendline[MAXLINE], recvline[MAXLINE], username[21], password[34], npassword[34];
	short int 	permission;

	FD_ZERO(&rset);
	FD_ZERO(&wset);

	logined = 0;

	for ( ; ; ) {

		if (logined == 0) {
			FD_SET(sockfd, &wset);
		}
		else {
			FD_SET(fileno(fp), &rset);
			FD_SET(sockfd, &rset);
		}
		
		maxfdp1 = ( (fileno(fp) > sockfd)?fileno(fp):sockfd ) + 1;
		
		select(maxfdp1, &rset, &wset, NULL, NULL);

		memset(recvline, '\0', MAXLINE);
		memset(sendline, '\0', MAXLINE);

		if (FD_ISSET(sockfd, &rset)) {	/* socket is readable */
			
			memset(recvline, '\0', MAXLINE);
			if ( read(sockfd, recvline, MAXLINE) == 0 ) {
				fputs("Service is not avaliable.", stdout);
				exit(0);
	        }

	        if (recvline[0] == '\0')
	        	continue;

	        fputs(recvline, stdout);
	        fflush(stdout);
		}

		if (FD_ISSET(fileno(fp), &rset)) {  /* input is readable */
			
			read(fileno(fp), sendline, MAXLINE );

			printf("fp: %s", sendline);

			/* Change passwd */

			if( !strcmp(sendline, "passwd\n") ) {

				memset(password, '\0', 34);
				memset(npassword, '\0', 34);
				memset(sendline, '\0', MAXLINE);

				printf("New password: "******"\nRetype new password: "******"\n:: Change password complete!\n");

					sprintf(sendline, "passwd %s\n", password);
					//printf("[%s]\n", sendline);

					if ( write(sockfd, sendline, strlen(sendline)) <= 0 ){
						printf("server is dead.\n");
						exit(1);
					}
				}
				else {
					printf("\n:: Change password failed, please try again.\n> ");
				}

				memset(password, '\0', 34);
				memset(npassword, '\0', 34);
				memset(sendline, '\0', MAXLINE);

				//continue;
			}

			/* Create Account */

			else if( !strcmp(sendline, "newaccount\n") ) {

				memset(username, '\0', 21);
				memset(password, '\0', 34);
				memset(sendline, '\0', MAXLINE);
				memset(recvline, '\0', MAXLINE);

				permission = 0;

				printf("Username: "******"Password: "******"\nPermission: ");
				scanf("%hd", &permission);

				// Encrypt password. 
				strcpy(password, str2md5(password, strlen(password)));

				sprintf(sendline, "newaccount %s %s %hd\n", username, password, permission);
				//printf("[%s]\n", sendline);

				if ( write(sockfd, sendline, strlen(sendline)) <= 0 ){
					printf("server is dead.\n");
					exit(1);
				}

		        if ( read(sockfd, recvline, MAXLINE) == 0 ) {
					fputs("Service is not avaliable.", stdout);
					exit(1);
				}

		        fputs(recvline, stdout);
		        fflush(stdout);

				memset(password, '\0', 34);
				memset(username, '\0', 21);
				memset(sendline, '\0', MAXLINE);
				memset(recvline, '\0', MAXLINE);

				//continue;
			}

			for(i = 0; i < strlen(sendline); i++) {
				if(sendline[i] != '\n')
					continue;
				sendline[i+1] = '\0';
			}

			if(strlen(sendline) > 0)
				FD_SET(sockfd, &wset);
		}

		if (FD_ISSET(sockfd, &wset)) {

			//printf("sock is writeable!\n");

			if (logined == 0) {
				
				printf("Username: "******"Password: "******"lg %s %s\n", username, password);
				//printf("[%s]\n", sendline);

				if ( write(sockfd, sendline, strlen(sendline)) <= 0 ){
					printf("server is dead.\n");
					exit(1);
				}

				if ( read(sockfd, recvline, MAXLINE) == 0 ) {
					fputs("Service is not avaliable.", stdout);
					exit(0);
				}

		        fputs(recvline, stdout);
		        fflush(stdout);

		        if ( strncmp(recvline, "\nLogin Success!\n", 16) == 0) {
		        	logined = 1;
			        FD_SET(fileno(fp), &rset);
					FD_SET(sockfd, &rset);
					FD_CLR(sockfd, &wset);
				}

				memset(sendline, '\0', MAXLINE);
				memset(username, '\0', 21);
				memset(password, '\0', 34);
			}

			else if ( write(sockfd, sendline, strlen(sendline)) <= 0 ){
				printf("server is dead.\n");
				exit(1);
			}

			FD_CLR(sockfd, &wset);
		}
	}
}
예제 #18
0
파일: cli5.c 프로젝트: dracon416/sci-clat
int main(int argc, char** argv){

    int sock = 0; // declaración del socket e inicializado a 0
    int error = 0; /** declaramos una variable que nos servirá para detectar
                    * errores
                    */
    int serverTalk = 0;
    //socklen_t length = (socklen_t) sizeof (struct sockaddr_in); // tamaño del paquete
    //struct sockaddr_in addr; // definimos el contenedor de la dirección
    unsigned int port = 5678; /** creamos la variable que identifica el puerto
                               * de conexión, siendo el puerto por defecto 5678
                               */
    char dir[DIM] = "localhost"; /** definimos la cadena que contendrá a la
                                  * dirección del servidor, la cual, será por
                                  * defecto localhost
                                  */
    //struct hostent*  server; // estructura utilizada para la gestión de direcciones
    sms auxMsj;
    char name[DIM] = {0};
    int nbytes = 0; // contador de bytes leidos y escritos
    char aux[DIM] = {0};
    // inicializamos las variables de SSL
    BIO* bio = NULL;
    SSL_CTX* ctx = NULL;
    SSL* ssl = NULL;
    char cert[DIM] = "/usr/share/doc/libssl-dev/demos/sign/cert.pem";

    //analizamos los parámetros de entrada
    int i = 0;
    for(; i < argc; i++){
        if(strcmp(argv[i], "-p") == 0){ // leemos el puerto
            if(argc <= i + 1 || isNum(argv[i+1]) == 0){
                perror("Se esperaba un número después de -p");
                exit(-1);
            }else{
                PDEBUG("INFO: Puerto identificado\n");
                i++;
                port = atoi(argv[i]);
            }
            continue;
        }else if(strcmp(argv[i], "-d") == 0){ // dirección de destino
            if(argc <= i + 1){
                perror("Se esperaba una dirección después de -d");
                exit(-1);
            }else{
                PDEBUG("INFO: Destino identificado");
                i++;
                strcpy(dir, argv[i]);
            }
            continue;
        }else if(strcmp(argv[i], "-cert") == 0){ // dirección de destino
            if(argc <= i + 1){
                perror("Se esperaba una ruta de certificado después de -cert");
                exit(-1);
            }else{
                PDEBUG("INFO: Destino identificado");
                i++;
                strcpy(cert, argv[i]);
            }
            continue;
        }
    }

    /***********************************SSL************************************/
    PDEBUG("INFO: Iniciamos la librería SSL\n");
    SSL_load_error_strings(); // strings de error
    SSL_library_init(); // iniciams la libreria en sí
    ERR_load_BIO_strings(); // strings de error de BIO
    OpenSSL_add_all_algorithms(); // inicializamos los algoritmos de la librería

    PDEBUG("INFO: Conectando...\n");
    PDEBUG("INFO: Inicializando los punteros\n");
    ctx = SSL_CTX_new(SSLv23_client_method());
    ssl = NULL;
    PDEBUG("INFO: Cargamos el certificado\n");
    if(SSL_CTX_load_verify_locations(ctx, cert, NULL) == 0){
        char aux[] = "ERROR: No se pudo comprobar el certificado\n";
        write(WRITE, aux, strlen(aux));
        exit(-1);
    }
    PDEBUG("INFO: Inicializando BIO\n");
    bio = BIO_new_ssl_connect(ctx);
    BIO_get_ssl(bio, &ssl);
    if(ssl == 0){
        char aux[] = "ERROR: Error al crear el objeto ssl\n";
        write(WRITE, aux, strlen(aux));
        exit(-1);
    }
    PDEBUG("INFO: Estableciendo el modo de trabajo, no queremos reintentos\n");
    SSL_set_mode(ssl, SSL_MODE_AUTO_RETRY);
    PDEBUG("INFO: Intentando realizar la conexión\n");
    PDEBUG("INFO: Conectando a -> ");
    sprintf(aux, "%s:%i", dir, port);
    PDEBUG(aux);PDEBUG("\n");
    BIO_set_conn_hostname(bio, aux);
    PDEBUG("INFO: Verificando la conexión\n");
    if (BIO_do_connect(bio) < 1){
        char aux[] = "ERROR: al conectar el BIO\n";
        write(WRITE, aux, strlen(aux));
        exit(-1);
    }
    //PDEBUG("INFO: Verificando el resultado de la conexión\n");
    //printf("--%i-%i--\n", X509_V_OK, SSL_get_verify_result(ssl));
    //if (SSL_get_verify_result(ssl) != X509_V_OK) {
    //    char aux[] = "ERROR: verificar el resultado de la conexión\n";
    //    write(WRITE, aux, strlen(aux));
    //    exit(-1);
    //}

    PDEBUG("INFO: Conectado\n");
    /***********************************SSL************************************/

    ////Creamos el socket
    //PDEBUG("INFO: Creando el socket\n");
    //sock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
    ////Comprobamos si ha ocurrido un error al crear el socket
    //if(sock < 0){
    //    char aux[] = "ERROR: creación del socket {{socket()}}:\n";
    //    write(WRITE, aux, strlen(aux));
    //    exit(-1);
    //}
    //
    //
    //addr.sin_family = AF_INET; // familia AF_INET
    //addr.sin_port = htons(port); // definimos el puerto de conexión
    //PDEBUG("INFO: Traducimos la dirección del servidor\n");
    //server = gethostbyname(dir); /** convertimos la dirección dada
    //                              * en una dirección válida para el
    //                              * equipo y la metemos en addr
    //                              */
    ////Comprobamos si ha ocurrido un error obtener el host
    //if(server == NULL){
    //    write(WRITE, "ERROR: Host inválido\n", DIM);
    //    // terminamos la ejecución del programa
    //    exit(-1);
    //}
    //// copiamos el contenido correspondiente a la dirección de server en addr
    //bcopy(server->h_addr, &(addr.sin_addr.s_addr), server->h_length);
    //
    //// realizamos la conexión al servidor
    //PDEBUG("INFO: Nos conectamos al servidor\n");
    //error = connect(sock, (struct sockaddr*) &addr, length);
    //if(error < 0){
    //    char aux[] = "ERROR: al establecer la conexion con el servidor {{connect()}}: \n";
    //    write(WRITE, aux, strlen(aux));
    //    // terminamos la ejecución del programa
    //    exit(-1);
    //}
    //
    //PDEBUG("INFO: Conexión establecida\n");
    PDEBUG("INFO: Esperando mensaje de bienvenida\n");

    memset(&auxMsj, 0, sizeof(sms));
    if(client_read(bio, &auxMsj, sizeof(sms)) <= 0){
        PDEBUG("INFO: El socket está cerrado\n");
        perror("Error al leer contenido del socket porque está cerrado\n");
        perror("El cliente se parará\n");
        exit(-1);
    }


    // atendemos la autentificación del cliente
    do{
        bzero(aux, DIM);
        sprintf(aux, "%s ~$> %s\n", auxMsj.name, auxMsj.text);
        write(WRITE, aux, DIM);
        bzero(&auxMsj.text, SMS_LEN);

        if(auxMsj.flag == MSJ){ // si es un mensaje, solo imprimimos por la salida estandar

            memset(&auxMsj, 0, sizeof(sms));
            if(client_read(bio, &auxMsj, sizeof(sms)) <= 0){
                PDEBUG("INFO: El socket está cerrado\n");
                perror("Error al leer contenido del socket porque está cerrado\n");
                perror("El cliente se parará\n");
                exit(-1);
            }
            continue;

        }

        if(auxMsj.flag == REQ_PASS){ // si es password desactivamos el echo
            echo_off();
        }
        nbytes = read(READ, &auxMsj.text, SMS_LEN);
        if(auxMsj.flag == REQ_PASS){// si es password activamos el echo
            echo_on();
        }
        auxMsj.text[nbytes - 1] = '\0'; // eliminamos el retorno de carro
        
        // nos salimos?
        if(strcmp(auxMsj.text, "-x") == 0){
            PDEBUG("EXIT: Cerrando el cliente, avisando al servidor...\n");
            auxMsj.flag = CLI_EXIT;
            client_write(bio, &auxMsj, sizeof(sms));
            PDEBUG("EXIT: Cerrando el socket\n");
            shutdown(sock, 2);
            PDEBUG("EXIT: Cerrando el cliente\n");
            exit(0);
        }else{ // es un mensaje
            strcpy(name, auxMsj.text); // hacemos una copia del nombre introducido para no perderlo
            if(auxMsj.flag == REQ_TEXT){
                auxMsj.flag = REQ_AUTH;
            }else if(auxMsj.flag == REQ_PASS){ // entonces REQ_PASS
                auxMsj.flag = CHECK_PASS;
            }else if(auxMsj.flag == REQ_ROOM){ // entonces REQ_ROOM
                auxMsj.flag = CHECK_ROOM;
            }
            client_write(bio, &auxMsj, sizeof(sms));
            memset(&auxMsj, 0, sizeof(sms));
            if(client_read(bio, &auxMsj, sizeof(sms)) <= 0){
                PDEBUG("INFO: El socket está cerrado\n");
                perror("Error al leer contenido del socket porque está cerrado\n");
                perror("El cliente se parará\n");
                exit(-1);
            }
        }
    }while(auxMsj.flag != OK);

    PDEBUG("INFO: Usuario conectado\n");
    printf("Usuario conectado...\n");
    
    fd_set desc, descCopy; // definimos un descriptor que contendrá nuestros descriptores
    //inicializamos la lista de conexiones
    FD_ZERO(&desc);
    // Inicio del bit descriptor sock con el valor de sock
    int fd;
	if(BIO_get_fd(bio, &fd) < 0){
            write(WRITE, "ERROR: crear le descriptor %s\n", DIM);
            // terminamos la ejecución del programa
            exit(-1);
	}
    FD_SET (fd, &desc);
    // Inicio del bit descriptor connList con el valor del descriptor de entrada estándar
    FD_SET (READ, &desc);

    while(1){
        // hacemos una copia de seguridad para asegurarnos de no perder los datos
        descCopy = desc;
        // ¿Hay algún socket listo para leer?
        PDEBUG("INFO: ¿Hay algún socket listo para leer?\n");
        error = select(fd + 1, &descCopy, NULL, NULL, NULL);
        //Comprobamos si ha ocurrido un error al ponernos a escuchar
        if(error < 0){
            write(WRITE, "ERROR: al realizar la selección {{select()}}: %s\n", DIM);
            // terminamos la ejecución del programa
            exit(-1);
        }

        // recorriendo los sockets para ver los que están activos
        PDEBUG("INFO: recorriendo los sockets para ver los que están activos\n");
        if(FD_ISSET(fd, &descCopy)){
            PDEBUG("INFO: Nuevo mensaje recibido\n");
            if(client_read(bio, &auxMsj, sizeof(sms)) <= 0){
                PDEBUG("INFO: El socket está cerrado\n");
                perror("Error al leer contenido del socket porque está cerrado\n");
                perror("El cliente se parará\n");
                exit(-1);
            }

            switch(auxMsj.flag){
                case OK: // mensaje de aceptacion, mismo comportamiento que msj
                case MSJ:  // mensaje recibido
                    if(serverTalk != 1 || strcmp(auxMsj.name, SERVER) == 0){
                        PDEBUG("INFO: Recibido mensaje\n");
                        sprintf(aux, "%s ~$> %s\n", auxMsj.name, auxMsj.text);
                        write(WRITE, aux, strlen(aux));
                        sync();
                    }
                    break;
                case SERV_EXIT: // el servidor se va a cerrar
                    PDEBUG("EXIT: El servidor se está cerrando, se dejará de leer\n");
                    shutdown(sock, SHUT_RDWR);
                    sprintf(aux, "%s ~$> Servidor desconectado\n", SERVER);
                    write(WRITE, aux, strlen(aux));
                    sprintf(aux, "El proceso cliente se cerrará\n");
                    write(WRITE, aux, strlen(aux));
                    exit(0);
                    break;
                default:
                    sprintf(aux, "Recibido un mensaje mal formado\n");
                    write(WRITE, aux, strlen(aux));
                    sync();
                    break;
            }
        }else if(FD_ISSET(READ, &descCopy)){
            PDEBUG("INFO: Nuevo mensaje escrito\n");

            bzero(&auxMsj.text, SMS_LEN); // inicializamos el array
            nbytes = read(READ, &auxMsj.text, SMS_LEN); // leemos de la entrada estándar
            auxMsj.text[nbytes - 1] = 0; // eliminamos el retorno de carro

            // nos salimos?
            if(strcmp(auxMsj.text, "-x") == 0 && serverTalk != 1){

                PDEBUG("EXIT: Cerrando el cliente, avisando al servidor...\n");
                auxMsj.flag = CLI_EXIT;

            }else if(strcmp(auxMsj.text, "--serv") == 0){ // queremos hablar con el servidor

                PDEBUG("SERV_ADMIN: Iniciando la comunicación directa con el servidor\n");
                sprintf(aux, "%s ~$> Iniciada conversación con el servidor\n", SERVER);
                write(WRITE, aux, strlen(aux));
                serverTalk = 1;
                continue;

            }else if(sscanf(auxMsj.text, "--mp %s", aux) == 1){ // queremos hablar con el servidor

                PDEBUG("MP: Mensaje privado detectado\n");
                strcpy(auxMsj.to, aux);
                sprintf(aux, "%s ~$> Inserte el mensaje privado\n", SERVER);
                write(WRITE, aux, strlen(aux));
                auxMsj.flag = MP;
                nbytes = read(READ, &auxMsj.text, SMS_LEN); // leemos de la entrada estándar
                auxMsj.text[nbytes - 1] = 0; // eliminamos el retorno de carro

            }else{ // es un mensaje

                if(serverTalk == 1){

                    PDEBUG("SERV_ADMIN: Enviando mensaje al servidor\n");
                    auxMsj.flag = SERV_ADMIN;

                    if(strcmp(auxMsj.text, "exit") == 0){

                        serverTalk = 0;
                        sprintf(aux, "%s ~$> Envio de mensajes de configuración terminada:\n", SERVER);
                        write(WRITE, aux, strlen(aux));
                        continue;

                    }

                }else{

                    auxMsj.flag = MSJ;

                }
            }

            strcpy(auxMsj.name, name); // hacemos una copia del nombre introducido para no perderlo
            PDEBUG("INFO: Enviando mensaje...\n");
            client_write(bio, &auxMsj, sizeof(sms));
            PDEBUG("INFO: Mensaje Enviado\n");

            // nos salimos?
            if(auxMsj.flag == CLI_EXIT){

                PDEBUG("EXIT: Cerrando el socket\n");
                shutdown(sock, SHUT_RDWR);
                PDEBUG("EXIT: Cerrando el cliente\n");
                exit(0);
                
            }
        }
    }
    
    return 0;
}
예제 #19
0
파일: main.c 프로젝트: renbaoke/h3c
int main(int argc, char **argv) {
	int ch;
	char *interface = NULL;
	char *username = NULL;
	char *password = NULL;
	int can_free_pw = 0;
	char md5_method = MD5_XOR;

	while ((ch = getopt(argc, argv, "i:u:p:m:h")) != -1) {
		switch (ch) {
		case 'i':
			interface = optarg;
			break;
		case 'u':
			username = optarg;
			break;
		case 'p':
			password = optarg;
			break;
		case 'm': {
				char *use_md5 = "md5";
				if(strcmp(optarg,use_md5) == 0) {
					md5_method = MD5_MD5;
				}
			}
			break;
		case 'h':
			usage(stdout);
			exit(0);
		default:
			usage(stderr);
			exit(-1);
		}
	}

	/* must run as root */
	if (geteuid() != 0) {
		fprintf(stderr, "Run as root, please.\n");
		exit(-1);
	}

	if (interface == NULL || username == NULL) {
		usage(stderr);
		exit(-1);
	}

	if (h3c_set_username(username) != SUCCESS) {
		fprintf(stderr, "Failed to set username.\n");
		exit(-1);
	}

	if (password == NULL) {
		if ((password = (char *) malloc(PWD_LEN)) == NULL) {
			fprintf(stderr, "Failed to malloc: %s\n", strerror(errno));
			exit(-1);
		}
		printf("Password for %s:", username);

		signal(SIGINT, exit_with_echo_on);
		signal(SIGTERM, exit_with_echo_on);

		echo_off();
		fgets(password, PWD_LEN - 1, stdin);
		can_free_pw = 1;
		echo_on();

		/* replace '\n' with '\0', as it is NOT part of password */
		password[strlen(password) - 1] = '\0';
		putchar('\n');
	}

	if (h3c_set_password(password) != SUCCESS) {
		fprintf(stderr, "Failed to set password.\n");
		if (can_free_pw) {
			free(password);
		}
		exit(-1);
	}
	if (can_free_pw) {
		free(password);
	}

	if (h3c_init(interface) != SUCCESS) {
		fprintf(stderr, "Failed to initialize: %s\n", strerror(errno));
		exit(-1);
	}

	if (h3c_start() != SUCCESS) {
		fprintf(stderr, "Failed to start: %s\n", strerror(errno));
		exit(-1);
	}

	signal(SIGINT, exit_handler);
	signal(SIGTERM, exit_handler);

	for (;;) {
		if (h3c_response(success_handler, failure_handler, unkown_eapol_handler,
				unkown_eap_handler, got_response_handler, md5_method) != SUCCESS) {
			fprintf(stderr, "Failed to response: %s\n", strerror(errno));
			exit(-1);
		}
	}

	return 0;
}
예제 #20
0
int main()
{
        struct timeb start, end, repeat_start, repeat_end;

        Input input = Input(KB_DEVICE);
        show_splash();

        Board board = Board(20, 10);

        echo_off();
        ftime(&start);
        ftime(&repeat_start);

        std::size_t i, size;
        std::deque<int> pressed_keys;
        std::deque<int> repeated_keys;

        for(; ; )
        {
                input._update();

                for(pressed_keys = input.get_pressed_keys(), i = 0, size = pressed_keys.size(); i < size; i++)
                {
                        switch(pressed_keys[i])
                        {
                        case KEY_UP:
                                board.rotate_block(CLOCKWISE);
                                break;
                        case KEY_LEFTSHIFT:
                        case KEY_RIGHTSHIFT:
                                board.hold_block();
                                break;
                        case KEY_LEFTCTRL:
                        case KEY_RIGHTCTRL:
                                board.rotate_block(COUNTERCLOCKWISE);
                                break;
                        case KEY_SPACE:
                                board.drop_block();
                                break;
                        case KEY_Q:
                                echo_on();
                                return 0;
                                break;
                        case KEY_DOWN:
                                board.move_block_down();
                                break;
                        case KEY_LEFT:
                                board.move_block_left();
                                break;
                        case KEY_RIGHT:
                                board.move_block_right();
                                break;
                        default:
                                break;
                        }
                }

                ftime(&repeat_end);
                if((repeat_end.time * 1000 + repeat_end.millitm) - (repeat_start.time * 1000 + repeat_start.millitm) >= 30)
                {
                        for(repeated_keys = input.get_repeated_keys(), i = 0, size = repeated_keys.size(); i < size; i++)
                        {
                                switch(repeated_keys[i])
                                {
                                case KEY_DOWN:
                                        board.move_block_down();
                                        break;
                                case KEY_LEFT:
                                        board.move_block_left();
                                        break;
                                case KEY_RIGHT:
                                        board.move_block_right();
                                        break;
                                default:
                                        break;
                                }
                        }

                        ftime(&repeat_start);
                }

                ftime(&end);
                if(end.time - start.time >= 1)
                {
                        board.move_block_down();
                        ftime(&start);
                }

                usleep(20000);
        }
}