Пример #1
0
char *daemon_expect(THREAD_CTX *TTX, const char *command) {
    char buf[128];
    char *cmd;

    cmd = daemon_getline(TTX, 300);
    if (cmd == NULL)
        return NULL;

    while(strncasecmp(cmd, command, strlen(command))) {
        if (!strncasecmp(cmd, "QUIT", 4)) {
            free(cmd);
            daemon_reply(TTX, LMTP_QUIT, "2.0.0", "OK");
            return NULL;
        }
        if (!strncasecmp(cmd, "RSET", 4)) {
            snprintf(buf, sizeof(buf), "%d OK", LMTP_OK);
            if (send_socket(TTX, buf)<=0)
                return NULL;
            free(cmd);
            return "RSET";
        }

        snprintf(buf, sizeof(buf), "%d 5.0.0 Need %s here.", LMTP_BAD_CMD, command);

        if (send_socket(TTX, buf)<=0)
            return NULL;
        free(cmd);
        cmd = daemon_getline(TTX, 300);
        if (cmd == NULL)
            return NULL;
    }
    return cmd;
}
Пример #2
0
// This is the main transfer func which does the transfer and sleep job
static snd_pcm_sframes_t a2dp_transfer2(snd_pcm_ioplug_t * io, char *buf, int32_t datatoread)
{
	snd_pcm_a2dp_t *a2dp = io->private_data;
	int transfer = 0;

	// Connect if needed and send
	a2dp_connect(a2dp);
	if (transfer >= 0)
		transfer = send_socket(a2dp->sk, &datatoread, sizeof(datatoread));
	if (transfer >= 0)
		transfer = send_socket(a2dp->sk, buf, datatoread);

	// Disconnect if error detected
	if (transfer < 0)
		a2dp_disconnect(a2dp);

	// The data are sent to the daemon that act as a proxy thus we double transfer delay to compensate latency
	a2dp_timer_notifyframe(&a2dp->TimerInfos);
	a2dp_timer_sleep(&a2dp->TimerInfos, 4 * A2DPTIMERPREDELAY);

	// Stats
	if (a2dp->TimerInfos.display > 0) {
		if (errno != 0 || transfer <= 0) {
			syslog(LOG_INFO, "send_socket(%d bytes)=%d (errno=%d:%s)", datatoread, transfer, errno, strerror(errno));
		}
	}
	// update pointer, tell alsa we're done
	a2dp->num += datatoread / a2dp->frame_bytes;

	return datatoread / a2dp->frame_bytes;
}
Пример #3
0
/* add the recently connected client to the game as a player */
void join_player(struct socket_node *socket) {
   struct packet_version packet;
   struct packet_welcome packet2;
   int i;
   struct action_node *action;
   struct socket_node *p;
   socket->player = get_free_player();
   init_player(socket->player, INIT_PLAYER_HUMAN);
/* send version */
   packet.version = swap_int(PROGRAM_VERSION);
   send_socket(socket, PACKET_VERSION, &packet, sizeof(struct packet_version));
   
/* send welcome */
   packet2.player = swap_int(socket->player);
   send_socket(socket, PACKET_WELCOME, &packet2, sizeof(struct packet_welcome));

/* send all previous players to the new client */
   for (i = 0; i < NUM_PLAYERS; i++) {
      if (IS_ACTIVE(i) && i != socket->player) {
         send_player_info(socket, i, 0);
      /* send any already selected action */
         action = find_action(i, current_turn);
         if (action && action->action != ACTION_NOTHING)
            send_action(socket, i, current_turn);
      }
   }

/* send the new player to ALL clients */
   for (p = socket_list; p != NULL; p = p->next) {
      if (p->type == SOCKET_CLIENT)
         send_player_info(p, socket->player, 1);
   }

   telegram("\n%s has\nconnected to the server.\n", GET_NAME(socket->player));
}
Пример #4
0
/*
 * Cette fonction permet de choisir entre se connecter directement au serveur,
 * ou de s'inscrire avant de se connecter.
 * il reçoit en paramètre une structure de type user_t et un
 * pointeur sur un buffer qui sera utilisé pour former les requêtes.
 */
state req_sign_up(struct user_t * client, char * buffer)
{ 
	char buff[50]; // permet de recevoir les réponse du serveur
	int tentative = 0;
	do // tant que le login est libre (4 tentatives)
	{
		do // LOGIN
		{
			__fpurge(stdin);
			if(tentative <4)
			{
				if(tentative == 0)printf("\nVeuillez rentrer un login: "******"\nTENTATIVE %d :Veuillez rentrer un autre login SVP: ", tentative +1);
			}
			else
			{
				echecm("4 tentatives");
			}
		}while ((scanf("%s", client->login) != 1 ));
		tentative ++;

		clean_b(buffer);	
		sprintf(buffer, "REQ_VERIFY_LOGIN = %s \n", client->login);
		send_socket(client, buffer);
		
		rcv_socket(client, buff); // réponse du serveur
		
		debugm(buff); debugm("Réception");
	}while(strncmp(buff, "LOGIN_FREE", 10) != 0);	//Sort de la boucle si la réponse est LOGIN_FREE
	
	printf("%sLe nom d'utilisateur est libre.\n%s", GREEN, NORM);
	printf("Entrer un mot de passe SVP: ");
	scanf("%s", client->password);
	
	clean_b(buffer);	
	sprintf(buffer, "REQ_NEW_USER = %s + %s \n", client->login, client->password);
	send_socket(client, buffer); clean_b(buffer);
	
	rcv_socket(client, buffer); // réponse du serveur
	
	if(strcmp(buffer, "USER_ADDED \n") == 0) // si l'utilisateur a bien été ajouté
	{
		greenm("Votre compte a bien été créé !");
		return SUCCESS;
	}
	else
	{
		echecm("L'utilisateur n'a pas pû être ajouté");
		printf(buffer);
		return FAIL;
	}
}
Пример #5
0
// return type
static int
ctrl_cmd(struct socket_server *ss, struct socket_message *result) {
    int fd = ss->recvctrl_fd;
    // the length of message is one byte, so 256+8 buffer size is enough.
    uint8_t buffer[256];
    uint8_t header[2];
    block_readpipe(fd, header, sizeof(header));
    int type = header[0];
    int len = header[1];
    block_readpipe(fd, buffer, len);
    // ctrl command only exist in local fd, so don't worry about endian.
    switch (type) {
    case 'S':
        return start_socket(ss,(struct request_start *)buffer, result);
    case 'B':
        return bind_socket(ss,(struct request_bind *)buffer, result);
    case 'L':
        return listen_socket(ss,(struct request_listen *)buffer, result);
    case 'K':
        return close_socket(ss,(struct request_close *)buffer, result);
    case 'O':
        return open_socket(ss, (struct request_open *)buffer, result);
    case 'X':
        result->opaque = 0;
        result->id = 0;
        result->ud = 0;
        result->data = NULL;
        return SOCKET_EXIT;
    case 'D':
        return send_socket(ss, (struct request_send *)buffer, result, PRIORITY_HIGH, NULL);
    case 'P':
        return send_socket(ss, (struct request_send *)buffer, result, PRIORITY_LOW, NULL);
    case 'A': {
        struct request_send_udp * rsu = (struct request_send_udp *)buffer;
        return send_socket(ss, &rsu->send, result, PRIORITY_HIGH, rsu->address);
    }
    case 'C':
        return set_udp_address(ss, (struct request_setudp *)buffer, result);
    case 'T':
        setopt_socket(ss, (struct request_setopt *)buffer);
        return -1;
    case 'U':
        add_udp_socket(ss, (struct request_udp *)buffer);
        return -1;
    default:
        fprintf(stderr, "socket-server: Unknown ctrl %c.\n",type);
        return -1;
    };

    return -1;
}
Пример #6
0
int do_processing(SOCKET* sockfd)
{
    int result = 0;

    if (*sockfd != INVALID_SOCKET)
    {
        int read;
        char buffer[256] = {0};
		
		struct timeval tv = {0};
		tv.tv_usec = 100;
		
		FD_SET fdset = {0};
		FD_SET (*sockfd, &fdset);
		
		result = select (0, &fdset, NULL, NULL, &tv);
		
		if (result > 0)
		{	
			if ((read = recv_socket(sockfd, buffer, 255)) >= 0)
			{
				send_socket(sockfd, buffer, read);
				result = 1;
			}
		}
    }

    return result;
}
Пример #7
0
int do_processing(SOCKET *sockfd)
{
    int result = 0;

    if (*sockfd != INVALID_SOCKET)
    {
        int read;
        char buffer[256] = {0};
		struct fd_set testeset={0};
        int clilen,selection;
        struct sockaddr_in cli_addr;
		struct timeval tv = {0};
		tv.tv_usec = 100;
		
        listen(*sockfd, MAX_SOCKETS);
        clilen = sizeof(cli_addr);
		
		FD_SET(*sockfd,&testeset);
		selection = select(0,&testeset,NULL,NULL,&tv);
		if(selection>0)
		{
        if ((read = recv_socket(sockfd, buffer, 255)) > 0)
        {
            send_socket(sockfd, buffer, read);
            result = 1;
        }
		else	
			return -1;
		}
    }

    return result;
}
Пример #8
0
void echo(SOCKET* sock, char* buffer, int to_send, int uppercase)
{
	if(uppercase)
	{
		
	}
	
	printf("enviando '%s' %d bytes\n\n", buffer, to_send);
	int len = send_socket(sock, buffer, to_send);
	
	if(len >= 0)
		len = send_socket(sock, 0, 1);
		
	else
		perror("ERROR writing to socket");
}
Пример #9
0
// return type
static int
ctrl_cmd(struct socket_server *ss, union socket_message *result) {
	int fd = ss->server_fd;
	uint8_t header[2];
	block_read(fd, header, sizeof(header));
	int type = header[0];
	int len = header[1];
	char buffer[256];
	// ctrl command only exist in local fd, so don't worry about endian.
	block_read(fd, buffer, len);
	switch (type) {
	case 'B':
		return bind_socket(ss,(struct request_bind *)buffer, result);
	case 'L':
		return listen_socket(ss,(struct request_listen *)buffer, result);
	case 'K':
		return close_socket(ss,(struct request_close *)buffer, result);
	case 'O':
		return open_socket(ss, (struct request_open *)buffer, result);
	case 'X':
		return SOCKET_EXIT;
	case 'D':
		return send_socket(ss, (struct request_send *)buffer, result);
	default:
		fprintf(stderr, "socket-server: Unknown ctrl %c.\n",type);
		return -1;
	};

	return -1;
}
Пример #10
0
int main(int argc, char **argv) 
{
		SOCKET sock = connect_socket(IP_ADDR, PORT);
		BOOL must_continue = sock != INVALID_SOCKET;
		
		char buf[MAXLINE];
		char* prompt = "sldb> ";
		while( must_continue ){
			//snprintf(buf, MAXLINE, "?1 ? ?\r\n");
			
			write(STDOUT_FILENO, prompt, strlen(prompt));
      int n_readed = read(STDIN_FILENO, buf, MAXLINE);
			must_continue &= !send_socket(sock, buf, n_readed);
			
			while( must_continue ){
				int len = read_line(sock, buf, MAXLINE);
				BOOL is_empty_line = len == 0;
				if( is_empty_line ){
					break;
				}
				write(STDOUT_FILENO, buf, len);
				printf("\r\n");
				BOOL must_close = !strcmp(buf, "!close");
				must_continue &= !must_close;
			}
		}
		
		int iResult = close_socket(sock);
    return iResult;
}
Пример #11
0
/**
 * write a buffer to socket with timeout
 * and receive an ack 0 || 1
 */
static int write_line(int sock, int top, const char* type)
{

   int bytes_read, bytes_sent;
   int fileid;
   char bf[512];


   memset(bf, '\0', sizeof(bf));
   
   if (top == 0) {
     if ( ((bytes_sent=send_socket(sock , nodelogger_buf , sizeof(nodelogger_buf) , SOCK_TIMEOUT_CLIENT)) <= 0)) {
        fprintf(stderr,"%%%%%%%%%%%% NODELOGGER: socket closed at send  %%%%%%%%%%%%%%\n");
        return(-1);
     }
   } else {
     /* create tolog file */
     if ((fileid = open(TOP_LOG_PATH,O_WRONLY|O_CREAT,0755)) < 1 ) {
                        fprintf(stderr,"Nodelogger: could not create toplog:%s\n",TOP_LOG_PATH);
			/* return something */
     }

     if ( ((bytes_sent=send_socket(sock , nodelogger_buf_top , sizeof(nodelogger_buf_top) , SOCK_TIMEOUT_CLIENT)) <= 0)) {
       fprintf(stderr,"%%%%%%%%%%%% NODELOGGER: socket closed at send  %%%%%%%%%%%%%%\n");
       return(-1);
     }
   }

   if ( (bytes_read=recv_socket (sock , bf , sizeof(bf) , SOCK_TIMEOUT_CLIENT)) <= 0 ) {
     fprintf(stderr,"%%%%%%%%%%%% NODELOGGER: socket closed at recv   %%%%%%%%%%%%%%\n");
     return(-1);
   }
   if ( bf[0] != '0' ) {
     bf[bytes_read > 0 ? bytes_read : 0] = '\0';  
     fprintf(stderr,"Nodelogger::write_line: Error=%s bf=%s nodelogger_buf=%s\n",strerror(errno),bf,nodelogger_buf);
     return(-1);
   }
   /* Notify user if he is using nfs mode, this will be done at begin and end of root node 
      Note : we notify user when using inter-dependencies
   if ( top != 0 && (strcmp(type,"begin") == 0 || strcmp(type,"endx") == 0 ) ) NotifyUser ( sock , top ,'S', _seq_exp_home  );  */
   

   return(0);
}
Пример #12
0
/* only used by the server */
void send_all_sockets(int type, void *data, int size) {
   struct socket_node *p;

   if (server) {
      for (p = socket_list; p != NULL; p = p->next) {
         if (p->type != SOCKET_SERVER)
            send_socket(p, type, data, size);
      }
   }
}
Пример #13
0
int daemon_reply(
    THREAD_CTX *TTX,
    int reply,
    const char *ecode,
    const char *text)
{
    char buf[128];
    snprintf(buf, sizeof(buf), "%d %s%s%s",
             reply, ecode, (ecode[0]) ? " " : "", text);
    return send_socket(TTX, buf);
}
Пример #14
0
/* this function is called when the alarm expires */
void report()
{
    struct timeval end;
    gettimeofday(&end, NULL);
    double elapse = (end.tv_sec + (end.tv_usec/1000000.0)) - (start.tv_sec + (start.tv_usec/1000000.0));
	fprintf(stderr,"COUNT|%ld|1|lps\n", iter);
    fprintf(stderr, "TIME|%f\n", elapse);
    char buff[BUFFER_SIZE];
    sprintf(buff, "COUNT|%ld|1|lps|%f\n", iter, elapse);
    send_socket(buff);
    close_socket();
	exit(0);
}
Пример #15
0
int main(int argc, char *argv[])
{
    SOCKET sock = create_socket();

    if (sock != INVALID_SOCKET)
    {
        if (connect_socket(&sock, IP_ADDR, PORT_NO, 10))
        {
            char buffer[256] = {0};
            int n;

            keyboard_read("Please enter the message: ", buffer, 255);

            n = send_socket(&sock, buffer, strlen(buffer));

            if (n >= 0)
            {
                memset((void*) buffer, 0, 256);
                n = recv_socket(&sock, buffer, 256);

                if (n >= 0)
                {
                    printf("%s\n", buffer);
                }
                else
                {
                    puts("ERROR reading from socket");
                }
            }
            else
            {
                puts("ERROR writing to socket");
            }
        }
        else
        {
            puts("ERROR connecting");
        }

        disconnect_socket(&sock);
    }
    else
    {
        puts("ERROR opening socket");
    }

    destroy_socket(&sock);

    return 0;
}
Пример #16
0
static int a2dp_connect(snd_pcm_a2dp_t * a2dp)
{
	if (a2dp->sk <= 0) {
		int sockfd = make_client_socket();
		a2dp->sk = -1;
		if (sockfd > 0) {
			int32_t client_type = A2DPD_PLUGIN_PCM_WRITE;
			if (send_socket(sockfd, &client_type, sizeof(client_type)) == sizeof(client_type)) {
				// Fill stream informations
				AUDIOSTREAMINFOS StreamInfos = INVALIDAUDIOSTREAMINFOS;
				StreamInfos.rate = a2dp->rate;
				StreamInfos.channels = a2dp->channels;
				StreamInfos.bitspersample = a2dp->frame_bytes/a2dp->channels;
				switch(a2dp->io.format) {
				case SND_PCM_FORMAT_S8:     StreamInfos.format = A2DPD_PCM_FORMAT_S8; break;
				case SND_PCM_FORMAT_U8:     StreamInfos.format = A2DPD_PCM_FORMAT_U8; break;
				case SND_PCM_FORMAT_S16_LE: StreamInfos.format = A2DPD_PCM_FORMAT_S16_LE; break;
				default: StreamInfos.format = A2DPD_PCM_FORMAT_UNKNOWN; break;
				}
				if (send_socket(sockfd, &StreamInfos, sizeof(StreamInfos)) == sizeof(StreamInfos)) {
					a2dp->sk = sockfd;
					syslog(LOG_INFO, "Connected a2dp %p, sk %d, fps %f", a2dp, a2dp->sk, a2dp->TimerInfos.fps);
				} else {
					syslog(LOG_WARNING, "Couldn't send stream informations");
					a2dp_disconnect(a2dp);
				}
			} else {
				close_socket(sockfd);
				syslog(LOG_WARNING, "Connected a2dp %p, sk %d, Authorisation failed", a2dp, a2dp->sk);
			}
		} else {
			syslog(LOG_ERR, "Socket failed a2dp %p, sk %d", a2dp, a2dp->sk);
		}
	}
	return 0;
}
Пример #17
0
int socket_server::ctrl_cmd(struct socket_message * result) 
{
    int fd = recvctrl_fd;
    uint8_t buffer[256];
    uint8_t header[2];
    block_readpipe(fd, (void *)header, sizeof(header));
    int type = header[0];
    int len = header[1];
    block_readpipe(fd, buffer, len);

    switch (type) {
        case 'S':
            return start_socket((struct request_start *)buffer, result);
        case 'B':
            return bind_socket((struct request_bind *)buffer, result);
        case 'L':
            return listen_socket((struct request_listen *)buffer, result);
        case 'K':
            return close_socket((struct request_close *)buffer, result);
        case 'O':
            return open_socket((struct request_open *)buffer, result);;
        case 'X':
            result->opaque = 0;
            result->ud = 0;
            result->id = 0;
            result->data = nullptr;
            return SOCKET_EXIT;
        case 'D':
            printf("*****************send data*******************\n");
            return send_socket((struct request_send *)buffer, result, PRIORITY_HIGH);
        case 'P':
            break;
        case 'A':
            break;
        case 'C':
            break;
        case 'T':
            setopt_socket((struct request_setopt *)buffer);
            return -1;
        case 'U':
            break;
        default:
            fprintf(stderr, "socket-server: unknown ctrl %c.\n", type);
            break;
    }
    return -1;
}
Пример #18
0
void redrobd_rc_net_server_thread::send_client(void *data,
					       unsigned nbytes)
{
  long rc;
  unsigned actual_bytes;

  // Send data to client
  rc = send_socket(m_client_sd,
		   data,
		   nbytes,
		   true,  // Send all
		   &actual_bytes);
  
  if (rc != SOCKET_SUPPORT_SUCCESS) {
    throw client_com_error;
  }
}
Пример #19
0
/** 
* Notify User if he is using nfs mode, This notification will happen twice a run :
* in the beginning and end of root Node
*/
static void NotifyUser (int sock , int top , char mode, const char * _seq_exp_home)
{
   char bf[512];
   char *rcfile, *lmech ;
   int bytes_sent, bytes_read, fileid, num;

   if ( top != 0 ) {
         if ( (rcfile=malloc( strlen (getenv("HOME")) + strlen("/.maestrorc") + 2 )) != NULL ) {
	     sprintf(rcfile, "%s/.maestrorc", getenv("HOME"));
        if ( (lmech=SeqUtil_getdef( rcfile, "SEQ_LOGGING_MECH", _seq_exp_home )) != NULL ) {
		  switch ( mode ) {
		        case 'S': /* mserver is up but logging mechanism is through NFS */
			         strcat(nodelogger_buf_notify,"Please initialize SEQ_LOGGING_MECH=server in ~/.maestrorc file\n");
	                         if ( strcmp(lmech,"nfs") == 0 ) {
                                     if ( ((bytes_sent=send_socket(sock , nodelogger_buf_notify , sizeof(nodelogger_buf_notify) , SOCK_TIMEOUT_CLIENT)) <= 0)) {
	                                     free(rcfile);free(lmech);
                                             return;
                                     }
                                     if ( (bytes_read=recv_socket (sock , bf , sizeof(bf) , SOCK_TIMEOUT_CLIENT)) <= 0 ) {
	                                     free(rcfile);free(lmech);
                                             return;
                                     }
		                  }
				  break;
		        case 'N': /* mserver is down and logging mech. is through NFS */
			         strcat(nodelogger_buf_notify_short,"Please start mserver and initialize SEQ_LOGGING_MECH=server in ~/.maestrorc file\n");
	                         if ( strcmp(lmech,"nfs") == 0 ) {
                                       if ( (fileid = open(LOG_PATH,O_WRONLY|O_CREAT,0755)) > 0 ) {
 	                                        off_t s_seek=lseek(fileid, 0, SEEK_END);
		                                num = write(fileid, nodelogger_buf_notify_short, strlen(nodelogger_buf_notify_short));
		                                fsync(fileid);
		                                close(fileid);
                                       } 
				 } 
				 break;
                  }
		  free(lmech);
	     }
	     free(rcfile);
	 }
   }

}
Пример #20
0
int do_processing(int sockfd)
{
    int result = 0;

    if (sockfd != INVALID_SOCKET)
    {
        int read;
        char buffer[256] = {0};

        if ((read = recv_socket(sockfd, buffer, 255)) > 0)
        {
            send_socket(sockfd, buffer, read);
            result = 1;
        }

        if (read == 0)
            errno = 0;
    }

    return result;
}
Пример #21
0
int send_HMAC( std::string data, std::string& response, int sock, keyinfo &conn_info ){
    // Attempt to HMAC and send the message
    std::string wrappedData;
    std::string wrappedResponse;
    std::string unwrappedResponse;
    
    if( data.length() != 0 )
        if( compileHashedMessage( data, conn_info.hmackey, wrappedData ) != 0 ){
            return -1;
        }
    
    int err = send_socket( wrappedData, wrappedResponse, sock );
    if( err != 0 ) return err;
    
    if( extractData( wrappedResponse, conn_info.hmackey, unwrappedResponse ) != 0 ){
        return -1;
    }
    
    response.assign( unwrappedResponse );
    
    return 0;
}
Пример #22
0
/*
 * Funktion zum Beenden des Servers
 */
void quitServer(int error, char message[MAX_ERRORMESSAGE])
{
	int i;
	int socket, userId;

	for (i = 0; i < MAX_PLAYER;  i++)
	{
		socket = getSocketDescr(i);
		userId = getUserId(i);
		if(error == ERROR && i != 0 && userId != 99)
		{
			send_socket(socket, ErrorWarning, message , error);

			infoPrint("Schliesse SocketDescr.: %d", socket);
			close(socket);
		}
	}
	infoPrint("Beende den Server...");
	remove("pid_server");
	closeSHM();														/*Shared Memory schließen*/
	infoPrint("Done!");
	exit(0);
}
Пример #23
0
int do_processing(SOCKET* sockfd)
{
	int dataLen = 0;
	char buffer[2048] = {0};
	int result = 0;
	
	if (*sockfd != INVALID_SOCKET)
    {
		if ((dataLen = recv(*sockfd, buffer, 2048, 0)) > 0)
        {
            printf("recebido: %s | %d bytes\n", buffer, dataLen);
			
			buffer[dataLen] = 0;
			send_socket(sockfd, buffer, strlen(buffer));
		
			//switch(buffer[0])
			//{
			//	case 1:
			//		echo(sockfd, buffer+2, buffer[1], 0);
			//		break;
			//	case 2:
			//		echo(sockfd, buffer+2, buffer[1], 1);
			//		break;
			//	case 3:
			//		break;
			//	case 4:
			//		break;
			//	default:
			//		printf("packet desconhecido recebido.\n");
			//}
			
            result = 1;
        }
	}
	
	return result;
}
Пример #24
0
int main(int argc, char **argv) {
	send_socket();
	
	return EXIT_SUCCESS;
}
Пример #25
0
void *process_connection(void *ptr) {
    char *server_ident = _ds_read_attribute(agent_config, "ServerIdent");
    THREAD_CTX *TTX = (THREAD_CTX *) ptr;
    AGENT_CTX *ATX = NULL;
    char *input, *cmdline = NULL, *token, *ptrptr;
    buffer *message = NULL;
    char *parms=NULL, *p=NULL;
    int i, locked = -1, invalid = 0;
    int server_mode = SSM_DSPAM;
    char *argv[64];
    char buf[1024];
    int tries = 0;
    int argc = 0;
    FILE *fd = 0;

    if (_ds_read_attribute(agent_config, "ServerMode") &&
            !strcasecmp(_ds_read_attribute(agent_config, "ServerMode"), "standard"))
    {
        server_mode = SSM_STANDARD;
    }

    if (_ds_read_attribute(agent_config, "ServerMode") &&
            !strcasecmp(_ds_read_attribute(agent_config, "ServerMode"), "auto"))
    {
        server_mode = SSM_AUTO;
    }

    /* Initialize a file descriptor hook for dspam to use as stdout */

    fd = fdopen(TTX->sockfd, "w");
    if (!fd) {
        close(TTX->sockfd);
        goto CLOSE;
    }
    setbuf(fd, NULL);

    TTX->packet_buffer = buffer_create(NULL);
    if (TTX->packet_buffer == NULL)
        goto CLOSE;

    /*
     *  Send greeting banner
     *  in auto mode, we want to look like a regular LMTP server so we don't
     *  cause any compatibility problems. in dspam mode, we can change this.
     */

    snprintf(buf, sizeof(buf), "%d DSPAM %sLMTP %s %s",
             LMTP_GREETING,
             (server_mode == SSM_DSPAM) ? "D" : "",
             VERSION,
             (server_mode == SSM_DSPAM) ? "Authentication Required" : "Ready");
    if (send_socket(TTX, buf)<=0)
        goto CLOSE;

    TTX->authenticated = 0;

    /* LHLO */

    input = daemon_expect(TTX, "LHLO");
    if (input == NULL)
        goto CLOSE;
    if (server_mode == SSM_AUTO && input[4]) {
        char buff[128];

        /*
         *  Auto-detect the server mode based on whether or not the ident is
         *  assigned a password in dspam.conf
         */

        snprintf(buff, sizeof(buff), "ServerPass.%s", input + 5);
        chomp(buff);
        if (_ds_read_attribute(agent_config, buff))
            server_mode = SSM_DSPAM;
        else
            server_mode = SSM_STANDARD;
    }
    free(input);

    /* Advertise extensions */

    if (daemon_extension(TTX, (server_ident) ? server_ident :
                         "localhost.localdomain")<=0)
        goto CLOSE;

    if (daemon_extension(TTX, "PIPELINING")<=0)
        goto CLOSE;

    if (daemon_extension(TTX, "ENHANCEDSTATUSCODES")<=0)
        goto CLOSE;

    if (server_mode == SSM_DSPAM)
        if (daemon_extension(TTX, "DSPAMPROCESSMODE")<=0)
            goto CLOSE;

    if (daemon_extension(TTX, "8BITMIME")<=0)
        goto CLOSE;

    if (daemon_reply(TTX, LMTP_OK, "", "SIZE")<=0)
        goto CLOSE;

    /* Main protocol loop */

    while(1) {
        char processmode[256];
        parms = NULL;

        /* Configure a new agent context for each pass */

        ATX = calloc(1, sizeof(AGENT_CTX));
        if (ATX == NULL) {
            LOG(LOG_CRIT, ERR_MEM_ALLOC);
            daemon_reply(TTX, LMTP_TEMP_FAIL, "4.3.0", ERR_MEM_ALLOC);
            goto CLOSE;
        }

        if (initialize_atx(ATX)) {
            LOG(LOG_ERR, ERR_AGENT_INIT_ATX);
            daemon_reply(TTX, LMTP_BAD_CMD, "5.3.0", ERR_AGENT_INIT_ATX);
            goto CLOSE;
        }

        /* MAIL FROM (and authentication, if SSM_DSPAM) */

        processmode[0] = 0;
        while(!TTX->authenticated) {
            input = daemon_expect(TTX, "MAIL FROM");

            if (RSET(input))
                goto RSET;

            if (input == NULL)
                goto CLOSE;
            else {
                char *pass, *ident;
                chomp(input);

                if (server_mode == SSM_STANDARD) {
                    TTX->authenticated = 1;

                    ATX->mailfrom[0] = 0;
                    _ds_extract_address(ATX->mailfrom, input, sizeof(ATX->mailfrom));

                    if (daemon_reply(TTX, LMTP_OK, "2.1.0", "OK")<=0) {
                        free(input);
                        goto CLOSE;
                    }
                } else {
                    char id[256];
                    pass = ident = NULL;
                    id[0] = 0;
                    if (!_ds_extract_address(id, input, sizeof(id))) {
                        pass = strtok_r(id, "@", &ptrptr);
                        ident = strtok_r(NULL, "@", &ptrptr);
                    }

                    if (pass && ident) {
                        char *serverpass;
                        char *ptr, *ptr2, *ptr3;

                        snprintf(buf, sizeof(buf), "ServerPass.%s", ident);
                        serverpass = _ds_read_attribute(agent_config, buf);

                        snprintf(buf, sizeof(buf), "ServerPass.%s", ident);
                        if (serverpass && !strcmp(pass, serverpass)) {
                            TTX->authenticated = 1;

                            /* Parse PROCESSMODE service tag */

                            ptr = strstr(input, "DSPAMPROCESSMODE=\"");
                            if (ptr) {
                                char *mode;
                                int i;
                                ptr2 = strchr(ptr, '"')+1;
                                mode = ptr2;
                                while((ptr3 = strstr(ptr2, "\\\"")))
                                    ptr2 = ptr3+2;
                                ptr3 = strchr(ptr2+2, '"');
                                if (ptr3)
                                    ptr3[0] = 0;
                                strlcpy(processmode, mode, sizeof(processmode));

                                ptr = processmode;
                                for(i=0; ptr[i]; i++) {
                                    if (ptr[i] == '\\' && ptr[i+1] == '"') {
                                        strcpy(ptr+i, ptr+i+1);
                                    }
                                }
                                LOGDEBUG("process mode: '%s'", processmode);
                            }

                            if (daemon_reply(TTX, LMTP_OK, "2.1.0", "OK")<=0) {
                                free(input);
                                goto CLOSE;
                            }
                        }
                    }
                }

                free(input);
                if (!TTX->authenticated) {
                    LOGDEBUG("fd %d authentication failure.", TTX->sockfd);

                    if (daemon_reply(TTX, LMTP_AUTH_ERROR, "5.1.0",
                                     "Authentication Required")<=0)
                    {
                        free(input);
                        goto CLOSE;
                    }

                    tries++;
                    if (tries>=3) {
                        struct timeval tv;
                        tv.tv_sec = 5;
                        tv.tv_usec = 0;
                        select(0, NULL, NULL, NULL, &tv);
                        goto CLOSE;
                    }
                }
            }
        }

        /* MAIL FROM response */

        snprintf(buf, sizeof(buf), "%d OK", LMTP_OK);

        argc = 1;
        argv[0] = "dspam";
        argv[1] = 0;

        /* Load open-LMTP configuration parameters */

        if (server_mode == SSM_STANDARD) {
            parms = _ds_read_attribute(agent_config, "ServerParameters");
            if (parms) {
                p = strdup(parms);
                if (p) {
                    token = strtok_r(p, " ", &ptrptr);
                    while(token != NULL && argc<63) {
                        argv[argc] = token;
                        argc++;
                        argv[argc] = 0;
                        token = strtok_r(NULL, " ", &ptrptr);
                    }
                }
            }
        }

        /* RCPT TO */

        while(ATX->users->items == 0 || invalid) {
            free(cmdline);
            cmdline = daemon_getline(TTX, 300);

            while(cmdline &&
                    (!strncasecmp(cmdline, "RCPT TO:", 8) ||
                     !strncasecmp(cmdline, "RSET", 4)))
            {
                char username[256];
                char *at = NULL;

                if (!strncasecmp(cmdline, "RSET", 4)) {
                    snprintf(buf, sizeof(buf), "%d OK", LMTP_OK);
                    if (send_socket(TTX, buf)<=0)
                        goto CLOSE;
                    goto RSET;
                }

                if (_ds_extract_address(username, cmdline, sizeof(username)) ||
                        username[0] == 0 || username[0] == '-' || username[0] == '@')
                {
                    if ((server_mode == SSM_DSPAM) || (server_mode == SSM_STANDARD && _ds_validate_address(username) == 0)) {
                        daemon_reply(TTX, LMTP_BAD_CMD, "5.1.2", ERR_LMTP_BAD_RCPT);
                        goto GETCMD;
                    }
                }

                if (_ds_match_attribute(agent_config, "Broken", "case"))
                    lc(username, username);

                /* Chop of @.* from the recipient */
                if (_ds_match_attribute(agent_config, "StripRcptDomain", "on")) {
                    at = strchr(username, '@');
                    if (at != NULL)
                        *at = '\0';
                }

                if (server_mode == SSM_DSPAM) {
                    nt_add(ATX->users, username);
                }
                else {
                    if (!parms || !strstr(parms, "--user "))
                        nt_add(ATX->users, username);

                    if (!ATX->recipients) {
                        ATX->recipients = nt_create(NT_CHAR);
                        if (ATX->recipients == NULL) {
                            LOG(LOG_CRIT, ERR_MEM_ALLOC);
                            goto CLOSE;
                        }
                    }
                    if (at != NULL)
                        *at = '@'; /* always add complete address (user@domain) to recipient list */
                    nt_add(ATX->recipients, username);
                }

                if (daemon_reply(TTX, LMTP_OK, "2.1.5", "OK")<=0)
                    goto CLOSE;

GETCMD:
                free(cmdline);
                cmdline = daemon_getline(TTX, 300);
            }

            if (cmdline == NULL)
                goto CLOSE;

            if (!strncasecmp(cmdline, "RSET", 4)) {
                snprintf(buf, sizeof(buf), "%d OK", LMTP_OK);
                if (send_socket(TTX, buf)<=0)
                    goto CLOSE;
                goto RSET;
            }

            if (!strncasecmp(cmdline, "quit", 4)) {
                daemon_reply(TTX, LMTP_OK, "2.0.0", "OK");
                goto CLOSE;
            }

            /* Parse DSPAMPROCESSMODE input and set up process arguments */

            if (server_mode == SSM_DSPAM && processmode[0] != 0) {
                token = strtok_r(processmode, " ", &ptrptr);
                while(token != NULL && argc<63) {
                    argv[argc] = token;
                    argc++;
                    argv[argc] = 0;
                    token = strtok_r(NULL, " ", &ptrptr);
                }
            }

            invalid = 0;
            if (process_arguments(ATX, argc, argv) || apply_defaults(ATX))
            {
                LOG(LOG_ERR, ERR_AGENT_INIT_ATX);
                daemon_reply(TTX, LMTP_NO_RCPT, "5.1.0", ERR_AGENT_INIT_ATX);
                invalid = 1;
            } else if (ATX->users->items == 0) {
                daemon_reply(TTX, LMTP_NO_RCPT, "5.1.1", ERR_AGENT_USER_UNDEFINED);
            }
        }

        ATX->sockfd = fd;
        ATX->sockfd_output = 0;

        /* Something's terribly misconfigured */

        if (check_configuration(ATX)) {
            LOG(LOG_ERR, ERR_AGENT_MISCONFIGURED);
            daemon_reply(TTX, LMTP_BAD_CMD, "5.3.5", ERR_AGENT_MISCONFIGURED);
            goto CLOSE;
        }

        /* DATA */

        if (cmdline != NULL) {
            if (strncasecmp(cmdline, "DATA", 4)) {
                if (daemon_reply(TTX, LMTP_BAD_CMD, "5.0.0", "Need DATA Here")<0)
                    goto CLOSE;
                input = daemon_expect(TTX, "DATA");
                if (input == NULL)
                    goto CLOSE;
                if (RSET(input))
                    goto RSET;
            }
        }

        if (daemon_reply(TTX, LMTP_DATA, "", INFO_LMTP_DATA)<=0)
            goto CLOSE;

        /*
         *  Read in the message from a DATA. I personally like to just hang up on
         *  a client stupid enough to pass in a NULL message for DATA, but you're
         *  welcome to do whatever you want.
         */

        message = read_sock(TTX, ATX);
        if (message == NULL || message->data == NULL || message->used == 0) {
            daemon_reply(TTX, LMTP_FAILURE, "5.2.0", ERR_LMTP_MSG_NULL);
            goto CLOSE;
        }

        /*
         *  Lock a database handle. We currently use the modulus of the socket
         *  id against the number of database connections in the cache. This
         *  seems to work rather well, as we would need to lock up the entire
         *  cache to wrap back around. And if we do wrap back around, that means
         *  we're busy enough to justify spinning on the current lock (vs. seeking
         *  out a free handle, which there likely are none).
         */

        i = (TTX->sockfd % TTX->DTX->connection_cache);
        LOGDEBUG("using database handle id %d", i);
        if (TTX->DTX->flags & DRF_RWLOCK) {
            if (ATX->operating_mode == DSM_CLASSIFY ||
                    ATX->training_mode == DST_NOTRAIN   ||
                    (ATX->training_mode == DST_TOE && ATX->classification == DSR_NONE))
            {
                pthread_rwlock_rdlock(&TTX->DTX->connections[i]->rwlock);
            } else {
                pthread_rwlock_wrlock(&TTX->DTX->connections[i]->rwlock);
            }
        } else {
            pthread_mutex_lock(&TTX->DTX->connections[i]->lock);
        }
        LOGDEBUG("handle locked");
        ATX->dbh = TTX->DTX->connections[i]->dbh;
        locked = i;

        /* Process the message by tying back into the agent functions */

        ATX->results = nt_create(NT_PTR);
        if (ATX->results == NULL) {
            LOG(LOG_CRIT, ERR_MEM_ALLOC);
            goto CLOSE;
        }
        process_users(ATX, message);

        /*
         *  Unlock the database handle as soon as we're done. We also need to
         *  refresh our handle index with a new handle if for some reason we
         *  had to re-establish a dewedged connection.
         */

        if (TTX->DTX->connections[locked]->dbh != ATX->dbh)
            TTX->DTX->connections[locked]->dbh = ATX->dbh;

        if (TTX->DTX->flags & DRF_RWLOCK) {
            pthread_rwlock_unlock(&TTX->DTX->connections[locked]->rwlock);
        } else {
            pthread_mutex_unlock(&TTX->DTX->connections[locked]->lock);
        }
        locked = -1;

        /* Send a terminating '.' if --stdout in 'dspam' mode */

        if (ATX->sockfd_output) {
            if (send_socket(TTX, ".")<=0)
                goto CLOSE;

            /* Otherwise, produce standard delivery results */

        } else {
            struct nt_node *node_nt, *node_res = NULL;
            struct nt_c c_nt;
            if (ATX->recipients)
                node_nt = c_nt_first(ATX->recipients, &c_nt);
            else
                node_nt = c_nt_first(ATX->users, &c_nt);

            if (ATX->results)
                node_res = ATX->results->first;

            while(node_res && node_nt != NULL) {
                agent_result_t result = (agent_result_t) node_res->ptr;

                if (result != NULL && result->exitcode == ERC_SUCCESS)
                {
                    if (server_mode == SSM_DSPAM) {
                        snprintf(buf, sizeof(buf),
                                 "%d 2.6.0 <%s> Message accepted for delivery: %s",
                                 LMTP_OK, (char *) node_nt->ptr,
                                 (result->classification == DSR_ISSPAM) ? "SPAM" : "INNOCENT");
                    } else {
                        snprintf(buf, sizeof(buf),
                                 "%d 2.6.0 <%s> Message accepted for delivery",
                                 LMTP_OK, (char *) node_nt->ptr);
                    }
                }
                else
                {
                    if (result != NULL && result->exitcode == ERC_PERMANENT_DELIVERY) {
                        snprintf(buf, sizeof(buf), "%d 5.3.0 <%s> %s",
                                 LMTP_FAILURE, (char *) node_nt->ptr,
                                 (result->text[0]) ? result->text : "Permanent error occured");
                    } else {
                        if (result != NULL && result->text[0]) {
                            snprintf(buf, sizeof(buf),
                                     "%d 4.3.0 <%s> %s",
                                     LMTP_TEMP_FAIL, (char *) node_nt->ptr, result->text);
                        } else {
                            snprintf(buf, sizeof(buf),
                                     "%d 4.3.0 <%s> Error occured during %s",
                                     LMTP_TEMP_FAIL, (char *) node_nt->ptr,
                                     (result != NULL && result->exitcode == ERC_DELIVERY) ? "delivery" : "processing");
                        }
                    }
                }

                if (send_socket(TTX, buf)<=0)
                    goto CLOSE;
                if (ATX->recipients)
                    node_nt = c_nt_next(ATX->recipients, &c_nt);
                else
                    node_nt = c_nt_next(ATX->users, &c_nt);
                if (node_res)
                    node_res = node_res->next;
            }
        }

        /* Cleanup and get ready for another message */

RSET:
        fflush(fd);

        buffer_destroy(message);
        message = NULL;
        if (ATX != NULL) {
            nt_destroy(ATX->users);
            nt_destroy(ATX->recipients);
            nt_destroy(ATX->results);
            free(ATX);
            ATX = NULL;
            free(cmdline);
            cmdline = NULL;
            TTX->authenticated = 0;
            /* argc = 0; */
        }

        free(p);
        p = NULL;

    } /* while(1) */

    /* Close connection and return */

CLOSE:
    if (locked>=0)
        pthread_mutex_unlock(&TTX->DTX->connections[locked]->lock);
    if (fd)
        fclose(fd);
    buffer_destroy(TTX->packet_buffer);
    if (message)
        buffer_destroy(message);
    if (ATX != NULL) {
        nt_destroy(ATX->users);
        nt_destroy(ATX->recipients);
        nt_destroy(ATX->results);
    }
    free(ATX);
    free(cmdline);
    free(TTX);
    decrement_thread_count();
    pthread_exit(0);
    return 0;
}
Пример #26
0
// return type
// 执行管道指令,写入socket_message
static int
ctrl_cmd(struct socket_server *ss, struct socket_message *result) {
	int fd = ss->recvctrl_fd;
	// the length of message is one byte, so 256+8 buffer size is enough.
	// 读管道数据,相反的数据写入管道逻辑见send_request方法
	// len长度1个字节,所以缓冲区的长度为256足够
	uint8_t buffer[256];
	uint8_t header[2];
	// 先读2字节的头
	block_readpipe(fd, header, sizeof(header));
	int type = header[0];
	int len = header[1];
	// 再读剩余数据部分
	block_readpipe(fd, buffer, len);
	// ctrl command only exist in local fd, so don't worry about endian.
	switch (type) {
	case 'S':
		// PACCEPT -> CONNECTED 
		// PLISTEN -> LISTEN
		// 把套接字加入事件循环
		return start_socket(ss,(struct request_start *)buffer, result);
	case 'B':
		// 绑定套接字
		return bind_socket(ss,(struct request_bind *)buffer, result);
	case 'L':
		// 监听套接字
		return listen_socket(ss,(struct request_listen *)buffer, result);
	case 'K':
		// 关闭套接字
		return close_socket(ss,(struct request_close *)buffer, result);
	case 'O':
		// 打开套接字
		return open_socket(ss, (struct request_open *)buffer, result);
	case 'X':
		// 退出套接字
		result->opaque = 0;
		result->id = 0;
		result->ud = 0;
		result->data = NULL;
		return SOCKET_EXIT;
	case 'D':
		// 发送高优先级数据
		return send_socket(ss, (struct request_send *)buffer, result, PRIORITY_HIGH, NULL);
	case 'P':
		// 发送低优先级数据
		return send_socket(ss, (struct request_send *)buffer, result, PRIORITY_LOW, NULL);
	case 'A': {
		struct request_send_udp * rsu = (struct request_send_udp *)buffer;
		return send_socket(ss, &rsu->send, result, PRIORITY_HIGH, rsu->address);
	}
	case 'C':
		return set_udp_address(ss, (struct request_setudp *)buffer, result);
	case 'T':
		// 设置套接字
		setopt_socket(ss, (struct request_setopt *)buffer);
		return -1;
	case 'U':
		add_udp_socket(ss, (struct request_udp *)buffer);
		return -1;
	default:
		fprintf(stderr, "socket-server: Unknown ctrl %c.\n",type);
		return -1;
	};

	return -1;
}
Пример #27
0
int main( int   argc,
	  char *argv[])
#endif
{
	// command_line_path = argv[0];

	// g_debug ("argc = %d", argc);
	// print_array ("argv", argv);
	// i18n support. We need to support i18n under console, too.
	setlocale(LC_ALL, "");
	bindtextdomain (BINARY, LOCALEDIR);
	bind_textdomain_codeset (BINARY, "UTF-8");
	textdomain (BINARY);

	const gchar *user_config_dir = g_get_user_config_dir();

#if ! defined(SAFEMODE) && defined(DEVELOP)
	g_message("Running %s without SAFE MODE!", PACKAGE);
#endif

#ifdef OUT_OF_MEMORY
#  undef g_strdup_printf
#endif
	if (user_config_dir) profile_dir = g_strdup_printf("%s/%s", user_config_dir, BINARY);
#ifdef OUT_OF_MEMORY
	#define g_strdup_printf(...) NULL
#endif
	proc_exist = check_if_default_proc_dir_exist(NULL);
	// g_debug ("Get proc_exist = %d, proc_file_system_path = %s", proc_exist, proc_file_system_path);

	shell = g_getenv("SHELL");
	if (shell==NULL) shell = "";

	gboolean pwd_need_be_free = FALSE;
	pwd = (gchar *)g_getenv("PWD");
	if (pwd==NULL)
	{
		pwd_need_be_free = TRUE;
		pwd = g_get_current_dir();
	}
	if (pwd==NULL)
	{
		pwd_need_be_free = FALSE;
		pwd = "";
	}
	// g_debug("Got $PWD = %s", pwd);

	home = g_getenv("HOME");
	if (home==NULL) home = "";
	// g_debug("Get $HOME = %s", home);

	// deal the command line options
	command_option(argc, argv);
	if (wmclass_name==NULL) wmclass_name = g_getenv("RESOURCE_NAME");
	if (wmclass_name==NULL) wmclass_name = "";
	if (wmclass_class==NULL) wmclass_class = "";
	// g_debug("Got wmclass_name = %s, wmclass_class = %s", wmclass_name, wmclass_class);

	// init the gtk+2 engine

	// GTK3: get gtk_test_widget_click() working...
	// gdk_disable_multidevice();

#ifndef UNIT_TEST
	gtk_init(&argc, &argv);
#endif
	// FIXME: we should get the single_process from profile. Current is command-line option only.
	if (single_process)
	{
		// init socket data
		if (init_socket_data())
		{
			// trying to connect to an existing LilyTerm
			if (query_socket())
			{
				// success, sent the argc/argv to socket then quit
				// g_debug("A LilyTerm socket server is exist already. exiting...");
				if (send_socket(argc, argv, TRUE))
				{
					g_free(profile_dir);
					exit (0);
				}
			}
			// no LilyTerm exist. create a socket server
			// g_debug("Creating a LilyTerm socket server...");
			init_socket_server();
			g_atexit((GVoidFunc)shutdown_socket_server);
		}
	}

	// start LilyTerm

	// empty_environ = g_strsplit("", " ", -1);
	extern gchar **environ;
	// print_array("main(): environ", environ);
	gchar *environ_str = convert_array_to_string(environ, '\t');
	window_list = NULL;
	// g_debug("Got environ_str (in main.c) = %s", environ_str);
	selection_clipboard = gtk_clipboard_get(GDK_SELECTION_CLIPBOARD);
	selection_primary = gtk_clipboard_get(GDK_SELECTION_PRIMARY);
	system_locale_list = get_locale_list();
	// g_debug("Got system_locale_list = %s", system_locale_list);
	init_LC_CTYPE = g_strdup(get_default_lc_data(LC_CTYPE));
	// g_debug("Got init_LC_CTYPE = %s", init_LC_CTYPE);
	init_LANGUAGE = g_strdup(get_default_lc_data(LANGUAGE));
	// g_debug("Got init_LANGUAGE = %s", init_LANGUAGE);
	init_LC_MESSAGES = g_strdup(get_default_lc_data(LC_MESSAGES));
	// g_debug("init_LC_MESSAGES = %s", init_LC_MESSAGES);
	init_encoding = (gchar *)get_encoding_from_locale(NULL);
	if (! compare_strings(init_encoding, "ANSI_X3.4-1968", TRUE))
	{
		g_free(init_encoding);
		init_encoding = g_strdup("UTF-8");
	}
	// g_debug("init_encoding = %s", init_encoding);
	SYSTEM_VTE_CJK_WIDTH_STR = g_getenv("VTE_CJK_WIDTH");
	// g_debug ("Got SYSTEM_VTE_CJK_WIDTH_STR = %s", SYSTEM_VTE_CJK_WIDTH_STR);
	// FIXME: signal(SIGCHLD, SIG_IGN);
	// The first window of LilyTerm

	// Convert the GdkColor to GdkRGBA
	convert_system_color_to_rgba();

	// g_debug("Got original encoding = %s", get_encoding_from_locale(NULL));
	//GtkNotebook *new_window(int argc,
	//			char *argv[],
	//			gchar *shell,
	//			gchar *environment,
	//			gchar *locale_list,
	//			gchar *PWD,
	//			gchar *HOME,
	//			gchar *VTE_CJK_WIDTH_STR,
	//			gboolean VTE_CJK_WIDTH_STR_overwrite_profile,
	//			gchar *wmclass_name,
	//			gchar *wmclass_class,
	//			gchar *user_environ,
	//			gchar *encoding,
	//			gboolean encoding_overwrite_profile,
	//			gchar *lc_messages,
	//			struct Window *win_data_orig,
	//			struct Page *page_data_orig)

	if ((new_window(argc,
			argv,
			(gchar *) shell,
			environ_str,
			system_locale_list,
			(gchar *) pwd,
			(gchar *) home,
			SYSTEM_VTE_CJK_WIDTH_STR,
			FALSE,
			wmclass_name,
			wmclass_class,
			NULL,
			init_encoding,
			FALSE,
			init_LC_MESSAGES,
			NULL,
			NULL)) ||
	     window_list)
	{
		// The argv of "main" LilyTerm can't be free.
		// Set it to NULL here to avoid double_free().
		argv=NULL;
#ifdef ENABLE_X_STARTUP_NOTIFICATION_ID
		gdk_notify_startup_complete_with_id(PACKAGE);
#endif
		// g_debug("gtk_main_level = %d", gtk_main_level());
		if (! gtk_main_level())
			gtk_main();
	}
#ifdef DETAIL
	else
	{
//		g_debug("Got window_list = %p", window_list);
//		GList *win_list = window_list;
//		gint i=0;
//
//		while (win_list)
//		{
//			g_debug("Got %d win_data = %p", ++i, win_list->data);
//			win_list = win_list->next;
//		}
		g_debug("??? The creation of first window is FAIL!!!");
	}
#endif
	extern struct KeyValue system_keys[KEYS];
	gint i;
	// g_debug("Clear function key data!!");
	for (i=KEY_SWITCH_TO_TAB_1; i<=KEY_SWITCH_TO_TAB_12; i++)
	{
		g_free(system_keys[i].name);
		g_free(system_keys[i].topic);
		g_free(system_keys[i].comment);
		g_free(system_keys[i].translation);
#ifdef UNIT_TEST
		system_keys[i].name = NULL;
		system_keys[i].topic = NULL;
		system_keys[i].comment = NULL;
		system_keys[i].translation = NULL;
#endif
	}

	// g_free(pwd);
	// g_strfreev(empty_environ);
	g_free(environ_str);
	g_free(init_encoding);
	g_free(system_locale_list);
	g_free(profile_dir);
	if (pwd_need_be_free) g_free(pwd);
	g_free(restricted_locale_message);
	g_list_free(window_list);
	g_free(init_LC_CTYPE);
	g_free(init_LC_MESSAGES);
#ifdef UNIT_TEST
	// empty_environ = NULL;
	environ_str = NULL;
	init_encoding = NULL;
	system_locale_list = NULL;
	profile_dir = NULL;
	restricted_locale_message = NULL;
	window_list = NULL;
	init_LC_CTYPE = NULL;
	init_LC_MESSAGES = NULL;
#endif
	return 0;
}
Пример #28
0
int send_rsa(bool server, std::string data, std::string& recieved, int sock) {
	
	CryptoPP::AutoSeededRandomPool rng;
    //Do RSA Encryption here
   
	std::string plain, encrypted, decrypted, signature, recovered, tdecoded;
    bool result;

	CryptoPP::RSAES_OAEP_SHA_Encryptor other_pub;
	CryptoPP::RSAES_OAEP_SHA_Encryptor my_pub;
    CryptoPP::RSAES_OAEP_SHA_Decryptor my_priv;

	if(server)
	{
	    {
		    CryptoPP::HexDecoder decoder;
		    decoder.Put( (byte*)bank_priv, bank_priv_size );
		    decoder.MessageEnd();

		     my_priv.AccessKey().Load( decoder );
		 }

	    {

	        CryptoPP::HexDecoder decoder;
	        decoder.Put( (byte*)atm_pub, atm_pub_size );
	        decoder.MessageEnd();

	        other_pub.AccessKey().Load( decoder );
	    }
	    {

	        CryptoPP::HexDecoder decoder;
	        decoder.Put( (byte*)bank_pub, bank_pub_size);
	        decoder.MessageEnd();

	        my_pub.AccessKey().Load( decoder );
	    }


	 }
	 else
	 {
        {
	        CryptoPP::HexDecoder decoder;
	        decoder.Put( (byte*)atm_pub, atm_pub_size);
	        decoder.MessageEnd();

	        my_pub.AccessKey().Load( decoder );
	    }
	    {
	        CryptoPP::HexDecoder decoder;
	        decoder.Put( (byte*)bank_pub, bank_pub_size );
	        decoder.MessageEnd();

	        other_pub.AccessKey().Load( decoder );
	    }
	    {
	        CryptoPP::HexDecoder decoder;
	        decoder.Put( (byte*)atm_priv, atm_priv_size );
	        decoder.MessageEnd();

	        my_priv.AccessKey().Load( decoder );
	    }
	
	  }

	CryptoPP::RSASS<CryptoPP::PSSR, CryptoPP::SHA1>::Signer signer( my_priv );

	//Run the data through the RSA encryption
	CryptoPP::StringSource( data, true, new CryptoPP::PK_EncryptorFilter( rng, other_pub, new CryptoPP::StringSink( encrypted )));
	
	//Sign the encrypted data	
    size_t length = signer.MaxSignatureLength(); 
    byte sig_buff[length];

    signer.SignMessage(rng, (byte *)encrypted.c_str(), encrypted.length(), sig_buff);
    signature.assign((char *)sig_buff, length);

	CryptoPP::RSASS<CryptoPP::PSSR, CryptoPP::SHA1>::Verifier verifiermine( my_pub);

    data.assign(std::to_string(signature.length()));
    data.append("|");
    data.append(signature);
    data.append(encrypted);


    int err = send_socket(data, recieved, sock);
    if (err != 0) {
        return -1;
    }

    if (recieved.find("|") == recieved.npos) {
        return -1;
    }
    int sig_length = atoi(recieved.substr(0, recieved.find("|")).c_str());
    if (sig_length == 0) {
        return -1;
    }
    if (recieved.length() < sig_length + recieved.find("|")+1) {
        return -1;
    }
    recieved = recieved.substr(recieved.find("|")+1, recieved.length()-recieved.find("|")-1);
    std::string other_signature = recieved.substr(0, sig_length);
    std::string other_encrypted = recieved.substr(sig_length, recieved.length() - sig_length);
    if (other_signature.length() != (unsigned int)sig_length) {
        return -1;
    }

	CryptoPP::RSASS<CryptoPP::PSSR, CryptoPP::SHA1>::Verifier verifier( other_pub );

    result = verifier.VerifyMessage((byte *)other_encrypted.c_str(), other_encrypted.length(), (byte *)other_signature.c_str(), other_signature.length());
    if (result == false)
	{
        return -1;//Signature failed if it returns -1
    }

	CryptoPP::StringSource( other_encrypted, true, new CryptoPP::PK_DecryptorFilter( rng, my_priv, new CryptoPP::StringSink( decrypted )));

    recieved.assign(decrypted);
    return 0;
}
Пример #29
0
static int proxy_fdpass_handler(request_rec *r, proxy_worker *worker,
                              proxy_server_conf *conf,
                              char *url, const char *proxyname,
                              apr_port_t proxyport)
{
    apr_status_t rv;
    apr_socket_t *sock;
    apr_socket_t *clientsock;

    if (strncasecmp(url, "fd://", 5) == 0) {
        url += 5;
    }
    else {
        return DECLINED;
    }

    rv = get_socket_from_path(r->pool, url, &sock);

    if (rv != APR_SUCCESS) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(01152)
                      "Failed to connect to '%s'", url);
        return HTTP_INTERNAL_SERVER_ERROR;
    }

    {
        int status;
        const char *flush_method = worker->s->flusher ? worker->s->flusher : "flush";

        proxy_fdpass_flush *flush = ap_lookup_provider(PROXY_FDPASS_FLUSHER,
                                                       flush_method, "0");

        if (!flush) {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(01153)
                          "Unable to find configured flush provider '%s'",
                          flush_method);
            return HTTP_INTERNAL_SERVER_ERROR;
        }

        status = flush->flusher(r);
        if (status) {
            return status;
        }
    }

    clientsock = ap_get_conn_socket(r->connection);

    rv = send_socket(r->pool, sock, clientsock);
    if (rv != APR_SUCCESS) {
        ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(01154) "send_socket failed:");
        return HTTP_INTERNAL_SERVER_ERROR;
    }

    {
        apr_socket_t *dummy;
        /* Create a dummy unconnected socket, and set it as the one we were
         * connected to, so that when the core closes it, it doesn't close
         * the tcp connection to the client.
         */
        rv = apr_socket_create(&dummy, APR_INET, SOCK_STREAM, APR_PROTO_TCP,
                               r->connection->pool);
        if (rv != APR_SUCCESS) {
            ap_log_rerror(APLOG_MARK, APLOG_ERR, rv, r, APLOGNO(01155)
                          "failed to create dummy socket");
            return HTTP_INTERNAL_SERVER_ERROR;
        }
        ap_set_core_module_config(r->connection->conn_config, dummy);
    }


    return OK;
}
Пример #30
0
void gks_drv_socket(int fctid, int dx, int dy, int dimx, int *ia, int lr1, double *r1, int lr2, double *r2, int lc,
                    char *chars, void **ptr)
{
  ws_state_list *wss;
  const char *command = NULL, *env;
  int retry_count;
  char *cmd = NULL;

  wss = (ws_state_list *)*ptr;

  switch (fctid)
    {
    case 2:
      gkss = (gks_state_list_t *)*ptr;
      wss = (ws_state_list *)gks_malloc(sizeof(ws_state_list));

      if (ia[2] == 411)
        {
          command = gks_getenv("GKS_QT");
          if (command == NULL)
            {
              env = gks_getenv("GRDIR");
              if (env == NULL) env = GRDIR;

              cmd = (char *)gks_malloc(MAXPATHLEN);
#ifndef _WIN32
#ifdef __APPLE__
              sprintf(cmd, "%s/Applications/gksqt.app/Contents/MacOS/gksqt", env);
#else
              sprintf(cmd, "%s/bin/gksqt", env);
#endif
#else
              sprintf(cmd, "%s\\bin\\gksqt.exe", env);
#endif
              command = cmd;
            }
        }

      for (retry_count = 1; retry_count <= 10; retry_count++)
        {
          if ((wss->s = connect_socket(retry_count != 10)) == -1)
            {
              if (command != NULL && retry_count == 1)
                {
                  if (start(command) != 0) gks_perror("could not auto-start GKS Qt application");
                }
#ifndef _WIN32
              usleep(300000);
#else
              Sleep(300);
#endif
            }
          else
            break;
        }

      if (cmd != NULL) free(cmd);

      if (wss->s == -1)
        {
          gks_perror("can't connect to GKS socket application\n"
                     "Did you start 'gksqt'?\n");

          gks_free(wss);
          wss = NULL;

          ia[0] = ia[1] = 0;
        }
      else
        *ptr = wss;
      break;

    case 3:
      close_socket(wss->s);
      if (wss->dl.buffer)
        {
          free(wss->dl.buffer);
        }
      gks_free(wss);
      wss = NULL;
      break;

    case 8:
      if (ia[1] & GKS_K_PERFORM_FLAG)
        {
          send_socket(wss->s, (char *)&wss->dl.nbytes, sizeof(int));
          send_socket(wss->s, wss->dl.buffer, wss->dl.nbytes);
        }
      break;
    }

  if (wss != NULL)
    {
      gks_dl_write_item(&wss->dl, fctid, dx, dy, dimx, ia, lr1, r1, lr2, r2, lc, chars, gkss);
    }
}