Exemple #1
0
static void
send(module_t *module, const char *channel, const char *message) {
	irc_t *irc = (irc_t *)module;

	if (strncmp(message, me_prefix, strlen(me_prefix)) == 0) {
		const char *action = message + strlen(me_prefix);
		// Transmit an action
		printf("[%s] * %s %s\n", channel, irc->current_nick, action);

		if (irc_cmd_me(irc->session, channel, action)) {
			fprintf(stderr, "irc: %s\n", irc_strerror(irc_errno(irc->session)));
			return;
		}
	} else {
		// Send a regular message
		printf("[%s] <%s> %s\n", channel, irc->current_nick, message);

		if (irc_cmd_msg(irc->session, channel, message)) {
			fprintf(stderr, "irc: %s\n", irc_strerror(irc_errno(irc->session)));
			return;
		}
	}

	bot_on_read_log(module->bot, irc->current_nick, message);
}
Exemple #2
0
void Twitch::SendChatMessage( const std::string &message ) {
	if ( !session ) {
		return;
	}

	if ( irc_cmd_msg( session, channel.c_str(), message.c_str() ) ) {
		OnError( irc_errno( session ), irc_strerror( irc_errno( session ) ) );
	}
}
Exemple #3
0
void ServerState::prepareConnecting(Server &server, fd_set &setinput, fd_set &setoutput, int &maxfd)
{
	/*
	 * The connect function will either fail if the hostname wasn't resolved
	 * or if any of the internal functions fail.
	 *
	 * It returns success if the connection was successful but it does not
	 * mean that connection is established.
	 *
	 * Because this function will be called repeatidly from the
	 * ServerManager, if the connection was started and we're still not
	 * connected in the specified timeout time, we mark the server
	 * as disconnected.
	 *
	 * Otherwise, the libircclient event_connect will change the state.
	 */
	const ServerInfo &info = server.info();

	if (m_started) {
		const ServerSettings &settings = server.settings();

		if (m_timer.elapsed() > static_cast<unsigned>(settings.recotimeout * 1000)) {
			Logger::warning() << "server " << info.name << ": timeout while connecting" << std::endl;
			server.next(ServerState::Disconnected);
		} else if (!irc_is_connected(server.session())) {
			Logger::warning() << "server " << info.name << ": error while connecting: "
					  << irc_strerror(irc_errno(server.session())) << std::endl;

			if (settings.recotimeout > 0) {
				Logger::warning() << "server " << info.name << ": retrying in " << settings.recotimeout << " seconds" << std::endl;
			}

			server.next(ServerState::Disconnected);
		} else {
			irc_add_select_descriptors(server.session(), &setinput, &setoutput, &maxfd);
		}
	} else {
		/*
		 * This is needed if irccd is started before DHCP or if
		 * DNS cache is outdated.
		 *
		 * For more information see bug #190.
		 */
#if !defined(_WIN32)
		(void)res_init();
#endif
		Logger::info() << "server " << info.name << ": trying to connect to " << info.host << ", port " << info.port << std::endl;

		if (!connect(server)) {
			Logger::warning() << "server " << info.name << ": disconnected while connecting: "
					  << irc_strerror(irc_errno(server.session())) << std::endl;
			server.next(ServerState::Disconnected);
		} else {
			m_started = true;
		}
	}
}
Exemple #4
0
void event_connect( irc_session_t *session, const char *event, const char *origin, const char **params, unsigned int count ) {
	TwitchContext *ctx = ( TwitchContext * ) irc_get_ctx( session );
	if ( !ctx ) {
		return;
	}
	
	if ( irc_cmd_join( session, ctx->twitch->channel.c_str(), 0 ) ) {
		ctx->twitch->OnError( irc_errno( session ), irc_strerror( irc_errno( session ) ) );
		return;
	}

	ctx->twitch->status = TWITCH_CONNECTED;
	ctx->twitch->OnConnected();
}
Exemple #5
0
/*
====================
IRC_ConnectSession

Connects a session handle created by IRC_CreateSession to an IRC server.
Returns 0 on success, -1 on invalid handle, error code on libircclient error.
====================
*/
int IRC_ConnectSession(int handle, const char *server, unsigned short port, const char *server_password, const char *nick, const char *username, const char *realname) {
    irc_session_t *s;
    int err;
    
    if(!IS_VALID_IRC_SESSION(handle)) {
        IRC_Printf("Attempted to connect an invalid session %i\n", handle);
        return -1;
    }
    
    if(IRC_SessionIsConnected(handle))
        IRC_DisconnectSession(handle, "Changing server");
    
    s = &irc_sessions[handle];
    strlcpy(s->server, server, sizeof(s->server));
    strlcpy(s->nick, nick, sizeof(s->nick));
    strlcpy(s->username, username, sizeof(s->username));
    strlcpy(s->realname, realname, sizeof(s->realname));
    if(server_password)
        strlcpy(s->password, server_password, sizeof(s->password));
    else
        memset(s->password, 0, sizeof(s->password));
    
    irc_disconnect(s->session);
    if(irc_connect(s->session, server, port, server_password, nick, username, realname)) {
        err = irc_errno(s->session);
        IRC_Printf("Connection error on session %i: %s\n", handle, irc_strerror(err));
        return err;
    }
    
    return 0;
}
Exemple #6
0
/*
====================
IRC_SendRaw

Sends a raw irc command to the server.
====================
*/
int IRC_SendRaw(int handle, const char *fmt, ...) {
    int err;
    va_list args;
    char cmd[MAX_INPUTLINE];
    
    va_start(args, fmt);
    dpvsnprintf(cmd, sizeof(cmd), fmt, args);
    va_end(args);
    
    if(developer.integer)
        Con_DPrintf("IRC_SendRaw(%i): %s\n", handle, cmd);
        
    if(!IS_VALID_IRC_SESSION(handle)) {
        IRC_Printf("IRC_SendRaw: %i is not a valid session\n", handle);
        return -1;
    }
    
    if(irc_send_raw(irc_sessions[handle].session, "%s", cmd)) {
        err = irc_errno(irc_sessions[handle].session);
        if(err) {
            IRC_Printf("IRC_SendRaw: Error: %s\n", irc_strerror(err));
            return err;
        }
    }
    
    return 0;
}
Exemple #7
0
/*
====================
IRC_Frame

Called every host frame.
Used to poll IRC connections.
====================
*/
void IRC_Frame(void) {
    struct timeval tv;
    fd_set in, out;
    int maxfd = 0;
    int i, err;
    
    if(!irc_initialized.integer || !irc_enabled.integer)
        return;
    
    tv.tv_usec = 0;
    tv.tv_sec = 0;
    
    FD_ZERO(&in);
    FD_ZERO(&out);
    
    FOR_ACTIVE_IRC_SESSIONS(i)
        irc_add_select_descriptors(irc_sessions[i].session, &in, &out, &maxfd);
    
    select(maxfd + 1, &in, &out, 0, &tv);
    
    FOR_ACTIVE_IRC_SESSIONS(i)
        if(irc_process_select_descriptors(irc_sessions[i].session, &in, &out)) {
            err = irc_errno(irc_sessions[i].session);
            if(err)
                IRC_Printf("Error on session %i: %s\n", i, irc_strerror(err));
        }
}
Exemple #8
0
// Handle errors
void IRCSession::resolve_errno() {
  int err = irc_errno(session);
  const char* msg = irc_strerror(err);
  std::stringstream ss;
  ss << "Irc errno " << err << ": " << msg;
  throw std::runtime_error{ss.str()};
}
Exemple #9
0
void* irc_thread_net(void *data) {
    irc_thread_data *self = (irc_thread_data*)data;
    irc_callbacks_t callbacks;
    irc_ctx_t ctx;
    irc_session_t *irc_s;

    void *socket = zmq_socket(self->d.context, ZMQ_PUSH); // "server" from irc -> tun
    int ret = zmq_connect(socket, "inproc://#irc_to_#tun");

    if (ret) {
        irc_debug(self, "(irc_thread_net) error when creating IPC socket - %s", zmq_strerror(errno));
        goto exit;
    }

    memset (&callbacks, 0, sizeof(callbacks));

    callbacks.event_connect = event_connect;
    callbacks.event_join = event_join;
    callbacks.event_privmsg = event_message;
    callbacks.event_channel = event_message;

    ctx.channel = strdup(self->chan);
    ctx.nick = malloc(sizeof(char)*512);
    snprintf(ctx.nick, 511, self->nick, rand());
    ctx.self = self;
    ctx.buffer = malloc(sizeof(char)*MTU*4);
    ctx.data = socket; // WE ARE PASSING A NON-THREAD-SAFE SOCKET HERE! </redwarning>

    irc_s = irc_create_session(&callbacks);
    if (!irc_s) {
        irc_debug(self, "error when creating irc_session");
        goto exit;
    }
    self->irc_s = irc_s;

    irc_debug(self, "created irc_session!");
    irc_set_ctx(self->irc_s, &ctx);

    if (irc_connect (self->irc_s, self->server, 6667, self->pass, ctx.nick, "ipoirc", "IP over IRC - http://github.com/EXio4/IPoIRC")) {
        irc_debug(self, "error when connecting to irc (%s)", irc_strerror(irc_errno(self->irc_s)));
        goto exit;
    }

    sleep(1); // wait for the network to answer THIS SHOULD BE DONE IN A RIGHT WAY!

    int rc = irc_run(self->irc_s);

    (void) rc;

    exit:
    if (self->irc_s) {
        irc_destroy_session(self->irc_s);
    }
    if (socket) {
        zmq_close(socket);
    }
    pthread_exit(NULL);
}
Exemple #10
0
int main (int argc, char **argv)
{
	irc_callbacks_t	callbacks;
	irc_ctx_t ctx;
	irc_session_t * s;

	if ( argc != 4 )
	{
		printf ("Usage: %s <server> <nick> <channel>\n", argv[0]);
		return 1;
	}

	memset (&callbacks, 0, sizeof(callbacks));

	callbacks.event_connect = event_connect;
	callbacks.event_join = event_join;
	callbacks.event_nick = dump_event;
	callbacks.event_quit = dump_event;
	callbacks.event_part = dump_event;
	callbacks.event_mode = dump_event;
	callbacks.event_topic = dump_event;
	callbacks.event_kick = dump_event;
	callbacks.event_channel = event_channel;
	callbacks.event_privmsg = event_privmsg;
	callbacks.event_notice = dump_event;
	callbacks.event_invite = dump_event;
	callbacks.event_umode = dump_event;
	callbacks.event_ctcp_rep = dump_event;
	callbacks.event_ctcp_action = dump_event;
	callbacks.event_unknown = dump_event;
	callbacks.event_numeric = event_numeric;

	callbacks.event_dcc_chat_req = irc_event_dcc_chat;
	callbacks.event_dcc_send_req = irc_event_dcc_send;

	s = irc_create_session (&callbacks);

	if ( !s )
	{
		printf ("Could not create session\n");
		return 1;
	}

	ctx.channel = argv[3];
    ctx.nick = argv[2];

	irc_set_ctx (s, &ctx);

	if ( irc_connect (s, argv[1], 6667, 0, argv[2], 0, 0) )
	{
		printf ("Could not connect: %s\n", irc_strerror (irc_errno(s)));
		return 1;
	}

	irc_run (s);

	return 1;
}
Exemple #11
0
// Handler for libircclient errors
void irc_error(irc_session_t* irc_session, int fatal){
	int err = irc_errno(irc_session);
	const char* errstr = irc_strerror(err);
	fprintf(stderr,"IRC error: %s (%d)\n", errstr, err);
	if(fatal){
		fprintf(stderr, "Fatal error... Exiting.\n");
		exit(1);
	}
}
Exemple #12
0
void IRC::ircEventLoop(irc_session_t* session)
{
    if(irc_run(session))
        irc_errno(session);

    // is this needed?
    while(_run)
    {
        sleep(1);
    }
}
Exemple #13
0
std::thread Twitch::Connect( const std::string &user, const std::string &password ) {
	return std::thread( [this, user, password] {
		this->user = user;
		this->channel = "#" + user;

		irc_callbacks_t	callbacks;
		memset( &callbacks, 0, sizeof( callbacks ) );
		callbacks.event_connect = event_connect;
		callbacks.event_channel = event_channel;
		callbacks.event_numeric = event_numeric;

		session = irc_create_session( &callbacks );

		if ( !session ) {
			OnError( -1, "Failed to create IRC session" );
			return;
		}

		TwitchContext *ctx = new TwitchContext();
		ctx->twitch = this;
		irc_set_ctx( session, ctx );

		irc_option_set( session, LIBIRC_OPTION_STRIPNICKS );

		status = TWITCH_CONNECTING;

		if ( irc_connect( session, "irc.chat.twitch.tv", 6667, password.c_str(), user.c_str(), user.c_str(), user.c_str() ) ) {
			OnError( irc_errno( session ), irc_strerror( irc_errno( session ) ) );
			status = TWITCH_DISCONNECTED;
			return;
		}

		if ( irc_run( session ) ) {
			OnError( irc_errno( session ), irc_strerror( irc_errno( session ) ) );
			status = TWITCH_DISCONNECTED;
			return;
		}
	} );
}
Exemple #14
0
static void
event_connect(irc_session_t *session, const char *event, const char *origin,
		const char **params, unsigned int count) {
	irc_t *irc = get_module(session);

	printf("Connected to %s:%u.\n", irc->server, irc->port);

	// Join our channels
	for (channel_t *channel = irc->channels; channel; channel = channel->next) {
		if (irc_cmd_join(session, channel->name, NULL)) {
			fprintf(stderr, "irc: %s\n", irc_strerror(irc_errno(session)));
			return;
		}
	}
}
Exemple #15
0
int main (int argc, char **argv)
{
	irc_callbacks_t	callbacks;
	irc_ctx_t ctx;
	irc_session_t * s;

	if ( argc != 4 )
	{
		printf ("Usage: %s <server> <nick> <channel>\n", argv[0]);
		return 1;
	}

	memset (&callbacks, 0, sizeof(callbacks));

	callbacks.event_connect = event_connect;
	callbacks.event_join = event_join;
	callbacks.event_channel = event_channel;
	callbacks.event_numeric = event_numeric;

	s = irc_create_session (&callbacks);

	if ( !s )
	{
		printf ("Could not create session\n");
		return 1;
	}

	ctx.channel = argv[3];
    ctx.nick = argv[2];

	irc_set_ctx (s, &ctx);
	
	if ( irc_connect (s, argv[1], 6667, 0, argv[2], 0, 0) )
	{
		printf ("Could not connect: %s\n", irc_strerror (irc_errno(s)));
		return 1;
	}

	irc_run (s);

	return 1;
}
Exemple #16
0
static int
module_connect(module_t *module) {
	irc_t *irc = (irc_t *)module;

	printf("Connecting to server: %s, port: %u\n",
		&irc->server[irc->ssl ? -1 : 0],
		irc->port);

	if ((irc->ipv6 ? irc_connect6 : irc_connect)
			(irc->session,
			 &irc->server[irc->ssl ? -1 : 0],
			 irc->port,
			 irc->password,
			 irc->nick,
			 irc->username,
			 irc->realname)) {
		fprintf(stderr, "irc: %s\n", irc_strerror(irc_errno(irc->session)));
		return 0;
	}
	return 1;
}
Exemple #17
0
module_t *
irc_new() {
	irc_t *irc = calloc(1, sizeof(irc_t));

	if (!irc) {
		perror("calloc");
		return NULL;
	}

	irc->module.type = "irc";
	irc->module.name = NULL;
	irc->module.connect = module_connect;
	irc->module.config = config;
	irc->module.process_select_descriptors = process_select;
	irc->module.add_select_descriptors = add_select;
	irc->module.send = send;
	irc->module.get_nicks = get_nicks;

	irc->server = "";
	irc->ssl = 0;
	irc->ipv6 = 0;
	irc->port = 6667;
	irc->password = NULL;
	irc->nick = "guest";
	irc->username = "******";
	irc->realname = "noname";
	irc->channels = NULL;

	// Add this module to the global linked list
	irc->next = modules;
	modules = irc;

	irc->session = irc_create_session(&callbacks);
	if (!irc->session) {
		fprintf(stderr, "irc: %s\n", irc_strerror(irc_errno(irc->session)));
	}
	irc_option_set(irc->session, LIBIRC_OPTION_STRIPNICKS);

	return (module_t *)irc;
}
Exemple #18
0
/*
====================
IRC_ReconnectSession

Reconnects the session to the last server it connected to.
Returns 0 on success, -1 on invalid handle, error code on libircclient error.
====================
*/
int IRC_ReconnectSession(int handle) {
    irc_session_t *s;
    int err;
    
    if(!IS_VALID_IRC_SESSION(handle)) {
        IRC_Printf("Attempted to reconnect an invalid session %i\n", handle);
        return -1;
    }
    
    if(IRC_SessionIsConnected(handle))
        IRC_DisconnectSession(handle, "Reconnecting");
    
    s = &irc_sessions[handle];
    irc_disconnect(s->session);
    if(irc_connect(s->session, s->server, s->port, s->password, s->nick, s->username, s->realname)) {
        err = irc_errno(s->session);
        IRC_Printf("Connection error on session %i: %s\n", handle, irc_strerror(err));
        return err;
    }
    
    return 0;
}
Exemple #19
0
static void
event_nick(irc_session_t *session, const char *event, const char *old_nick,
		const char **params, unsigned int count) {
	const char *new_nick = params[0];
	if (count < 1) {
		return;
	}
	irc_t *irc = get_module(session);
	if (irc->current_nick && strcmp(irc->current_nick, old_nick)) {
		printf("(nick) %s -> %s\n", old_nick, new_nick);
	} else {
		if (irc->current_nick) {
			free(irc->current_nick);
		}
		irc->current_nick = strdup(new_nick);
		irc->module.name = irc->current_nick;
		if (debug) {
			printf("Nick changed: %s\n", new_nick);
		}
		if (irc_cmd_nick(session, irc->nick)) {
			fprintf(stderr, "irc: %s\n", irc_strerror(irc_errno(irc->session)));
		}
	}
}
Exemple #20
0
int main (int argc, char **argv)
{
    bool daemon_deaktiv = false;
    bool btipp = false;

    int is=1, in=2, ic=3;
    int i=1;

    for(; i < argc; i++)
    {
        if ( !strncmp(argv[i], "-d",3) || !strncmp(argv[i], "-D",3) )
        {
            if(argc > 4)
                btipp = true;
            daemon_deaktiv = true;
            printf("\n--------------------------------------------------\n");
            printf("Daemon wird deaktiviert.");
            if(i<2)
            {
                is = 2;
                in = 3;
                ic = 4;
            }

        }
        else if ( !strncmp(argv[i], "-h",3) || !strncmp(argv[i], "-help",6) )
        {
            btipp = true;
            printf("TEST: HELP ist da\n");
            system("nroff -mandoc ./man/iman.pod | less");
        }

    }
    if(btipp == false && argc != 4 )
    {
        printf("\nUsage: %s [options]\n", argv[0]);
        printf("\n          [ -h | -help ]                   Anleitung");
        printf("\n          [ <server> <nick> <#channel> ]   Ircbot startet");
        printf("\n          [ -d .......... ] startet und Daemon wird deaktiviert\n\n");
        exit(EXIT_SUCCESS);
    }


    irc_callbacks_t	callbacks;
    irc_ctx_t ctx;
    irc_session_t * s;

    memset (&callbacks, 0, sizeof(callbacks));

    callbacks.event_connect = event_connect;
    callbacks.event_join = event_join;
    callbacks.event_channel = event_channel;
    callbacks.event_quit = event_quit;

    s = irc_create_session (&callbacks);

    if ( !s )
    {
        printf ("Could not create session\n");
        return 1;
    }

    ctx.channel = argv[ic];
    ichanel = argv[ic];
    ctx.nick = argv[in];
    mynick = argv[in];

    irc_set_ctx (s, &ctx);
    irc_option_set(s, LIBIRC_OPTION_STRIPNICKS);

    if ( irc_connect (s, argv[is], 6667, 0, argv[in], 0, 0) )
    {
        printf ("Es kann nicht verbinden: %s\n", irc_strerror (irc_errno(s)));
        return 1;
    }
    else
    {
        if(daemon_deaktiv == false)
        {
            printf("\n--------------------------------------------------\n");
            printf("Daemon wird aktiviert.");
        }

        printf("\nBot-Nickname: '%s'",argv[in]);
        printf("\nChannel     : '%s'",argv[ic]);
        printf("\nEs verbindet: '%s'....\n", argv[is]);
    }
    if(daemon_deaktiv == false)
    {
        openlog (daemon_name, LOG_CONS | LOG_PID | LOG_NDELAY, LOG_DAEMON);
        syslog (LOG_INFO, "Ircbot: Starting....");
        start_daemon(daemon_name, LOG_USER);
    }
    irc_run (s);

    syslog (LOG_INFO, "Ircbot: Terminating...");
    closelog();

    return 1;
}
Exemple #21
0
void event_channel (irc_session_t * session, const char * event, const char * origin, const char ** params, unsigned int count)
{
    printf ("<%s> sagt in %s: %s\n", origin ? origin : "someone", params[0], params[1] );
    snprintf(textbuf, sizeof(textbuf), "<%s>  %s", origin, params[1]);
    dlop(textbuf,false);

    if ( !strcmp (params[1], "-h") || !strcmp (params[1], "-help") )
    {
        char * str = irc_color_convert_to_mirc ("[B]bold[/B], [I]reverse[/I], [U]underline[/U], [COLOR=RED]red[/COLOR], [COLOR=YELLOW/BLACK]black[/COLOR]");
        irc_cmd_msg (session, params[0], str);
        free (str);
        irc_cmd_msg (session, params[0], "[B]bold[/B], [I]reverse[/I], [U]underline[/U], [COLOR=RED]red[/COLOR], [COLOR=YELLOW/BLACK]black[/COLOR]");
        irc_cmd_msg (session, params[0], " ");
        irc_cmd_msg (session, params[0], "-l nickname   | Abfrage, wann ein Nutzer das letzte Mal im Raum war.");
        irc_cmd_msg (session, params[0], "-e [email protected]  | Verschicken des irc-Log an eine Mailadresse");
        irc_cmd_msg (session, params[0], "-bot          | Abfrage, ob ein irc-Bot da ist.");
        irc_cmd_msg (session, params[0], "-q xxxxxx     | Bot wird geschlossen, z.B.: -q 123532");
    }

    if ( !strcmp (params[1], "-bot") )
    {
        char * str = irc_color_convert_to_mirc ("Hallo! Yes, I'm Bot. =)");
        irc_cmd_msg (session, params[0], str);
        free (str);
    }

    if ( strstr(params[1], "-l"))
    {
        char par[100];
        size_t len;
        strcpy(par, params[1]+3);

        char cdata[255];

        len = strlen(par);

        if(len > 0 )
        {
            strcpy(cdata, par);
            ssqlsv(cdata, false);
            snprintf (textbuf, sizeof(textbuf), "%s",cdata);
        }
        else snprintf (textbuf, sizeof(textbuf), "Hast du vergessen, einen Nickname einzugeben?");

        irc_cmd_msg (session, params[0], textbuf);
        printf("Rueckmeldung: %s\n",textbuf);

        snprintf(cdata, sizeof(cdata), " ");
    }

    if ( strstr(params[1], "-e") )
    {
        size_t lin2;
        lin2 = strlen(params[1]);
        if(lin2>3)
        {
            char cemail[50];
            strcpy(cemail, params[1]+3);
            irc_cmd_msg (session, params[0], "An deiner email-Adresse wurde log.txt geschickt");
            char system_str[256];

            FILE * datei;
            size_t len;
            char text[100];

            datei = fopen("/etc/ircbotF/confi.cfg", "r");

            if( datei != NULL)
            {
                fgets(text,100,datei);
                len = strlen(text);
                text[len-1] = '\0';
                fclose(datei);
            }
            char pfad[255];
            snprintf(pfad, sizeof(pfad),"%slog/log.txt",text);

            snprintf( system_str, sizeof(system_str), "mail -s \"IRC-LOG\" %s < %s", cemail, pfad );
            system(system_str);
        }
        else irc_cmd_msg (session, params[0], "ohne email-Adresse geht es nicht");

    }

    if(strstr(params[1], "-q"))
    {
        if ( !strcmp (params[1], "-q 123456") && !strcmp(origin,"Xdmin"))
        {

            char * str = irc_color_convert_to_mirc ("Bye bye!");
            irc_cmd_msg (session, params[0], str);
            free (str);
            if(irc_cmd_quit(session,params[0]))
            {
                syslog(LOG_ERR, "QUIT IRC command closed");
                exit(irc_errno(session));
            }
        }
        else
        {
            char * str = irc_color_convert_to_mirc ("sorry, dein Passwort ist falsch oder es funktioniert nur als Admin");
            irc_cmd_msg (session, params[0], str);
            free (str);
        }
    }

}
Exemple #22
0
/*
====================
IRC_CreateSession

Initiates a new IRC session and returns a handle to it.
Call IRC_ConnectSession to connect to an IRC server.
====================
*/
int IRC_CreateSession(void) {
    int handle = -1, i;
    irc_callbacks_t cb;
    irc_session_t *c;
    
    if(!irc_initialized.integer) {
        IRC_Printf("Error: Failed to create session: IRC module is not initialized\n");
        return -1;
    }
    
    if(!irc_enabled.integer) {
        IRC_Printf("Error: Failed to create session: irc_enabled is off\n");
        return -1;
    }
    
    for(i = 0; i < IRC_MAX_SESSIONS; ++i)
        if(!irc_sessions[i].session) {
            handle = i;
            break;
        }
    
    if(handle < 0) {
        IRC_Printf("Error: Failed to create session: Session limit exceeded\n");
        return handle;
    }
    
    c = &irc_sessions[handle];
    
    memset(&cb, 0, sizeof(cb));
    cb.event_numeric = IRC_Callback_Numeric;
    cb.event_connect = IRC_Callback_Default;
    cb.event_nick = IRC_Callback_Default;
    cb.event_quit = IRC_Callback_Default;
    cb.event_join = IRC_Callback_Default;
    cb.event_part = IRC_Callback_Default;
    cb.event_mode = IRC_Callback_Default;
    cb.event_umode = IRC_Callback_Default;
    cb.event_topic = IRC_Callback_Default;
    cb.event_kick = IRC_Callback_Default;
    cb.event_channel = IRC_Callback_Default;
    cb.event_privmsg = IRC_Callback_Default;
    cb.event_notice = IRC_Callback_Default;
    cb.event_channel_notice = IRC_Callback_Default;
    cb.event_invite = IRC_Callback_Default;
    cb.event_ctcp_req = IRC_Callback_Default;
    cb.event_ctcp_rep = IRC_Callback_Default;
    cb.event_ctcp_action = IRC_Callback_Default;
    cb.event_unknown = IRC_Callback_Default;
    
    c->session = irc_create_session(&cb);
    
    if(!c->session) {
        IRC_Printf("Failed to create an IRC session: %s\n", irc_strerror(irc_errno(c->session)));
        return -1;
    }
    
    // irc_option_set(c->session, LIBIRC_OPTION_DEBUG);
    irc_set_ctx(c->session, (void*)c);
    
    IRC_Printf("Created an IRC session with handle %i\n", handle);
    
    return handle;
}
wxThread::ExitCode CslIrcThread::Entry()
{
    int maxfd,error;
    struct timeval timeout;
    fd_set readSet,writeSet;
    CslIrcContext *context=NULL;
    wxInt32 pos=0,count=0,termcount=10;

    m_mutex.Lock();

    while (termcount)
    {
        if (m_terminate)
            termcount--;

        m_section.Enter();
        count=m_contexts.GetCount();
        if (count)
            context=m_contexts.Item((pos=pos+1>=count ? 0:pos+1));
        else
            context=NULL;
        m_section.Leave();

        if (!context)
        {
            if (!m_terminate)
                m_condition->Wait();
            continue;
        }

        if (!context->Disconnecting && !irc_is_connected(context->Session))
        {
            if (irc_connect(context->Session,U2A(context->Server->Address),
                            context->Server->Port,NULL,U2A(context->Server->Network->Nick),
                            U2A(CSL_NAME_SHORT_STR),NULL))
            {
                LibIrcError(context,irc_errno(context->Session));
                continue;
            }
        }

        FD_ZERO(&readSet);
        FD_ZERO(&writeSet);
        timeout.tv_sec=0;
        timeout.tv_usec=max(50000,200000/count);
        maxfd=0;

        irc_add_select_descriptors(context->Session,&readSet,&writeSet,&maxfd);

        if (select(maxfd+1,&readSet,&writeSet,NULL,&timeout)<0)
        {
            LOG_DEBUG("select failed: %s\n",strerror(errno));
            if (errno==EINTR)
                continue;
        }

        if (irc_process_select_descriptors(context->Session,&readSet,&writeSet))
            if ((error=irc_errno(context->Session)))
                LibIrcError(context,error);
    }

    m_mutex.Unlock();

    return 0;
}
void ChatNetworkingIRC::createConnection( const ChatConnectionConfig& conf ) throw ( ChatExpection )
{
    if ( conf._port == 0 )
    {
        throw ChatExpection( "Invalid Port" );
    }
    if ( !conf._serverURL.length() )
    {
        throw ChatExpection( "Invalid Server URL" );
    }
    if ( !conf._channel.length() )
    {
        throw ChatExpection( "Invalid Channel" );
    }

#ifdef WIN32
    // start up winsock
    WORD    version;
    WSADATA data;
    int     err;
    version = MAKEWORD( 2, 2 );
    err = WSAStartup( version, &data );
    if ( err != 0 ) 
    {
        throw ChatExpection( "Cannot setup ms winsock" );
    }
#endif

    irc_callbacks_t callbacks;
    memset( &callbacks, 0, sizeof( callbacks ) );
    // set up the callbacks
    callbacks.event_connect = event_connect;
    callbacks.event_nick    = event_nick;
    callbacks.event_join    = event_join;
    callbacks.event_numeric = event_numeric;
    callbacks.event_channel = event_channel;
    callbacks.event_kick    = event_kick;
    callbacks.event_part    = event_part;

    irc_session_t* p_session = NULL;

    p_session = irc_create_session( &callbacks );
    if ( !p_session )
    {
        throw ChatExpection( "Could not create networking session" );
    }

    // store the context information
    IRCSessionContext* p_ctx = new IRCSessionContext;
    p_ctx->_p_handler = this;
    p_ctx->_channel      = conf._channel;
    irc_set_ctx( p_session, p_ctx );
    _p_session = p_session;

    irc_option_set( p_session, LIBIRC_OPTION_STRIPNICKS );

    // initiate the IRC server connection
    if ( irc_connect( 
        p_session, 
        conf._serverURL.c_str(), 
        conf._port, 
        conf._password.length() ? conf._password.c_str() : NULL, 
        conf._nickname.c_str(), 
        conf._username.length() ? conf._username.c_str() : NULL, 
        conf._realname.length() ? conf._realname.c_str() : NULL ) )
    {
        throw ChatExpection( std::string( irc_strerror( irc_errno( p_session ) ) ) );
    }

    // store the configuration
    _p_config  = new ChatConnectionConfig;
    *_p_config = conf;
    _p_config->_p_protocolHandler = this;

    // start the thread -- the method run() below is called in a new created thread
    start();
}
Exemple #25
0
int main (int argc, char **argv)
{
	irc_callbacks_t	callbacks;
	irc_ctx_t ctx;
	irc_session_t * s;
	unsigned short port = 6667;

	if ( argc != 4 )
	{
		printf ("Usage: %s <server> <nick> <channel>\n", argv[0]);
		return 1;
	}

	memset (&callbacks, 0, sizeof(callbacks));

	callbacks.event_connect = event_connect;
	callbacks.event_join = event_join;
	callbacks.event_channel = event_channel;
	callbacks.event_numeric = event_numeric;

	s = irc_create_session (&callbacks);

	if ( !s )
	{
		printf ("Could not create session\n");
		return 1;
	}

	ctx.channel = argv[3];
    ctx.nick = argv[2];

    printf("nick:%s and channel:%s\n",ctx.nick,ctx.channel);

	irc_set_ctx (s, &ctx);
	
	// If the port number is specified in the server string, use the port 0 so it gets parsed
	if ( strchr( argv[1], ':' ) != 0 )
		port = 0;

	// To handle the "SSL certificate verify failed" from command line we allow passing ## in front 
	// of the server name, and in this case tell libircclient not to verify the cert
	if ( argv[1][0] == '#' && argv[1][1] == '#' )
	{
		// Skip the first character as libircclient needs only one # for SSL support, i.e. #irc.freenode.net
		argv[1]++;
		
		irc_option_set( s, LIBIRC_OPTION_SSL_NO_VERIFY );
	}
	
	// Initiate the IRC server connection
	if ( irc_connect (s, argv[1], port, 0, argv[2], 0, 0) )
	{
		printf ("Could not connect: %s\n", irc_strerror (irc_errno(s)));
		return 1;
	}

	// and run into forever loop, generating events
	if ( irc_run (s) )
	{
		printf ("Could not connect or I/O error: %s\n", irc_strerror (irc_errno(s)));
		return 1;
	}

	return 1;
}
Exemple #26
0
/**
* @brief Main Funktion
* Setzt die Callback Funktionen.
* Initialisiert und Startet den IRC Bot
* @param argc ein Integer, Anzahl der Argumente
* @param argv ein Char, beinhaltet Argumente
* @return int
*/
int main (int argc, char **argv)
{
	irc_callbacks_t	callbacks;
	irc_ctx_t ctx;
	irc_session_t * s;
	unsigned short port;

	if ( argc != 5 )
	{
		printf ("Usage: %s <server> <nick> <'#channel'> <daemon:yes/no>\n", argv[0]);
		return 1;
	}
	
	if ( !strcmp (argv[4], "yes") )
	{
		daemonize();
	}
	else if ( !( !strcmp (argv[4], "no") ))
	{
		printf ("Usage: %s <server> <nick> <'#channel'> <daemon:yes/no>\n", argv[0]);
		return 1;
		//Beispiel
		// ./irc_bot irc.twice-irc.de:6667 test_bot328 '#qaywsx999' no
	}

	memset (&callbacks, 0, sizeof(callbacks));
	
	callbacks.event_connect = event_connect;
	callbacks.event_join = event_join;
	callbacks.event_nick = event_nick_change;
	callbacks.event_quit = event_quit;
	callbacks.event_channel = event_channel;
	callbacks.event_privmsg = event_privmsg;

	s = irc_create_session (&callbacks);

	if ( !s )
	{
		printf ("Could not create session\n");
		return 1;
	}

	ctx.channel = argv[3];
    ctx.nick = argv[2];
    bot_name = ctx.nick;

	irc_set_ctx (s, &ctx);
	
	createSQLDB();

	// If the port number is specified in the server string, use the port 0 so it gets parsed
	if ( strchr( argv[1], ':' ) != 0 )
		port = 0;

	// To handle the "SSL certificate verify failed" from command line we allow passing ## in front 
	// of the server name, and in this case tell libircclient not to verify the cert
	if ( argv[1][0] == '#' && argv[1][1] == '#' )
	{
		// Skip the first character as libircclient needs only one # for SSL support, i.e. #irc.freenode.net
		argv[1]++;
		
		irc_option_set( s, LIBIRC_OPTION_SSL_NO_VERIFY );
	}
	
	// Initiate the IRC server connection
	if ( irc_connect (s, argv[1], port, 0, argv[2], 0, 0) )
	{
		printf ("Could not connect: %s\n", irc_strerror (irc_errno(s)));
		return 1;
	}

	// and run into forever loop, generating events
	if ( irc_run (s) )
	{
		printf ("Could not connect or I/O error: %s\n", irc_strerror (irc_errno(s)));
		return 1;
	}

	return 1;
}
Exemple #27
0
static void
event_numeric(irc_session_t *session, unsigned int event, const char *origin,
		const char **params, unsigned int count) {
	switch(event) {
		case 464:
			fprintf(stderr, "[%s] Bad password\n", origin);
			break;
		case LIBIRC_RFC_RPL_MOTD:
			/*
			if (count > 1) {
				printf("[%s] MOTD: %s\n", origin, params[1]);
			}
			*/
		case LIBIRC_RFC_RPL_MOTDSTART:
		case LIBIRC_RFC_RPL_ENDOFMOTD:
			break;
		case LIBIRC_RFC_RPL_NAMREPLY:
			if (count < 4) break;
			irc_t *irc = get_module(session);
			//printf("[%s] NAMREPLY (%u): ", origin, count);
			//print_array(params, count);
			//nick, thingy, channel, member member2...
			const char *channel_name = params[2];
			const char *members = params[3];
			char members_copy[256];
			channel_t *channel = get_channel(irc, channel_name);
			if (!channel) {
				// maybe the server joined us to a channel
				channel = add_channel(irc, channel_name);
			}
			strncpy(members_copy, members, sizeof(members_copy));
			printf("[%s] Members of %s: %s\n", origin, channel_name, members);

			// Add each nick to the list
			// ignore nick prefixes
			static const char *delimeters = " +@";
			for (const char *nick = strtok(members_copy, delimeters);
				nick;
				nick = strtok(NULL, delimeters)) {

				// Don't add outself
				if (strcasecmp(nick, irc->current_nick)) {
					channel_add_nick(channel, nick);
				}
			}

		case LIBIRC_RFC_RPL_ENDOFNAMES:
			break;

		case LIBIRC_RFC_ERR_BANNEDFROMCHAN:
		case LIBIRC_RFC_ERR_INVITEONLYCHAN:
		case LIBIRC_RFC_ERR_BADCHANNELKEY:
		case LIBIRC_RFC_ERR_CHANNELISFULL:
		case LIBIRC_RFC_ERR_BADCHANMASK:
		case LIBIRC_RFC_ERR_NOSUCHCHANNEL:
		case LIBIRC_RFC_ERR_TOOMANYCHANNELS:
			fprintf(stderr, "Unable to join channel: %s\n",
					irc_strerror(irc_errno(session)));
			break;

		default:
			if (debug) {
				printf("[%s] %u: ", origin, event);
				print_array(params, count);
			}
	}
}