source: protocols/jabber/jabber.c @ f712188

Last change on this file since f712188 was 43e3368, checked in by Wilmer van der Gaast <wilmer@…>, at 2005-11-23T17:35:18Z

Little code cleanup in Jabber module, added support for Jabber headline messages.

  • Property mode set to 100644
File size: 59.8 KB
Line 
1/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
2/*
3 * gaim
4 *
5 * Some code copyright (C) 1998-1999, Mark Spencer <markster@marko.net>
6 * libfaim code copyright 1998, 1999 Adam Fritzler <afritz@auk.cx>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21 *
22 */
23
24#ifdef HAVE_CONFIG_H
25#include "config.h"
26#endif
27
28#ifndef _WIN32
29#include <sys/utsname.h>
30#endif
31#include <errno.h>
32#include <string.h>
33#include <stdlib.h>
34#include <stdio.h>
35#include <time.h>
36#include <sys/stat.h>
37#include "jabber.h"
38#include "nogaim.h"
39#include "bitlbee.h"
40#include "proxy.h"
41#include "ssl_client.h"
42
43/* The priv member of gjconn's is a gaim_connection for now. */
44#define GJ_GC(x) ((struct gaim_connection *)(x)->priv)
45
46#define IQID_AUTH "__AUTH__"
47
48#define IQ_NONE -1
49#define IQ_AUTH 0
50#define IQ_ROSTER 1
51
52#define UC_AWAY (0x02 | UC_UNAVAILABLE)
53#define UC_CHAT  0x04
54#define UC_XA   (0x08 | UC_UNAVAILABLE)
55#define UC_DND  (0x10 | UC_UNAVAILABLE)
56
57#define DEFAULT_SERVER "jabber.org"
58#define DEFAULT_GROUPCHAT "conference.jabber.org"
59#define DEFAULT_PORT 5222
60#define DEFAULT_PORT_SSL 5223
61
62#define JABBER_GROUP "Friends"
63
64/* i18n disabled - Bitlbee */
65#define N_(String) String
66
67/*
68 * Note: "was_connected" may seem redundant, but it was needed and I
69 * didn't want to touch the Jabber state stuff not specific to Gaim.
70 */
71typedef struct gjconn_struct {
72        /* Core structure */
73        pool p;                 /* Memory allocation pool */
74        int state;              /* Connection state flag */
75        int was_connected;      /* We were once connected */
76        int fd;                 /* Connection file descriptor */
77        void *ssl;              /* SSL connection */
78        jid user;               /* User info */
79        char *pass;             /* User passwd */
80
81        /* Stream stuff */
82        int id;                 /* id counter for jab_getid() function */
83        char idbuf[9];          /* temporary storage for jab_getid() */
84        char *sid;              /* stream id from server, for digest auth */
85        XML_Parser parser;      /* Parser instance */
86        xmlnode current;        /* Current node in parsing instance.. */
87
88        /* Event callback ptrs */
89        void (*on_state)(struct gjconn_struct *gjc, int state);
90        void (*on_packet)(struct gjconn_struct *gjc, jpacket p);
91
92        GHashTable *queries;    /* query tracker */
93
94        void *priv;
95} *gjconn, gjconn_struct;
96
97typedef void (*gjconn_state_h)(gjconn gjc, int state);
98typedef void (*gjconn_packet_h)(gjconn gjc, jpacket p);
99
100static gjconn gjab_new(char *user, char *pass, void *priv);
101static void gjab_delete(gjconn gjc);
102static void gjab_state_handler(gjconn gjc, gjconn_state_h h);
103static void gjab_packet_handler(gjconn gjc, gjconn_packet_h h);
104static void gjab_start(gjconn gjc);
105static void gjab_stop(gjconn gjc);
106/*
107static int gjab_getfd(gjconn gjc);
108static jid gjab_getjid(gjconn gjc);
109static char *gjab_getsid(gjconn gjc);
110*/
111static char *gjab_getid(gjconn gjc);
112static void gjab_send(gjconn gjc, xmlnode x);
113static void gjab_send_raw(gjconn gjc, const char *str);
114static void gjab_recv(gjconn gjc);
115static void gjab_auth(gjconn gjc);
116
117/*
118 * It is *this* to which we point the gaim_connection proto_data
119 */
120struct jabber_data {
121        gjconn gjc;
122        gboolean did_import;
123        GSList *chats;
124        GHashTable *hash;
125        time_t idle;
126        gboolean die;
127};
128
129/*
130 * Jabber "chat group" info.  Pointers to these go in jabber_data
131 * pending and existing chats lists.
132 */
133struct jabber_chat {
134        jid Jid;
135        struct gaim_connection *gc;
136        struct conversation *b;
137        int id;
138        int state;
139};
140
141/*
142 * Jabber chat states...
143 *
144 * Note: due to a bug in one version of the Jabber server, subscriptions
145 * to chat groups aren't (always?) properly removed at the server.  The
146 * result is clients receive Jabber "presence" notifications for JIDs
147 * they no longer care about.  The problem with such vestigial notifies is
148 * that we really have no way of telling if it's vestigial or if it's a
149 * valid "buddy" presence notification.  So we keep jabber_chat structs
150 * around after leaving a chat group and simply mark them "closed."  That
151 * way we can test for such errant presence notifications.  I.e.: if we
152 * get a presence notfication from a JID that matches a chat group JID,
153 * we disregard it.
154 */
155#define JCS_PENDING 1   /* pending */
156#define JCS_ACTIVE  2   /* active */
157#define JCS_CLOSED  3   /* closed */
158
159
160static char *jabber_name()
161{
162        return "Jabber";
163}
164
165#define STATE_EVT(arg) if(gjc->on_state) { (gjc->on_state)(gjc, (arg) ); }
166
167static void jabber_remove_buddy(struct gaim_connection *gc, char *name, char *group);
168static void jabber_handlevcard(gjconn gjc, xmlnode querynode, char *from);
169
170static char *create_valid_jid(const char *given, char *server, char *resource)
171{
172        char *valid;
173
174        if (!strchr(given, '@'))
175                valid = g_strdup_printf("%s@%s/%s", given, server, resource);
176        else if (!strchr(strchr(given, '@'), '/'))
177                valid = g_strdup_printf("%s/%s", given, resource);
178        else
179                valid = g_strdup(given);
180
181        return valid;
182}
183
184static gjconn gjab_new(char *user, char *pass, void *priv)
185{
186        pool p;
187        gjconn gjc;
188
189        if (!user)
190                return (NULL);
191
192        p = pool_new();
193        if (!p)
194                return (NULL);
195        gjc = pmalloc_x(p, sizeof(gjconn_struct), 0);
196        if (!gjc) {
197                pool_free(p);   /* no need for this anymore! */
198                return (NULL);
199        }
200        gjc->p = p;
201
202        if((gjc->user = jid_new(p, user)) == NULL) {
203                pool_free(p);   /* no need for this anymore! */
204                return (NULL);
205        }
206        gjc->pass = pstrdup(p, pass);
207
208        gjc->state = JCONN_STATE_OFF;
209        gjc->was_connected = 0;
210        gjc->id = 1;
211        gjc->fd = -1;
212
213        gjc->priv = priv;
214
215        return gjc;
216}
217
218static void gjab_delete(gjconn gjc)
219{
220        if (!gjc)
221                return;
222
223        gjab_stop(gjc);
224        pool_free(gjc->p);
225}
226
227static void gjab_state_handler(gjconn gjc, gjconn_state_h h)
228{
229        if (!gjc)
230                return;
231
232        gjc->on_state = h;
233}
234
235static void gjab_packet_handler(gjconn gjc, gjconn_packet_h h)
236{
237        if (!gjc)
238                return;
239
240        gjc->on_packet = h;
241}
242
243static void gjab_stop(gjconn gjc)
244{
245        if (!gjc || gjc->state == JCONN_STATE_OFF)
246                return;
247
248        gjab_send_raw(gjc, "</stream:stream>");
249        gjc->state = JCONN_STATE_OFF;
250        gjc->was_connected = 0;
251        if (gjc->ssl) {
252                ssl_disconnect(gjc->ssl);
253                gjc->ssl = NULL;
254        } else {
255                closesocket(gjc->fd);
256        }
257        gjc->fd = -1;
258        XML_ParserFree(gjc->parser);
259        gjc->parser = NULL;
260}
261
262/*
263static int gjab_getfd(gjconn gjc)
264{
265        if (gjc)
266                return gjc->fd;
267        else
268                return -1;
269}
270
271static jid gjab_getjid(gjconn gjc)
272{
273        if (gjc)
274                return (gjc->user);
275        else
276                return NULL;
277}
278
279static char *gjab_getsid(gjconn gjc)
280{
281        if (gjc)
282                return (gjc->sid);
283        else
284                return NULL;
285}
286*/
287
288static char *gjab_getid(gjconn gjc)
289{
290        g_snprintf(gjc->idbuf, 8, "%d", gjc->id++);
291        return &gjc->idbuf[0];
292}
293
294static void gjab_send(gjconn gjc, xmlnode x)
295{
296        if (gjc && gjc->state != JCONN_STATE_OFF) {
297                char *buf = xmlnode2str(x);
298                if (!buf)
299                        return;
300                else if (gjc->ssl)
301                        ssl_write(gjc->ssl, buf, strlen(buf));
302                else
303                        write(gjc->fd, buf, strlen(buf));
304        }
305}
306
307static void gjab_send_raw(gjconn gjc, const char *str)
308{
309        if (gjc && gjc->state != JCONN_STATE_OFF) {
310                int len;
311               
312                /*
313                 * JFIXME: No error detection?!?!
314                 */
315                if (gjc->ssl)
316                        len = ssl_write(gjc->ssl, str, strlen(str));
317                else
318                        len = write(gjc->fd, str, strlen(str));
319                       
320                if(len < 0) {
321                        /* Do NOT write to stdout/stderr directly, IRC clients
322                           might get confused, and we don't want that...
323                        fprintf(stderr, "DBG: Problem sending.  Error: %d\n", errno);
324                        fflush(stderr); */
325                }
326        }
327}
328
329static void gjab_reqroster(gjconn gjc)
330{
331        xmlnode x;
332
333        x = jutil_iqnew(JPACKET__GET, NS_ROSTER);
334        xmlnode_put_attrib(x, "id", gjab_getid(gjc));
335
336        gjab_send(gjc, x);
337        xmlnode_free(x);
338}
339
340static void gjab_reqauth(gjconn gjc)
341{
342        xmlnode x, y, z;
343        char *user;
344
345        if (!gjc)
346                return;
347
348        x = jutil_iqnew(JPACKET__GET, NS_AUTH);
349        xmlnode_put_attrib(x, "id", IQID_AUTH);
350        y = xmlnode_get_tag(x, "query");
351
352        user = gjc->user->user;
353
354        if (user) {
355                z = xmlnode_insert_tag(y, "username");
356                xmlnode_insert_cdata(z, user, -1);
357        }
358
359        gjab_send(gjc, x);
360        xmlnode_free(x);
361}
362
363static void gjab_auth(gjconn gjc)
364{
365        xmlnode x, y, z;
366        char *hash, *user;
367
368        if (!gjc)
369                return;
370
371        x = jutil_iqnew(JPACKET__SET, NS_AUTH);
372        xmlnode_put_attrib(x, "id", IQID_AUTH);
373        y = xmlnode_get_tag(x, "query");
374
375        user = gjc->user->user;
376
377        if (user) {
378                z = xmlnode_insert_tag(y, "username");
379                xmlnode_insert_cdata(z, user, -1);
380        }
381
382        z = xmlnode_insert_tag(y, "resource");
383        xmlnode_insert_cdata(z, gjc->user->resource, -1);
384
385        if (gjc->sid) {
386                z = xmlnode_insert_tag(y, "digest");
387                hash = pmalloc(x->p, strlen(gjc->sid) + strlen(gjc->pass) + 1);
388                strcpy(hash, gjc->sid);
389                strcat(hash, gjc->pass);
390                hash = shahash(hash);
391                xmlnode_insert_cdata(z, hash, 40);
392        } else {
393                z = xmlnode_insert_tag(y, "password");
394                xmlnode_insert_cdata(z, gjc->pass, -1);
395        }
396
397        gjab_send(gjc, x);
398        xmlnode_free(x);
399
400        return;
401}
402
403static void gjab_recv(gjconn gjc)
404{
405        static char buf[4096];
406        int len;
407
408        if (!gjc || gjc->state == JCONN_STATE_OFF)
409                return;
410       
411        if (gjc->ssl)
412                len = ssl_read(gjc->ssl, buf, sizeof(buf) - 1);
413        else
414                len = read(gjc->fd, buf, sizeof(buf) - 1);
415       
416        if (len > 0) {
417                struct jabber_data *jd = GJ_GC(gjc)->proto_data;
418                buf[len] = '\0';
419                XML_Parse(gjc->parser, buf, len, 0);
420                if (jd->die)
421                        signoff(GJ_GC(gjc));
422        } else if (len < 0 || errno != EAGAIN) {
423                STATE_EVT(JCONN_STATE_OFF)
424        }
425}
426
427static void startElement(void *userdata, const char *name, const char **attribs)
428{
429        xmlnode x;
430        gjconn gjc = (gjconn) userdata;
431
432        if (gjc->current) {
433                /* Append the node to the current one */
434                x = xmlnode_insert_tag(gjc->current, name);
435                xmlnode_put_expat_attribs(x, attribs);
436
437                gjc->current = x;
438        } else {
439                x = xmlnode_new_tag(name);
440                xmlnode_put_expat_attribs(x, attribs);
441                if (strcmp(name, "stream:stream") == 0) {
442                        /* special case: name == stream:stream */
443                        /* id attrib of stream is stored for digest auth */
444                        gjc->sid = g_strdup(xmlnode_get_attrib(x, "id"));
445                        /* STATE_EVT(JCONN_STATE_AUTH) */
446                        xmlnode_free(x);
447                } else {
448                        gjc->current = x;
449                }
450        }
451}
452
453static void endElement(void *userdata, const char *name)
454{
455        gjconn gjc = (gjconn) userdata;
456        xmlnode x;
457        jpacket p;
458
459        if (gjc->current == NULL) {
460                /* we got </stream:stream> */
461                STATE_EVT(JCONN_STATE_OFF)
462                    return;
463        }
464
465        x = xmlnode_get_parent(gjc->current);
466
467        if (!x) {
468                /* it is time to fire the event */
469                p = jpacket_new(gjc->current);
470
471                if (gjc->on_packet)
472                        (gjc->on_packet) (gjc, p);
473                else
474                        xmlnode_free(gjc->current);
475        }
476
477        gjc->current = x;
478}
479
480static void jabber_callback(gpointer data, gint source, GaimInputCondition condition)
481{
482        struct gaim_connection *gc = (struct gaim_connection *)data;
483        struct jabber_data *jd = (struct jabber_data *)gc->proto_data;
484
485        gjab_recv(jd->gjc);
486}
487
488static void charData(void *userdata, const char *s, int slen)
489{
490        gjconn gjc = (gjconn) userdata;
491
492        if (gjc->current)
493                xmlnode_insert_cdata(gjc->current, s, slen);
494}
495
496static void gjab_connected(gpointer data, gint source, GaimInputCondition cond)
497{
498        xmlnode x;
499        char *t, *t2;
500        struct gaim_connection *gc = data;
501        struct jabber_data *jd;
502        gjconn gjc;
503
504        if (!g_slist_find(get_connections(), gc)) {
505                closesocket(source);
506                return;
507        }
508
509        jd = gc->proto_data;
510        gjc = jd->gjc;
511
512        if (gjc->fd != source)
513                gjc->fd = source;
514
515        if (source == -1) {
516                STATE_EVT(JCONN_STATE_OFF)
517                return;
518        }
519
520        gjc->state = JCONN_STATE_CONNECTED;
521        STATE_EVT(JCONN_STATE_CONNECTED)
522
523        /* start stream */
524        x = jutil_header(NS_CLIENT, gjc->user->server);
525        t = xmlnode2str(x);
526        /* this is ugly, we can create the string here instead of jutil_header */
527        /* what do you think about it? -madcat */
528        t2 = strstr(t, "/>");
529        *t2++ = '>';
530        *t2 = '\0';
531        gjab_send_raw(gjc, "<?xml version='1.0'?>");
532        gjab_send_raw(gjc, t);
533        xmlnode_free(x);
534
535        gjc->state = JCONN_STATE_ON;
536        STATE_EVT(JCONN_STATE_ON);
537
538        gc = GJ_GC(gjc);
539        gc->inpa = gaim_input_add(gjc->fd, GAIM_INPUT_READ, jabber_callback, gc);
540}
541
542static void gjab_connected_ssl(gpointer data, void *source, GaimInputCondition cond)
543{
544        struct gaim_connection *gc = data;
545        struct jabber_data *jd;
546        gjconn gjc;
547       
548        if (!g_slist_find(get_connections(), gc)) {
549                ssl_disconnect(source);
550                return;
551        }
552       
553        jd = gc->proto_data;
554        gjc = jd->gjc;
555       
556        if (source == NULL) {
557                STATE_EVT(JCONN_STATE_OFF)
558                return;
559        }
560       
561        gjab_connected(data, gjc->fd, cond);
562}
563
564static void gjab_start(gjconn gjc)
565{
566        struct aim_user *user;
567        int port = -1, ssl = 0;
568        char *server = NULL, *s;
569
570        if (!gjc || gjc->state != JCONN_STATE_OFF)
571                return;
572
573        user = GJ_GC(gjc)->user;
574        if (*user->proto_opt[0]) {
575                /* If there's a dot, assume there's a hostname in the beginning */
576                if (strchr(user->proto_opt[0], '.')) {
577                        server = g_strdup(user->proto_opt[0]);
578                        if ((s = strchr(server, ':')))
579                                *s = 0;
580                }
581               
582                /* After the hostname, there can be a port number */
583                s = strchr(user->proto_opt[0], ':');
584                if (s && isdigit(s[1]))
585                        sscanf(s + 1, "%d", &port);
586               
587                /* And if there's the string ssl, the user wants an SSL-connection */
588                if (strstr(user->proto_opt[0], ":ssl") || g_strcasecmp(user->proto_opt[0], "ssl") == 0)
589                        ssl = 1;
590        }
591       
592        if (port == -1 && !ssl)
593                port = DEFAULT_PORT;
594        else if (port == -1 && ssl)
595                port = DEFAULT_PORT_SSL;
596       
597        if (server == NULL)
598                server = g_strdup(gjc->user->server);
599
600        gjc->parser = XML_ParserCreate(NULL);
601        XML_SetUserData(gjc->parser, (void *)gjc);
602        XML_SetElementHandler(gjc->parser, startElement, endElement);
603        XML_SetCharacterDataHandler(gjc->parser, charData);
604       
605        if (ssl) {
606                if ((gjc->ssl = ssl_connect(server, port, gjab_connected_ssl, GJ_GC(gjc))))
607                        gjc->fd = ssl_getfd(gjc->ssl);
608                else
609                        gjc->fd = -1;
610        } else {
611                gjc->fd = proxy_connect(server, port, gjab_connected, GJ_GC(gjc));
612        }
613       
614        g_free(server);
615       
616        if (!user->gc || (gjc->fd < 0)) {
617                STATE_EVT(JCONN_STATE_OFF)
618                return;
619        }
620}
621
622/*
623 * Find existing/active Jabber chat
624 */
625static struct jabber_chat *find_existing_chat(struct gaim_connection *gc, jid chat)
626{
627        GSList *jcs = ((struct jabber_data *)gc->proto_data)->chats;
628        struct jabber_chat *jc = NULL;
629
630        while (jcs) {
631                jc = jcs->data;
632                if (jc->state == JCS_ACTIVE && !jid_cmpx(chat, jc->Jid, JID_USER | JID_SERVER))
633                        break;
634                jc = NULL;
635                jcs = jcs->next;
636        }
637
638        return jc;
639}
640
641/*
642 * Find pending chat
643 */
644static struct jabber_chat *find_pending_chat(struct gaim_connection *gc, jid chat)
645{
646        GSList *jcs = ((struct jabber_data *)gc->proto_data)->chats;
647        struct jabber_chat *jc = NULL;
648
649        while (jcs) {
650                jc = jcs->data;
651                if (jc->state == JCS_PENDING && !jid_cmpx(chat, jc->Jid, JID_USER | JID_SERVER))
652                        break;
653                jc = NULL;
654                jcs = jcs->next;
655        }
656
657        return jc;
658}
659
660static gboolean find_chat_buddy(struct conversation *b, char *name)
661{
662        GList *m = b->in_room;
663
664        while (m) {
665                if (!strcmp(m->data, name))
666                        return TRUE;
667                m = m->next;
668        }
669
670        return FALSE;
671}
672
673/*
674 * Remove a buddy from the (gaim) buddylist (if he's on it)
675 */
676static void jabber_remove_gaim_buddy(struct gaim_connection *gc, char *buddyname)
677{
678        struct buddy *b;
679
680        if ((b = find_buddy(gc, buddyname)) != NULL) {
681                /* struct group *group;
682
683                group = find_group_by_buddy(gc, buddyname);
684                remove_buddy(gc, group, b); */
685                jabber_remove_buddy(gc, b->name, JABBER_GROUP);
686        }
687}
688
689/*
690 * keep track of away msg same as yahoo plugin
691 */
692static void jabber_track_away(gjconn gjc, jpacket p, char *name, char *type)
693{
694        struct jabber_data *jd = GJ_GC(gjc)->proto_data;
695        gpointer val = g_hash_table_lookup(jd->hash, name);
696        char *show;
697        char *vshow = NULL;
698        char *status = NULL;
699        char *msg = NULL;
700
701        if (type && (g_strcasecmp(type, "unavailable") == 0)) {
702                vshow = _("Unavailable");
703        } else {
704                if((show = xmlnode_get_tag_data(p->x, "show")) != NULL) {
705                        if (!g_strcasecmp(show, "away")) {
706                                vshow = _("Away");
707                        } else if (!g_strcasecmp(show, "chat")) {
708                                vshow = _("Online");
709                        } else if (!g_strcasecmp(show, "xa")) {
710                                vshow = _("Extended Away");
711                        } else if (!g_strcasecmp(show, "dnd")) {
712                                vshow = _("Do Not Disturb");
713                        }
714                }
715        }
716
717        status = xmlnode_get_tag_data(p->x, "status");
718
719        if(vshow != NULL || status != NULL ) {
720                /* kinda hokey, but it works :-) */
721                msg = g_strdup_printf("%s%s%s",
722                        (vshow == NULL? "" : vshow),
723                        (vshow == NULL || status == NULL? "" : ": "),
724                        (status == NULL? "" : status));
725        } else {
726                msg = g_strdup(_("Online"));
727        }
728
729        if (val) {
730                g_free(val);
731                g_hash_table_insert(jd->hash, name, msg);
732        } else {
733                g_hash_table_insert(jd->hash, g_strdup(name), msg);
734        }
735}
736
737static time_t iso8601_to_time(char *timestamp)
738{
739        struct tm t;
740        time_t retval = 0;
741
742        if(sscanf(timestamp,"%04d%02d%02dT%02d:%02d:%02d",
743                &t.tm_year, &t.tm_mon, &t.tm_mday, &t.tm_hour, &t.tm_min, &t.tm_sec))
744        {
745                t.tm_year -= 1900;
746                t.tm_mon -= 1;
747                t.tm_isdst = 0;
748                retval = mktime(&t);
749#               ifdef HAVE_TM_GMTOFF
750                        retval += t.tm_gmtoff;
751#               else
752#                       ifdef HAVE_TIMEZONE
753                                tzset();        /* making sure */
754                                retval -= timezone;
755#                       endif
756#               endif
757        }
758
759        return retval;
760}
761
762static void jabber_handlemessage(gjconn gjc, jpacket p)
763{
764        xmlnode y, xmlns, z;
765        time_t time_sent = time(NULL);
766
767        char *from = NULL, *msg = NULL, *type = NULL;
768        char m[BUF_LONG * 2];
769
770        type = xmlnode_get_attrib(p->x, "type");
771
772        z = xmlnode_get_firstchild(p->x);
773
774        while(z)
775        {
776           if(NSCHECK(z,NS_DELAY))
777           {
778              char *timestamp = xmlnode_get_attrib(z,"stamp");
779              time_sent = iso8601_to_time(timestamp);
780           }
781           z = xmlnode_get_nextsibling(z);
782        }
783
784        if (!type || !g_strcasecmp(type, "normal") || !g_strcasecmp(type, "chat")) {
785
786                /* XXX namespaces could be handled better. (mid) */
787                if ((xmlns = xmlnode_get_tag(p->x, "x")))
788                        type = xmlnode_get_attrib(xmlns, "xmlns");
789
790                from = jid_full(p->from);
791                /*
792                if ((y = xmlnode_get_tag(p->x, "html"))) {
793                        msg = xmlnode_get_data(y);
794                } else
795                */
796                if ((y = xmlnode_get_tag(p->x, "body"))) {
797                        msg = xmlnode_get_data(y);
798                }
799
800
801                if (!from)
802                        return;
803
804                if (type && !g_strcasecmp(type, "jabber:x:conference")) {
805                        /* do nothing */
806                } else if (msg) { /* whisper */
807                        struct jabber_chat *jc;
808                        g_snprintf(m, sizeof(m), "%s", msg);
809                        if (((jc = find_existing_chat(GJ_GC(gjc), p->from)) != NULL) && jc->b)
810                                serv_got_chat_in(GJ_GC(gjc), jc->b->id, p->from->resource, 1, m, time_sent);
811                        else {
812                                int flags = 0;
813                               
814                                if(p->from->user) {
815                                    from = g_strdup_printf("%s@%s", p->from->user, p->from->server);
816                                } else {
817                                    /* server message? */
818                                    from = g_strdup(p->from->server);
819                                }
820                                serv_got_im(GJ_GC(gjc), from, m, flags, time_sent, -1);
821                                g_free(from);
822                        }
823                }
824
825        } else if (!g_strcasecmp(type, "error")) {
826                if ((y = xmlnode_get_tag(p->x, "error"))) {
827                        type = xmlnode_get_attrib(y, "code");
828                        msg = xmlnode_get_data(y);
829                }
830
831                if (msg) {
832                        from = g_strdup_printf("Error %s", type ? type : "");
833                        do_error_dialog(GJ_GC(gjc), msg, from);
834                        g_free(from);
835                }
836        } else if (!g_strcasecmp(type, "headline")) {
837                char *subject, *body, *url;
838               
839                y = xmlnode_get_tag( p->x, "body" );
840                body = y ? g_strdup( xmlnode_get_data( y ) ) : NULL;
841               
842                y = xmlnode_get_tag( p->x, "subject" );
843                subject = y ? g_strdup( xmlnode_get_data( y ) ) : NULL;
844               
845                url = NULL;
846                z = xmlnode_get_firstchild(p->x);
847                while( z )
848                {
849                        char *xtype = xmlnode_get_attrib( z, "xmlns" );
850                       
851                        if( xtype && g_strcasecmp( xtype, "jabber:x:oob" ) == 0 &&
852                                     ( y = xmlnode_get_tag( z, "url" ) ) )
853                        {
854                                url = g_strdup( xmlnode_get_data( y ) );
855                                break;
856                        }
857                       
858                        z = xmlnode_get_nextsibling( z );
859                }
860               
861                g_snprintf( m, BUF_LONG, "Subject: %s\nURL: %s\nMessage:\n%s", subject ? subject : "(none)",
862                                     url ? url : "(none)", body ? body : "(none)" );
863
864                if( p->from->user )
865                        from = g_strdup_printf( "%s@%s", p->from->user, p->from->server );
866                else
867                        from = g_strdup( p->from->server );
868               
869                serv_got_im( GJ_GC(gjc), from, m, 0, time_sent, -1 );
870               
871                g_free( from );
872                g_free( subject );
873                g_free( body );
874                g_free( url );
875        }
876}
877           
878static void jabber_handlepresence(gjconn gjc, jpacket p)
879{
880        char *to, *from, *type;
881        struct buddy *b = NULL;
882        jid who;
883        char *buddy;
884        xmlnode y;
885        char *show;
886        int state = 0;
887        GSList *resources;
888        char *res;
889        struct conversation *cnv = NULL;
890        struct jabber_chat *jc = NULL;
891
892        to = xmlnode_get_attrib(p->x, "to");
893        from = xmlnode_get_attrib(p->x, "from");
894        type = xmlnode_get_attrib(p->x, "type");
895       
896        if (type && g_strcasecmp(type, "error") == 0) {
897                return;
898        }
899        else if ((y = xmlnode_get_tag(p->x, "show"))) {
900                show = xmlnode_get_data(y);
901                if (!show) {
902                        state = 0;
903                } else if (!g_strcasecmp(show, "away")) {
904                        state = UC_AWAY;
905                } else if (!g_strcasecmp(show, "chat")) {
906                        state = UC_CHAT;
907                } else if (!g_strcasecmp(show, "xa")) {
908                        state = UC_XA;
909                } else if (!g_strcasecmp(show, "dnd")) {
910                        state = UC_DND;
911                }
912        } else {
913                state = 0;
914        }
915
916        who = jid_new(gjc->p, from);
917        if (who->user == NULL) {
918                /* FIXME: transport */
919                return;
920        }
921
922        buddy = g_strdup_printf("%s@%s", who->user, who->server);
923
924        /* um. we're going to check if it's a chat. if it isn't, and there are pending
925         * chats, create the chat. if there aren't pending chats and we don't have the
926         * buddy on our list, simply bail out. */
927        if ((cnv = NULL) == NULL) {
928                static int i = 0x70;
929                if ((jc = find_pending_chat(GJ_GC(gjc), who)) != NULL) {
930                        jc->b = cnv = serv_got_joined_chat(GJ_GC(gjc), i++, who->user);
931                        jc->id = jc->b->id;
932                        jc->state = JCS_ACTIVE;
933                } else if ((b = find_buddy(GJ_GC(gjc), buddy)) == NULL) {
934                        g_free(buddy);
935                        return;
936                }
937        }
938
939        if (!cnv) {
940                resources = b->proto_data;
941                res = who->resource;
942                if (res)
943                        while (resources) {
944                                if (!strcmp(res, resources->data))
945                                        break;
946                                resources = resources->next;
947                        }
948
949                /* keep track of away msg same as yahoo plugin */
950                jabber_track_away(gjc, p, normalize(b->name), type);
951
952                if (type && (g_strcasecmp(type, "unavailable") == 0)) {
953                        if (resources) {
954                                g_free(resources->data);
955                                b->proto_data = g_slist_remove(b->proto_data, resources->data);
956                        }
957                        if (!b->proto_data) {
958                                serv_got_update(GJ_GC(gjc), buddy, 0, 0, 0, 0, 0, 0);
959                        }
960                } else {
961                        if (!resources) {
962                                b->proto_data = g_slist_append(b->proto_data, g_strdup(res));
963                        }
964
965                        serv_got_update(GJ_GC(gjc), buddy, 1, 0, b->signon, b->idle, state, 0);
966
967                }
968        } else {
969                if (who->resource) {
970                        char *buf;
971
972                        buf = g_strdup_printf("%s@%s/%s", who->user, who->server, who->resource);
973                        jabber_track_away(gjc, p, buf, type);
974                        g_free(buf);
975
976                        if (type && !g_strcasecmp(type, "unavailable")) {
977                                struct jabber_data *jd;
978                                if (!jc && !(jc = find_existing_chat(GJ_GC(gjc), who))) {
979                                        g_free(buddy);
980                                        return;
981                                }
982                                jd = jc->gc->proto_data;
983                                /* if it's not ourselves...*/
984                                if (strcmp(who->resource, jc->Jid->resource) && jc->b) {
985                                        remove_chat_buddy(jc->b, who->resource, NULL);
986                                        g_free(buddy);
987                                        return;
988                                }
989
990                                jc->state = JCS_CLOSED;
991                                serv_got_chat_left(GJ_GC(gjc), jc->id);
992                                /*
993                                 * TBD: put back some day?
994                                jd->chats = g_slist_remove(jd->chats, jc);
995                                g_free(jc);
996                                 */
997                        } else {
998                                if ((!jc && !(jc = find_existing_chat(GJ_GC(gjc), who))) || !jc->b) {
999                                        g_free(buddy);
1000                                        return;
1001                                }
1002                                if (!find_chat_buddy(jc->b, who->resource)) {
1003                                        add_chat_buddy(jc->b, who->resource);
1004                                }
1005                        }
1006                }
1007        }
1008
1009        g_free(buddy);
1010
1011        return;
1012}
1013
1014/*
1015 * Used only by Jabber accept/deny add stuff just below
1016 */
1017struct jabber_add_permit {
1018        gjconn gjc;
1019        gchar *user;
1020};
1021
1022/*
1023 * Common part for Jabber accept/deny adds
1024 *
1025 * "type" says whether we'll permit/deny the subscribe request
1026 */
1027static void jabber_accept_deny_add(struct jabber_add_permit *jap, const char *type)
1028{
1029        xmlnode g = xmlnode_new_tag("presence");
1030
1031        xmlnode_put_attrib(g, "to", jap->user);
1032        xmlnode_put_attrib(g, "type", type);
1033        gjab_send(jap->gjc, g);
1034
1035        xmlnode_free(g);
1036}
1037
1038/*
1039 * Callback from "accept" in do_ask_dialog() invoked by jabber_handles10n()
1040 */
1041static void jabber_accept_add(gpointer w, struct jabber_add_permit *jap)
1042{
1043        jabber_accept_deny_add(jap, "subscribed");
1044        /*
1045         * If we don't already have the buddy on *our* buddylist,
1046         * ask if we want him or her added.
1047         */
1048        if(find_buddy(GJ_GC(jap->gjc), jap->user) == NULL) {
1049                show_got_added(GJ_GC(jap->gjc), NULL, jap->user, NULL, NULL);
1050        }
1051        g_free(jap->user);
1052        g_free(jap);
1053}
1054
1055/*
1056 * Callback from "deny/cancel" in do_ask_dialog() invoked by jabber_handles10n()
1057 */
1058static void jabber_deny_add(gpointer w, struct jabber_add_permit *jap)
1059{
1060        jabber_accept_deny_add(jap, "unsubscribed");
1061        g_free(jap->user);
1062        g_free(jap);
1063}
1064
1065/*
1066 * Handle subscription requests
1067 */
1068static void jabber_handles10n(gjconn gjc, jpacket p)
1069{
1070        xmlnode g;
1071        char *Jid = xmlnode_get_attrib(p->x, "from");
1072        char *type = xmlnode_get_attrib(p->x, "type");
1073
1074        g = xmlnode_new_tag("presence");
1075        xmlnode_put_attrib(g, "to", Jid);
1076
1077        if (!strcmp(type, "subscribe")) {
1078                /*
1079                 * A "subscribe to us" request was received - put up the approval dialog
1080                 */
1081                struct jabber_add_permit *jap = g_new0(struct jabber_add_permit, 1);
1082                gchar *msg = g_strdup_printf(_("The user %s wants to add you to his/her buddy list."),
1083                                Jid);
1084
1085                jap->gjc = gjc;
1086                jap->user = g_strdup(Jid);
1087                do_ask_dialog(GJ_GC(gjc), msg, jap, jabber_accept_add, jabber_deny_add);
1088
1089                g_free(msg);
1090                xmlnode_free(g);        /* Never needed it here anyway */
1091                return;
1092
1093        } else if (!strcmp(type, "unsubscribe")) {
1094                /*
1095                 * An "unsubscribe to us" was received - simply "approve" it
1096                 */
1097                xmlnode_put_attrib(g, "type", "unsubscribed");
1098        } else {
1099                /*
1100                 * Did we attempt to subscribe to somebody and they do not exist?
1101                 */
1102                if (!strcmp(type, "unsubscribed")) {
1103                        xmlnode y;
1104                        char *status;
1105                        if((y = xmlnode_get_tag(p->x, "status")) && (status = xmlnode_get_data(y)) &&
1106                                        !strcmp(status, "Not Found")) {
1107                                char *msg = g_strdup_printf("%s: \"%s\"", _("No such user"), 
1108                                        xmlnode_get_attrib(p->x, "from"));
1109                                do_error_dialog(GJ_GC(gjc), msg, _("Jabber Error"));
1110                                g_free(msg);
1111                        }
1112                }
1113
1114                xmlnode_free(g);
1115                return;
1116        }
1117
1118        gjab_send(gjc, g);
1119        xmlnode_free(g);
1120}
1121
1122/*
1123 * Pending subscription to a buddy?
1124 */
1125#define BUD_SUB_TO_PEND(sub, ask) ((!g_strcasecmp((sub), "none") || !g_strcasecmp((sub), "from")) && \
1126                                        (ask) != NULL && !g_strcasecmp((ask), "subscribe"))
1127
1128/*
1129 * Subscribed to a buddy?
1130 */
1131#define BUD_SUBD_TO(sub, ask) ((!g_strcasecmp((sub), "to") || !g_strcasecmp((sub), "both")) && \
1132                                        ((ask) == NULL || !g_strcasecmp((ask), "subscribe")))
1133
1134/*
1135 * Pending unsubscription to a buddy?
1136 */
1137#define BUD_USUB_TO_PEND(sub, ask) ((!g_strcasecmp((sub), "to") || !g_strcasecmp((sub), "both")) && \
1138                                        (ask) != NULL && !g_strcasecmp((ask), "unsubscribe"))
1139
1140/*
1141 * Unsubscribed to a buddy?
1142 */
1143#define BUD_USUBD_TO(sub, ask) ((!g_strcasecmp((sub), "none") || !g_strcasecmp((sub), "from")) && \
1144                                        ((ask) == NULL || !g_strcasecmp((ask), "unsubscribe")))
1145
1146/*
1147 * If a buddy is added or removed from the roster on another resource
1148 * jabber_handlebuddy is called
1149 *
1150 * Called with roster item node.
1151 */
1152static void jabber_handlebuddy(gjconn gjc, xmlnode x)
1153{
1154        xmlnode g;
1155        char *Jid, *name, *sub, *ask;
1156        jid who;
1157        struct buddy *b = NULL;
1158        char *buddyname, *groupname = NULL;
1159
1160        Jid = xmlnode_get_attrib(x, "jid");
1161        name = xmlnode_get_attrib(x, "name");
1162        sub = xmlnode_get_attrib(x, "subscription");
1163        ask = xmlnode_get_attrib(x, "ask");
1164        who = jid_new(gjc->p, Jid);
1165
1166        /* JFIXME: jabber_handleroster() had a "FIXME: transport" at this
1167         * equivilent point.  So...
1168         *
1169         * We haven't allocated any memory or done anything interesting to
1170         * this point, so we'll violate Good Coding Structure here by
1171         * simply bailing out.
1172         */
1173        if (!who || !who->user) {
1174                return;
1175        }
1176
1177        buddyname = g_strdup_printf("%s@%s", who->user, who->server);
1178
1179        if((g = xmlnode_get_tag(x, "group")) != NULL) {
1180                groupname = xmlnode_get_data(g);
1181        }
1182
1183        /*
1184         * Add or remove a buddy?  Change buddy's alias or group?
1185         */
1186        if (BUD_SUB_TO_PEND(sub, ask) || BUD_SUBD_TO(sub, ask)) {
1187                if ((b = find_buddy(GJ_GC(gjc), buddyname)) == NULL) {
1188                        add_buddy(GJ_GC(gjc), groupname ? groupname : _("Buddies"), buddyname,
1189                                name ? name : buddyname);
1190                } else {
1191                        /* struct group *c_grp = find_group_by_buddy(GJ_GC(gjc), buddyname); */
1192
1193                        /*
1194                         * If the buddy's in a new group or his/her alias is changed...
1195                         */
1196                        if(groupname) {
1197                                int present = b->present;       /* save presence state */
1198                                int uc = b->uc;                 /* and away state (?) */
1199                                int idle = b->idle;
1200                                int signon = b->signon;
1201
1202                                /*
1203                                 * seems rude, but it seems to be the only way...
1204                                 */
1205                                /* remove_buddy(GJ_GC(gjc), c_grp, b); */
1206                                jabber_remove_buddy(GJ_GC(gjc), b->name, JABBER_GROUP);
1207                               
1208                                add_buddy(GJ_GC(gjc), groupname, buddyname,
1209                                        name ? name : buddyname);
1210                                if(present) {
1211                                        serv_got_update(GJ_GC(gjc), buddyname, 1, 0, signon, idle, uc, 0);
1212                                }
1213                        } else if(name != NULL && strcmp(b->show, name)) {
1214                                strncpy(b->show, name, BUDDY_ALIAS_MAXLEN);
1215                                b->show[BUDDY_ALIAS_MAXLEN - 1] = '\0'; /* cheap safety feature */
1216                                serv_buddy_rename(GJ_GC(gjc), buddyname, b->show);
1217                        }
1218                }
1219        }  else if (BUD_USUB_TO_PEND(sub, ask) || BUD_USUBD_TO(sub, ask) || !g_strcasecmp(sub, "remove")) {
1220                jabber_remove_gaim_buddy(GJ_GC(gjc), buddyname);
1221        }
1222        g_free(buddyname);
1223
1224}
1225
1226static void jabber_handleroster(gjconn gjc, xmlnode querynode)
1227{
1228        xmlnode x;
1229
1230        x = xmlnode_get_firstchild(querynode);
1231        while (x) {
1232                jabber_handlebuddy(gjc, x);
1233                x = xmlnode_get_nextsibling(x);
1234        }
1235
1236        x = jutil_presnew(0, NULL, "Online");
1237        gjab_send(gjc, x);
1238        xmlnode_free(x);
1239}
1240
1241static void jabber_handleauthresp(gjconn gjc, jpacket p)
1242{
1243        if (jpacket_subtype(p) == JPACKET__RESULT) {
1244                if (xmlnode_has_children(p->x)) {
1245                        xmlnode query = xmlnode_get_tag(p->x, "query");
1246                        set_login_progress(GJ_GC(gjc), 4, _("Authenticating"));
1247                        if (!xmlnode_get_tag(query, "digest")) {
1248                                g_free(gjc->sid);
1249                                gjc->sid = NULL;
1250                        }
1251                        gjab_auth(gjc);
1252                } else {
1253                        account_online(GJ_GC(gjc));
1254
1255                        if (bud_list_cache_exists(GJ_GC(gjc)))
1256                                do_import(GJ_GC(gjc), NULL);
1257
1258                        ((struct jabber_data *)GJ_GC(gjc)->proto_data)->did_import = TRUE;
1259
1260                        gjab_reqroster(gjc);
1261                }
1262        } else {
1263                xmlnode xerr;
1264                char *errmsg = NULL;
1265                int errcode = 0;
1266                struct jabber_data *jd = GJ_GC(gjc)->proto_data;
1267
1268                xerr = xmlnode_get_tag(p->x, "error");
1269                if (xerr) {
1270                        char msg[BUF_LONG];
1271                        errmsg = xmlnode_get_data(xerr);
1272                        if (xmlnode_get_attrib(xerr, "code")) {
1273                                errcode = atoi(xmlnode_get_attrib(xerr, "code"));
1274                                g_snprintf(msg, sizeof(msg), "Error %d: %s", errcode, errmsg ? errmsg : "Unknown error");
1275                        } else
1276                                g_snprintf(msg, sizeof(msg), "%s", errmsg);
1277                        hide_login_progress(GJ_GC(gjc), msg);
1278                } else {
1279                        hide_login_progress(GJ_GC(gjc), _("Unknown login error"));
1280                }
1281
1282                jd->die = TRUE;
1283        }
1284}
1285
1286static void jabber_handleversion(gjconn gjc, xmlnode iqnode) {
1287        xmlnode querynode, x;
1288        char *id, *from;
1289        char os[1024];
1290#ifndef _WIN32
1291        struct utsname osinfo;
1292
1293        uname(&osinfo);
1294        g_snprintf(os, sizeof os, "%s %s %s", osinfo.sysname, osinfo.release, osinfo.machine);
1295#else
1296        g_snprintf(os, sizeof os, "Windows %d %d", _winmajor, _winminor);
1297#endif
1298
1299
1300        id = xmlnode_get_attrib(iqnode, "id");
1301        from = xmlnode_get_attrib(iqnode, "from");
1302
1303        x = jutil_iqnew(JPACKET__RESULT, NS_VERSION);
1304
1305        xmlnode_put_attrib(x, "to", from);
1306        xmlnode_put_attrib(x, "id", id);
1307        querynode = xmlnode_get_tag(x, "query");
1308        xmlnode_insert_cdata(xmlnode_insert_tag(querynode, "name"), PACKAGE, -1);
1309        xmlnode_insert_cdata(xmlnode_insert_tag(querynode, "version"), BITLBEE_VERSION, -1);
1310        xmlnode_insert_cdata(xmlnode_insert_tag(querynode, "os"), os, -1);
1311
1312        gjab_send(gjc, x);
1313
1314        xmlnode_free(x);
1315}
1316
1317static void jabber_handletime(gjconn gjc, xmlnode iqnode) {
1318        xmlnode querynode, x;
1319        char *id, *from;
1320        time_t now_t; 
1321        struct tm *now;
1322        char buf[1024];
1323
1324        time(&now_t);
1325        now = localtime(&now_t);
1326
1327        id = xmlnode_get_attrib(iqnode, "id");
1328        from = xmlnode_get_attrib(iqnode, "from");
1329
1330        x = jutil_iqnew(JPACKET__RESULT, NS_TIME);
1331
1332        xmlnode_put_attrib(x, "to", from);
1333        xmlnode_put_attrib(x, "id", id);
1334        querynode = xmlnode_get_tag(x, "query");
1335
1336        strftime(buf, 1024, "%Y%m%dT%T", now);
1337        xmlnode_insert_cdata(xmlnode_insert_tag(querynode, "utc"), buf, -1);
1338        strftime(buf, 1024, "%Z", now);
1339        xmlnode_insert_cdata(xmlnode_insert_tag(querynode, "tz"), buf, -1);
1340        strftime(buf, 1024, "%d %b %Y %T", now);
1341        xmlnode_insert_cdata(xmlnode_insert_tag(querynode, "display"), buf, -1);
1342       
1343        gjab_send(gjc, x);
1344
1345        xmlnode_free(x);
1346}
1347
1348static void jabber_handlelast(gjconn gjc, xmlnode iqnode) {
1349        xmlnode x, querytag;
1350        char *id, *from;
1351        struct jabber_data *jd = GJ_GC(gjc)->proto_data;
1352        char idle_time[32];
1353       
1354        id = xmlnode_get_attrib(iqnode, "id");
1355        from = xmlnode_get_attrib(iqnode, "from");
1356
1357        x = jutil_iqnew(JPACKET__RESULT, "jabber:iq:last");
1358
1359        xmlnode_put_attrib(x, "to", from);
1360        xmlnode_put_attrib(x, "id", id);
1361        querytag = xmlnode_get_tag(x, "query");
1362        g_snprintf(idle_time, sizeof idle_time, "%ld", jd->idle ? time(NULL) - jd->idle : 0);
1363        xmlnode_put_attrib(querytag, "seconds", idle_time);
1364
1365        gjab_send(gjc, x);
1366        xmlnode_free(x);
1367}
1368
1369/*
1370 * delete == TRUE: delete found entry
1371 *
1372 * returns pointer to (local) copy of value if found, NULL otherwise
1373 *
1374 * Note: non-reentrant!  Local static storage re-used on subsequent calls.
1375 * If you're going to need to keep the returned value, make a copy!
1376 */
1377static gchar *jabber_track_queries(GHashTable *queries, gchar *key, gboolean delete)
1378{
1379        gpointer my_key, my_val;
1380        static gchar *ret_val = NULL;
1381
1382        if(ret_val != NULL) {
1383                g_free(ret_val);
1384                ret_val = NULL;
1385        }
1386
1387        /* self-protection */
1388        if(queries != NULL && key != NULL) {
1389                if(g_hash_table_lookup_extended(queries, key, &my_key, &my_val)) {
1390                        ret_val = g_strdup((gchar *) my_val);
1391                        if(delete) {
1392                                g_hash_table_remove(queries, key);
1393                                g_free(my_key);
1394                                g_free(my_val);
1395                        }
1396                }
1397        }
1398
1399        return(ret_val);
1400}
1401
1402static void jabber_handlepacket(gjconn gjc, jpacket p)
1403{
1404        char *id;
1405        switch (p->type) {
1406        case JPACKET_MESSAGE:
1407                jabber_handlemessage(gjc, p);
1408                break;
1409        case JPACKET_PRESENCE:
1410                jabber_handlepresence(gjc, p);
1411                break;
1412        case JPACKET_IQ:
1413                id = xmlnode_get_attrib(p->x, "id");
1414                if (id != NULL && !strcmp(id, IQID_AUTH)) {
1415                        jabber_handleauthresp(gjc, p);
1416                        break;
1417                }
1418
1419                if (jpacket_subtype(p) == JPACKET__SET) {
1420                        xmlnode querynode;
1421                        querynode = xmlnode_get_tag(p->x, "query");
1422                        if (NSCHECK(querynode, "jabber:iq:roster")) {
1423                                jabber_handlebuddy(gjc, xmlnode_get_firstchild(querynode));
1424                        }
1425                } else if (jpacket_subtype(p) == JPACKET__GET) {
1426                        xmlnode querynode;
1427                        querynode = xmlnode_get_tag(p->x, "query");
1428                        if (NSCHECK(querynode, NS_VERSION)) {
1429                                jabber_handleversion(gjc, p->x);
1430                        } else if (NSCHECK(querynode, NS_TIME)) {
1431                                jabber_handletime(gjc, p->x);
1432                        } else if (NSCHECK(querynode, "jabber:iq:last")) {
1433                                jabber_handlelast(gjc, p->x);
1434                        }
1435                } else if (jpacket_subtype(p) == JPACKET__RESULT) {
1436                        xmlnode querynode, vcard;
1437                        /* char *xmlns; */
1438                        char *from;
1439
1440                        /*
1441                         * TBD: ISTM maybe this part could use a serious re-work?
1442                         */
1443                        from = xmlnode_get_attrib(p->x, "from");
1444                        querynode = xmlnode_get_tag(p->x, "query");
1445                        vcard = xmlnode_get_tag(p->x, "vCard");
1446                        if (!vcard)
1447                                vcard = xmlnode_get_tag(p->x, "VCARD");
1448
1449                        if (NSCHECK(querynode, NS_ROSTER)) {
1450                                jabber_handleroster(gjc, querynode);
1451                        } else if (NSCHECK(querynode, NS_VCARD)) {
1452                                jabber_track_queries(gjc->queries, id, TRUE);   /* delete query track */
1453                                jabber_handlevcard(gjc, querynode, from);
1454                        } else if (vcard) {
1455                                jabber_track_queries(gjc->queries, id, TRUE);   /* delete query track */
1456                                jabber_handlevcard(gjc, vcard, from);
1457                        } else {
1458                                char *val;
1459
1460                                /* handle "null" query results */
1461                                if((val = jabber_track_queries(gjc->queries, id, TRUE)) != NULL) {
1462                                        if (!g_strncasecmp(val, "vcard", 5)) {
1463                                                jabber_handlevcard(gjc, NULL, from);
1464                                        }
1465
1466                                        /* No-op */
1467                                }
1468                        }
1469
1470                } else if (jpacket_subtype(p) == JPACKET__ERROR) {
1471                        xmlnode xerr;
1472                        char *from, *errmsg = NULL;
1473                        int errcode = 0;
1474
1475                        from = xmlnode_get_attrib(p->x, "from");
1476                        xerr = xmlnode_get_tag(p->x, "error");
1477                        if (xerr) {
1478                                errmsg = xmlnode_get_data(xerr);
1479                                if (xmlnode_get_attrib(xerr, "code"))
1480                                        errcode = atoi(xmlnode_get_attrib(xerr, "code"));
1481                        }
1482
1483                        from = g_strdup_printf("Error %d (%s)", errcode, from);
1484                        do_error_dialog(GJ_GC(gjc), errmsg, from);
1485                        g_free(from);
1486
1487                }
1488
1489                break;
1490        case JPACKET_S10N:
1491                jabber_handles10n(gjc, p);
1492                break;
1493        }
1494
1495        xmlnode_free(p->x);
1496
1497        return;
1498}
1499
1500static void jabber_handlestate(gjconn gjc, int state)
1501{
1502        switch (state) {
1503        case JCONN_STATE_OFF:
1504                if(gjc->was_connected) {
1505                        hide_login_progress_error(GJ_GC(gjc), _("Connection lost"));
1506                } else {
1507                        hide_login_progress(GJ_GC(gjc), _("Unable to connect"));
1508                }
1509                signoff(GJ_GC(gjc));
1510                break;
1511        case JCONN_STATE_CONNECTED:
1512                gjc->was_connected = 1;
1513                set_login_progress(GJ_GC(gjc), 2, _("Connected"));
1514                break;
1515        case JCONN_STATE_ON:
1516                set_login_progress(GJ_GC(gjc), 3, _("Requesting Authentication Method"));
1517                gjab_reqauth(gjc);
1518                break;
1519        }
1520        return;
1521}
1522
1523static void jabber_login(struct aim_user *user)
1524{
1525        struct gaim_connection *gc = new_gaim_conn(user);
1526        struct jabber_data *jd = gc->proto_data = g_new0(struct jabber_data, 1);
1527        char *loginname = create_valid_jid(user->username, DEFAULT_SERVER, "BitlBee");
1528
1529        jd->hash = g_hash_table_new(g_str_hash, g_str_equal);
1530        jd->chats = NULL;       /* we have no chats yet */
1531
1532        set_login_progress(gc, 1, _("Connecting"));
1533
1534        if (!(jd->gjc = gjab_new(loginname, user->password, gc))) {
1535                g_free(loginname);
1536                hide_login_progress(gc, _("Unable to connect"));
1537                signoff(gc);
1538                return;
1539        }
1540
1541        g_free(loginname);
1542        gjab_state_handler(jd->gjc, jabber_handlestate);
1543        gjab_packet_handler(jd->gjc, jabber_handlepacket);
1544        jd->gjc->queries = g_hash_table_new(g_str_hash, g_str_equal);
1545        gjab_start(jd->gjc);
1546}
1547
1548static gboolean jabber_destroy_hash(gpointer key, gpointer val, gpointer data) {
1549        g_free(key);
1550        g_free(val);
1551        return TRUE;
1552}
1553
1554static gboolean jabber_free(gpointer data)
1555{
1556        struct jabber_data *jd = data;
1557
1558        if(jd->gjc != NULL) {
1559                gjab_delete(jd->gjc);
1560                g_free(jd->gjc->sid);
1561                jd->gjc = NULL;
1562        }
1563        g_free(jd);
1564
1565        return FALSE;
1566}
1567
1568static void jabber_close(struct gaim_connection *gc)
1569{
1570        struct jabber_data *jd = gc->proto_data;
1571
1572        if(jd) {
1573                GSList *jcs = jd->chats;
1574
1575                /* Free-up the jabber_chat struct allocs and the list */
1576                while (jcs) {
1577                        g_free(jcs->data);
1578                        jcs = jcs->next;
1579                }
1580                g_slist_free(jd->chats);
1581
1582                /* Free-up the away status memories and the list */
1583                if(jd->hash != NULL) {
1584                        g_hash_table_foreach_remove(jd->hash, jabber_destroy_hash, NULL);
1585                        g_hash_table_destroy(jd->hash);
1586                        jd->hash = NULL;
1587                }
1588
1589                /* Free-up the pending queries memories and the list */
1590                if(jd->gjc != NULL && jd->gjc->queries != NULL) {
1591                        g_hash_table_foreach_remove(jd->gjc->queries, jabber_destroy_hash, NULL);
1592                        g_hash_table_destroy(jd->gjc->queries);
1593                        jd->gjc->queries = NULL;
1594                }
1595        }
1596        if (gc->inpa)
1597                gaim_input_remove(gc->inpa);
1598
1599        if(jd) {
1600                g_timeout_add(50, jabber_free, jd);
1601                if(jd->gjc != NULL)
1602                        xmlnode_free(jd->gjc->current);
1603        }
1604        gc->proto_data = NULL;
1605}
1606
1607static int jabber_send_im(struct gaim_connection *gc, char *who, char *message, int len, int flags)
1608{
1609        xmlnode x, y;
1610        char *realwho;
1611        gjconn gjc = ((struct jabber_data *)gc->proto_data)->gjc;
1612
1613        if (!who || !message)
1614                return 0;
1615
1616        x = xmlnode_new_tag("message");
1617        /* Bare username and "username" not the server itself? */
1618        if (!strchr(who, '@') && strcmp(who, gjc->user->server) != 0)
1619                realwho = g_strdup_printf("%s@%s", who, gjc->user->server);
1620        else
1621                realwho = g_strdup(who);
1622        xmlnode_put_attrib(x, "to", realwho);
1623        g_free(realwho);
1624
1625        xmlnode_insert_tag(x, "bitlbee");
1626        xmlnode_put_attrib(x, "type", "chat");
1627
1628        if (message && strlen(message)) {
1629                y = xmlnode_insert_tag(x, "body");
1630                xmlnode_insert_cdata(y, message, -1);
1631        }
1632
1633        gjab_send(((struct jabber_data *)gc->proto_data)->gjc, x);
1634        xmlnode_free(x);
1635        return 1;
1636}
1637
1638/*
1639 * Add/update buddy's roster entry on server
1640 */
1641static void jabber_roster_update(struct gaim_connection *gc, char *name)
1642{
1643        xmlnode x, y;
1644        char *realwho;
1645        gjconn gjc;
1646        struct buddy *buddy = NULL;
1647        /* struct group *buddy_group = NULL; */
1648       
1649        if(gc && gc->proto_data && ((struct jabber_data *)gc->proto_data)->gjc && name) {
1650                gjc = ((struct jabber_data *)gc->proto_data)->gjc;
1651
1652                if (!strchr(name, '@'))
1653                        realwho = g_strdup_printf("%s@%s", name, gjc->user->server);
1654                else {
1655                        jid who = jid_new(gjc->p, name);
1656                        if (who->user == NULL) {
1657                                /* FIXME: transport */
1658                                return;
1659                        }
1660                        realwho = g_strdup_printf("%s@%s", who->user, who->server);
1661                }
1662
1663
1664                x = jutil_iqnew(JPACKET__SET, NS_ROSTER);
1665                y = xmlnode_insert_tag(xmlnode_get_tag(x, "query"), "item");
1666                xmlnode_put_attrib(y, "jid", realwho);
1667
1668
1669                /* If we can find the buddy, there's an alias for him, it's not 0-length
1670                 * and it doesn't match his JID, add the "name" attribute.
1671                 */
1672                if((buddy = find_buddy(gc, realwho)) != NULL &&
1673                        buddy->show != NULL && buddy->show[0] != '\0' && strcmp(realwho, buddy->show)) {
1674
1675                        xmlnode_put_attrib(y, "name", buddy->show);
1676                }
1677
1678                /*
1679                 * Find out what group the buddy's in and send that along
1680                 * with the roster item.
1681                 */
1682                /* ** Bitlbee disabled **
1683                if((buddy_group = NULL) != NULL) {
1684                        xmlnode z;
1685                        z = xmlnode_insert_tag(y, "group");
1686                        xmlnode_insert_cdata(z, buddy_group->name, -1);
1687                }
1688                ** End - Bitlbee ** */
1689
1690                gjab_send(((struct jabber_data *)gc->proto_data)->gjc, x);
1691
1692                xmlnode_free(x);
1693                g_free(realwho);
1694        }
1695}
1696
1697/*
1698 * Change buddy's group on server roster
1699 */
1700static void jabber_group_change(struct gaim_connection *gc, char *name, char *old_group, char *new_group)
1701{
1702        if(strcmp(old_group, new_group)) {
1703                jabber_roster_update(gc, name);
1704        }
1705}
1706
1707static void jabber_add_buddy(struct gaim_connection *gc, char *name)
1708{
1709        xmlnode x;
1710        char *realwho;
1711        gjconn gjc = ((struct jabber_data *)gc->proto_data)->gjc;
1712
1713        if (!((struct jabber_data *)gc->proto_data)->did_import)
1714                return;
1715
1716        if (!name)
1717                return;
1718
1719        if (!strcmp(gc->username, name))
1720                return;
1721
1722        if (!strchr(name, '@'))
1723                realwho = g_strdup_printf("%s@%s", name, gjc->user->server);
1724        else {
1725                jid who;
1726               
1727                if((who = jid_new(gjc->p, name)) == NULL) {
1728                        char *msg = g_strdup_printf("%s: \"%s\"", _("Invalid Jabber I.D."), name);
1729                        do_error_dialog(GJ_GC(gjc), msg, _("Jabber Error"));
1730                        g_free(msg);
1731                        jabber_remove_gaim_buddy(gc, name);
1732                        return;
1733                }
1734                if (who->user == NULL) {
1735                        /* FIXME: transport */
1736                        return;
1737                }
1738                realwho = g_strdup_printf("%s@%s", who->user, who->server);
1739        }
1740
1741        x = xmlnode_new_tag("presence");
1742        xmlnode_put_attrib(x, "to", realwho);
1743        xmlnode_put_attrib(x, "type", "subscribe");
1744        gjab_send(((struct jabber_data *)gc->proto_data)->gjc, x);
1745        xmlnode_free(x);
1746
1747        jabber_roster_update(gc, realwho);
1748
1749        g_free(realwho);
1750}
1751
1752static void jabber_remove_buddy(struct gaim_connection *gc, char *name, char *group)
1753{
1754        xmlnode x;
1755        char *realwho;
1756        gjconn gjc = ((struct jabber_data *)gc->proto_data)->gjc;
1757
1758        if (!name)
1759                return;
1760
1761        if (!strchr(name, '@'))
1762                realwho = g_strdup_printf("%s@%s", name, gjc->user->server);
1763        else
1764                realwho = g_strdup(name);
1765
1766        x = xmlnode_new_tag("presence");
1767        xmlnode_put_attrib(x, "to", realwho);
1768        xmlnode_put_attrib(x, "type", "unsubscribe");
1769        gjab_send(((struct jabber_data *)gc->proto_data)->gjc, x);
1770        g_free(realwho);
1771        xmlnode_free(x);
1772}
1773
1774static void jabber_get_info(struct gaim_connection *gc, char *who) {
1775        xmlnode x;
1776        char *id;
1777        char *realwho;
1778        struct jabber_data *jd = gc->proto_data;
1779        gjconn gjc = jd->gjc;
1780
1781        x = jutil_iqnew(JPACKET__GET, NS_VCARD);
1782        /* Bare username? */
1783        if (!strchr(who, '@')) {
1784                realwho = g_strdup_printf("%s@%s", who, gjc->user->server);
1785        } else {
1786                realwho = g_strdup(who);
1787        }
1788        xmlnode_put_attrib(x, "to", realwho);
1789        g_free(realwho);
1790
1791        id = gjab_getid(gjc);
1792        xmlnode_put_attrib(x, "id", id);
1793
1794        g_hash_table_insert(jd->gjc->queries, g_strdup(id), g_strdup("vCard"));
1795
1796        gjab_send(gjc, x);
1797
1798        xmlnode_free(x);
1799       
1800}
1801
1802static void jabber_get_away_msg(struct gaim_connection *gc, char *who) {
1803        struct jabber_data *jd = gc->proto_data;
1804        gjconn gjc = jd->gjc;
1805        char *status;
1806
1807        /* space for all elements: Jabber I.D. + "status" + NULL (list terminator) */
1808        gchar **str_arr = (gchar **) g_new(gpointer, 3);
1809        gchar **ap = str_arr;
1810        gchar *realwho, *final;
1811
1812        /* Bare username? */
1813        if (!strchr(who, '@')) {
1814                realwho = g_strdup_printf("%s@%s", who, gjc->user->server);
1815        } else {
1816                realwho = g_strdup(who);
1817        }
1818        *ap++ = g_strdup_printf("<B>Jabber ID:</B> %s<BR>\n", realwho);
1819
1820        if((status = g_hash_table_lookup(jd->hash, realwho)) == NULL) {
1821                status = _("Unknown");
1822        }
1823        *ap++ = g_strdup_printf("<B>Status:</B> %s<BR>\n", status);
1824
1825        *ap = NULL;
1826
1827        final= g_strjoinv(NULL, str_arr);
1828        g_strfreev(str_arr);
1829
1830        g_free(realwho);
1831        g_free(final);
1832       
1833}
1834
1835static GList *jabber_away_states(struct gaim_connection *gc) {
1836        GList *m = NULL;
1837
1838        m = g_list_append(m, "Online");
1839        m = g_list_append(m, "Chatty");
1840        m = g_list_append(m, "Away");
1841        m = g_list_append(m, "Extended Away");
1842        m = g_list_append(m, "Do Not Disturb");
1843
1844        return m;
1845}
1846
1847static void jabber_set_away(struct gaim_connection *gc, char *state, char *message)
1848{
1849        xmlnode x, y;
1850        struct jabber_data *jd = gc->proto_data;
1851        gjconn gjc = jd->gjc;
1852
1853        gc->away = NULL; /* never send an auto-response */
1854
1855        x = xmlnode_new_tag("presence");
1856
1857        if (!strcmp(state, GAIM_AWAY_CUSTOM)) {
1858                /* oh goody. Gaim is telling us what to do. */
1859                if (message) {
1860                        /* Gaim wants us to be away */
1861                        y = xmlnode_insert_tag(x, "show");
1862                        xmlnode_insert_cdata(y, "away", -1);
1863                        y = xmlnode_insert_tag(x, "status");
1864                        {
1865                                char *utf8 = str_to_utf8(message);
1866                                xmlnode_insert_cdata(y, utf8, -1);
1867                                g_free(utf8);
1868                        }
1869                        gc->away = "";
1870                } else {
1871                        /* Gaim wants us to not be away */
1872                        /* but for Jabber, we can just send presence with no other information. */
1873                }
1874        } else {
1875                /* state is one of our own strings. it won't be NULL. */
1876                if (!g_strcasecmp(state, "Online")) {
1877                        /* once again, we don't have to put anything here */
1878                } else if (!g_strcasecmp(state, "Chatty")) {
1879                        y = xmlnode_insert_tag(x, "show");
1880                        xmlnode_insert_cdata(y, "chat", -1);
1881                } else if (!g_strcasecmp(state, "Away")) {
1882                        y = xmlnode_insert_tag(x, "show");
1883                        xmlnode_insert_cdata(y, "away", -1);
1884                        gc->away = "";
1885                } else if (!g_strcasecmp(state, "Extended Away")) {
1886                        y = xmlnode_insert_tag(x, "show");
1887                        xmlnode_insert_cdata(y, "xa", -1);
1888                        gc->away = "";
1889                } else if (!g_strcasecmp(state, "Do Not Disturb")) {
1890                        y = xmlnode_insert_tag(x, "show");
1891                        xmlnode_insert_cdata(y, "dnd", -1);
1892                        gc->away = "";
1893                }
1894        }
1895
1896        gjab_send(gjc, x);
1897        xmlnode_free(x);
1898}
1899
1900static void jabber_set_idle(struct gaim_connection *gc, int idle) {
1901        struct jabber_data *jd = (struct jabber_data *)gc->proto_data;
1902        jd->idle = idle ? time(NULL) - idle : idle;
1903}
1904
1905static void jabber_keepalive(struct gaim_connection *gc) {
1906        struct jabber_data *jd = (struct jabber_data *)gc->proto_data;
1907        gjab_send_raw(jd->gjc, \t  ");
1908}
1909
1910static void jabber_buddy_free(struct buddy *b)
1911{
1912        while (b->proto_data) {
1913                g_free(((GSList *)b->proto_data)->data);
1914                b->proto_data = g_slist_remove(b->proto_data, ((GSList *)b->proto_data)->data);
1915        }
1916}
1917
1918/*---------------------------------------*/
1919/* Jabber "set info" (vCard) support     */
1920/*---------------------------------------*/
1921
1922/*
1923 * V-Card format:
1924 *
1925 *  <vCard prodid='' version='' xmlns=''>
1926 *    <FN></FN>
1927 *    <N>
1928 *      <FAMILY/>
1929 *      <GIVEN/>
1930 *    </N>
1931 *    <NICKNAME/>
1932 *    <URL/>
1933 *    <ADR>
1934 *      <STREET/>
1935 *      <EXTADD/>
1936 *      <LOCALITY/>
1937 *      <REGION/>
1938 *      <PCODE/>
1939 *      <COUNTRY/>
1940 *    </ADR>
1941 *    <TEL/>
1942 *    <EMAIL/>
1943 *    <ORG>
1944 *      <ORGNAME/>
1945 *      <ORGUNIT/>
1946 *    </ORG>
1947 *    <TITLE/>
1948 *    <ROLE/>
1949 *    <DESC/>
1950 *    <BDAY/>
1951 *  </vCard>
1952 *
1953 * See also:
1954 *
1955 *      http://docs.jabber.org/proto/html/vcard-temp.html
1956 *      http://www.vcard-xml.org/dtd/vCard-XML-v2-20010520.dtd
1957 */
1958
1959/*
1960 * Cross-reference user-friendly V-Card entry labels to vCard XML tags
1961 * and attributes.
1962 *
1963 * Order is (or should be) unimportant.  For example: we have no way of
1964 * knowing in what order real data will arrive.
1965 *
1966 * Format: Label, Pre-set text, "visible" flag, "editable" flag, XML tag
1967 *         name, XML tag's parent tag "path" (relative to vCard node).
1968 *
1969 *         List is terminated by a NULL label pointer.
1970 *
1971 *         Entries with no label text, but with XML tag and parent tag
1972 *         entries, are used by V-Card XML construction routines to
1973 *         "automagically" construct the appropriate XML node tree.
1974 *
1975 * Thoughts on future direction/expansion
1976 *
1977 *      This is a "simple" vCard.
1978 *
1979 *      It is possible for nodes other than the "vCard" node to have
1980 *      attributes.  Should that prove necessary/desirable, add an
1981 *      "attributes" pointer to the vcard_template struct, create the
1982 *      necessary tag_attr structs, and add 'em to the vcard_dflt_data
1983 *      array.
1984 *
1985 *      The above changes will (obviously) require changes to the vCard
1986 *      construction routines.
1987 */
1988
1989static struct vcard_template {
1990        char *label;                    /* label text pointer */
1991        char *text;                     /* entry text pointer */
1992        int  visible;                   /* should entry field be "visible?" */
1993        int  editable;                  /* should entry field be editable? */
1994        char *tag;                      /* tag text */
1995        char *ptag;                     /* parent tag "path" text */
1996        char *url;                      /* vCard display format if URL */
1997} vcard_template_data[] = {
1998        {N_("Full Name"),          NULL, TRUE, TRUE, "FN",        NULL,  NULL},
1999        {N_("Family Name"),        NULL, TRUE, TRUE, "FAMILY",    "N",   NULL},
2000        {N_("Given Name"),         NULL, TRUE, TRUE, "GIVEN",     "N",   NULL},
2001        {N_("Nickname"),           NULL, TRUE, TRUE, "NICKNAME",  NULL,  NULL},
2002        {N_("URL"),                NULL, TRUE, TRUE, "URL",       NULL,  "<A HREF=\"%s\">%s</A>"},
2003        {N_("Street Address"),     NULL, TRUE, TRUE, "STREET",    "ADR", NULL},
2004        {N_("Extended Address"),   NULL, TRUE, TRUE, "EXTADD",    "ADR", NULL},
2005        {N_("Locality"),           NULL, TRUE, TRUE, "LOCALITY",  "ADR", NULL},
2006        {N_("Region"),             NULL, TRUE, TRUE, "REGION",    "ADR", NULL},
2007        {N_("Postal Code"),        NULL, TRUE, TRUE, "PCODE",     "ADR", NULL},
2008        {N_("Country"),            NULL, TRUE, TRUE, "COUNTRY",   "ADR", NULL},
2009        {N_("Telephone"),          NULL, TRUE, TRUE, "TELEPHONE", NULL,  NULL},
2010        {N_("Email"),              NULL, TRUE, TRUE, "EMAIL",     NULL,  "<A HREF=\"mailto:%s\">%s</A>"},
2011        {N_("Organization Name"),  NULL, TRUE, TRUE, "ORGNAME",   "ORG", NULL},
2012        {N_("Organization Unit"),  NULL, TRUE, TRUE, "ORGUNIT",   "ORG", NULL},
2013        {N_("Title"),              NULL, TRUE, TRUE, "TITLE",     NULL,  NULL},
2014        {N_("Role"),               NULL, TRUE, TRUE, "ROLE",      NULL,  NULL},
2015        {N_("Birthday"),           NULL, TRUE, TRUE, "BDAY",      NULL,  NULL},
2016        {N_("Description"),        NULL, TRUE, TRUE, "DESC",      NULL,  NULL},
2017        {"", NULL, TRUE, TRUE, "N",     NULL, NULL},
2018        {"", NULL, TRUE, TRUE, "ADR",   NULL, NULL},
2019        {"", NULL, TRUE, TRUE, "ORG",   NULL, NULL},
2020        {NULL, NULL, 0, 0, NULL, NULL, NULL}
2021};
2022
2023/*
2024 * Used by routines to parse an XML-encoded string into an xmlnode tree
2025 */
2026typedef struct {
2027        XML_Parser parser;
2028        xmlnode current;
2029} *xmlstr2xmlnode_parser, xmlstr2xmlnode_parser_struct;
2030
2031
2032/*
2033 * Used by XML_Parse on parsing CDATA
2034 */
2035static void xmlstr2xmlnode_charData(void *userdata, const char *s, int slen)
2036{
2037        xmlstr2xmlnode_parser xmlp = (xmlstr2xmlnode_parser) userdata;
2038
2039        if (xmlp->current)
2040                xmlnode_insert_cdata(xmlp->current, s, slen);
2041}
2042
2043/*
2044 * Used by XML_Parse to start or append to an xmlnode
2045 */
2046static void xmlstr2xmlnode_startElement(void *userdata, const char *name, const char **attribs)
2047{
2048        xmlnode x;
2049        xmlstr2xmlnode_parser xmlp = (xmlstr2xmlnode_parser) userdata;
2050
2051        if (xmlp->current) {
2052                /* Append the node to the current one */
2053                x = xmlnode_insert_tag(xmlp->current, name);
2054                xmlnode_put_expat_attribs(x, attribs);
2055
2056                xmlp->current = x;
2057        } else {
2058                x = xmlnode_new_tag(name);
2059                xmlnode_put_expat_attribs(x, attribs);
2060                xmlp->current = x;
2061        }
2062}
2063
2064/*
2065 * Used by XML_Parse to end an xmlnode
2066 */
2067static void xmlstr2xmlnode_endElement(void *userdata, const char *name)
2068{
2069        xmlstr2xmlnode_parser xmlp = (xmlstr2xmlnode_parser) userdata;
2070        xmlnode x;
2071
2072        if (xmlp->current != NULL && (x = xmlnode_get_parent(xmlp->current)) != NULL) {
2073                xmlp->current = x;
2074        }
2075}
2076
2077/*
2078 * Parse an XML-encoded string into an xmlnode tree
2079 *
2080 * Caller is responsible for freeing the returned xmlnode
2081 */
2082static xmlnode xmlstr2xmlnode(char *xmlstring)
2083{
2084        xmlstr2xmlnode_parser my_parser = g_new(xmlstr2xmlnode_parser_struct, 1);
2085        xmlnode x = NULL;
2086
2087        my_parser->parser = XML_ParserCreate(NULL);
2088        my_parser->current = NULL;
2089
2090        XML_SetUserData(my_parser->parser, (void *)my_parser);
2091        XML_SetElementHandler(my_parser->parser, xmlstr2xmlnode_startElement, xmlstr2xmlnode_endElement);
2092        XML_SetCharacterDataHandler(my_parser->parser, xmlstr2xmlnode_charData);
2093        XML_Parse(my_parser->parser, xmlstring, strlen(xmlstring), 0);
2094
2095        x = my_parser->current;
2096
2097        XML_ParserFree(my_parser->parser);
2098        g_free(my_parser);
2099
2100        return(x);
2101}
2102
2103/*
2104 * Insert a tag node into an xmlnode tree, recursively inserting parent tag
2105 * nodes as necessary
2106 *
2107 * Returns pointer to inserted node
2108 *
2109 * Note to hackers: this code is designed to be re-entrant (it's recursive--it
2110 * calls itself), so don't put any "static"s in here!
2111 */
2112static xmlnode insert_tag_to_parent_tag(xmlnode start, const char *parent_tag, const char *new_tag)
2113{
2114        xmlnode x = NULL;
2115
2116        /*
2117         * If the parent tag wasn't specified, see if we can get it
2118         * from the vCard template struct.
2119         */
2120        if(parent_tag == NULL) {
2121                struct vcard_template *vc_tp = vcard_template_data;
2122
2123                while(vc_tp->label != NULL) {
2124                        if(strcmp(vc_tp->tag, new_tag) == 0) {
2125                                parent_tag = vc_tp->ptag;
2126                                break;
2127                        }
2128                        ++vc_tp;
2129                }
2130        }
2131
2132        /*
2133         * If we have a parent tag...
2134         */
2135        if(parent_tag != NULL ) {
2136                /*
2137                 * Try to get the parent node for a tag
2138                 */
2139                if((x = xmlnode_get_tag(start, parent_tag)) == NULL) {
2140                        /*
2141                         * Descend?
2142                         */
2143                        char *grand_parent = strcpy(g_malloc(strlen(parent_tag) + 1), parent_tag);
2144                        char *parent;
2145
2146                        if((parent = strrchr(grand_parent, '/')) != NULL) {
2147                                *(parent++) = '\0';
2148                                x = insert_tag_to_parent_tag(start, grand_parent, parent);
2149                        } else {
2150                                x = xmlnode_insert_tag(start, grand_parent);
2151                        }
2152                        g_free(grand_parent);
2153                } else {
2154                        /*
2155                         * We found *something* to be the parent node.
2156                         * Note: may be the "root" node!
2157                         */
2158                        xmlnode y;
2159                        if((y = xmlnode_get_tag(x, new_tag)) != NULL) {
2160                                return(y);
2161                        }
2162                }
2163        }
2164
2165        /*
2166         * insert the new tag into its parent node
2167         */
2168        return(xmlnode_insert_tag((x == NULL? start : x), new_tag));
2169}
2170
2171/*
2172 * Send vCard info to Jabber server
2173 */
2174static void jabber_set_info(struct gaim_connection *gc, char *info)
2175{
2176        xmlnode x, vc_node;
2177        char *id;
2178        struct jabber_data *jd = gc->proto_data;
2179        gjconn gjc = jd->gjc;
2180
2181        x = xmlnode_new_tag("iq");
2182        xmlnode_put_attrib(x,"type","set");
2183
2184        id = gjab_getid(gjc);
2185       
2186        xmlnode_put_attrib(x, "id", id);
2187
2188        /*
2189         * Send only if there's actually any *information* to send
2190         */
2191        if((vc_node = xmlstr2xmlnode(info)) != NULL && xmlnode_get_name(vc_node) != NULL &&
2192                        g_strncasecmp(xmlnode_get_name(vc_node), "vcard", 5) == 0) {
2193                xmlnode_insert_tag_node(x, vc_node);
2194                gjab_send(gjc, x);
2195        }
2196
2197        xmlnode_free(x);
2198}
2199
2200/*
2201 * displays a Jabber vCard
2202 */
2203static void jabber_handlevcard(gjconn gjc, xmlnode querynode, char *from)
2204{
2205        struct jabber_data *jd = GJ_GC(gjc)->proto_data;
2206        jid who = jid_new(gjc->p, from);
2207        char *status = NULL, *text = NULL;
2208        GString *str = g_string_sized_new(100);
2209        xmlnode child;
2210
2211        gchar *buddy = NULL;
2212       
2213        if(querynode == NULL) {
2214                serv_got_crap(GJ_GC(gjc), "%s - Received empty info reply from %s", _("User Info"), from);
2215                return;
2216        }
2217
2218        if(who->resource != NULL && (who->resource)[0] != '\0') {
2219                buddy = g_strdup_printf("%s@%s/%s", who->user, who->server, who->resource);
2220        } else {
2221                buddy = g_strdup_printf("%s@%s", who->user, who->server);
2222        }
2223
2224        if((status = g_hash_table_lookup(jd->hash, buddy)) == NULL) {
2225                status = _("Unknown");
2226        }
2227
2228        g_string_sprintfa(str, "%s: %s - %s: %s", _("Jabber ID"), buddy, _("Status"),
2229                               status);
2230
2231        for(child = querynode->firstchild; child; child = child->next)
2232        {
2233                xmlnode child2;
2234
2235                if(child->type != NTYPE_TAG)
2236                        continue;
2237
2238                text = xmlnode_get_data(child);
2239                if(text && !strcmp(child->name, "FN")) {
2240                        info_string_append(str, "\n", _("Full Name"), text);
2241                } else if (!strcmp(child->name, "N")) {
2242                        for (child2 = child->firstchild; child2; child2 = child2->next) {
2243                                char *text2 = NULL;
2244
2245                                if (child2->type != NTYPE_TAG)
2246                                        continue;
2247
2248                                text2 = xmlnode_get_data(child2);
2249                                if (text2 && !strcmp(child2->name, "FAMILY")) {
2250                                        info_string_append(str, "\n", _("Family Name"), text2);
2251                                } else if (text2 && !strcmp(child2->name, "GIVEN")) {
2252                                        info_string_append(str, "\n", _("Given Name"), text2);
2253                                } else if (text2 && !strcmp(child2->name, "MIDDLE")) {
2254                                        info_string_append(str, "\n", _("Middle Name"), text2);
2255                                }
2256                        }
2257                } else if (text && !strcmp(child->name, "NICKNAME")) {
2258                        info_string_append(str, "\n", _("Nickname"), text);
2259                } else if (text && !strcmp(child->name, "BDAY")) {
2260                        info_string_append(str, "\n", _("Birthday"), text);
2261                } else if (!strcmp(child->name, "ADR")) {
2262                        /* show wich address it is */
2263                        /* Just for the beauty of bitlbee
2264                        if (child->firstchild)
2265                                g_string_sprintfa(str, "%s:\n", _("Address"));
2266                        */
2267                        for(child2 = child->firstchild; child2; child2 = child2->next) {
2268                                char *text2 = NULL;
2269
2270                                if(child2->type != NTYPE_TAG)
2271                                        continue;
2272
2273                                text2 = xmlnode_get_data(child2);
2274                                if(text2 && !strcmp(child2->name, "POBOX")) {
2275                                        info_string_append(str, "\n",
2276                                                        _("P.O. Box"), text2);
2277                                } else if(text2 && !strcmp(child2->name, "EXTADR")) {
2278                                        info_string_append(str, "\n",
2279                                                        _("Extended Address"), text2);
2280                                } else if(text2 && !strcmp(child2->name, "STREET")) {
2281                                        info_string_append(str, "\n",
2282                                                        _("Street Address"), text2);
2283                                } else if(text2 && !strcmp(child2->name, "LOCALITY")) {
2284                                        info_string_append(str, "\n",
2285                                                        _("Locality"), text2);
2286                                } else if(text2 && !strcmp(child2->name, "REGION")) {
2287                                        info_string_append(str, "\n",
2288                                                        _("Region"), text2);
2289                                } else if(text2 && !strcmp(child2->name, "PCODE")) {
2290                                        info_string_append(str, "\n",
2291                                                        _("Postal Code"), text2);
2292                                } else if(text2 && (!strcmp(child2->name, "CTRY")
2293                                                        || !strcmp(child2->name, "COUNTRY"))) {
2294                                        info_string_append(str, "\n", _("Country"), text2);
2295                                }
2296                        }
2297                } else if(!strcmp(child->name, "TEL")) {
2298                        char *number = NULL;
2299                        if ((child2 = xmlnode_get_tag(child, "NUMBER"))) {
2300                                /* show what kind of number it is */
2301                                number = xmlnode_get_data(child2);
2302                                if(number) {
2303                                        info_string_append(str, "\n", _("Telephone"), number);
2304                                }
2305                        } else if((number = xmlnode_get_data(child))) {
2306                                /* lots of clients (including gaim) do this,
2307                                 * but it's out of spec */
2308                                info_string_append(str, "\n", _("Telephone"), number);
2309                        }
2310                } else if(!strcmp(child->name, "EMAIL")) {
2311                        char *userid = NULL;
2312                        if((child2 = xmlnode_get_tag(child, "USERID"))) {
2313                                /* show what kind of email it is */
2314                                userid = xmlnode_get_data(child2);
2315                                if(userid) {
2316                                        info_string_append(str, "\n", _("Email"), userid);
2317                                }
2318                        } else if((userid = xmlnode_get_data(child))) {
2319                                /* lots of clients (including gaim) do this,
2320                                 * but it's out of spec */
2321                                info_string_append(str, "\n", _("Email"), userid);
2322                        }
2323                } else if(!strcmp(child->name, "ORG")) {
2324                        for(child2 = child->firstchild; child2; child2 = child2->next) {
2325                                char *text2 = NULL;
2326
2327                                if(child2->type != NTYPE_TAG)
2328                                        continue;
2329
2330                                text2 = xmlnode_get_data(child2);
2331                                if(text2 && !strcmp(child2->name, "ORGNAME")) {
2332                                        info_string_append(str, "\n", _("Organization Name"), text2);
2333                                } else if(text2 && !strcmp(child2->name, "ORGUNIT")) {
2334                                        info_string_append(str, "\n", _("Organization Unit"), text2);
2335                                }
2336                        }
2337                } else if(text && !strcmp(child->name, "TITLE")) {
2338                        info_string_append(str, "\n", _("Title"), text);
2339                } else if(text && !strcmp(child->name, "ROLE")) {
2340                        info_string_append(str, "\n", _("Role"), text);
2341                } else if(text && !strcmp(child->name, "DESC")) {
2342                        g_string_sprintfa(str, "\n%s:\n%s\n%s", _("Description"), 
2343                                        text, _("End of Description"));
2344                }
2345        }
2346
2347        serv_got_crap(GJ_GC(gjc), "%s\n%s", _("User Info"), str->str);
2348
2349        g_free(buddy);
2350        g_string_free(str, TRUE);
2351}
2352
2353
2354static GList *jabber_actions()
2355{
2356        GList *m = NULL;
2357
2358        m = g_list_append(m, _("Set User Info"));
2359        /*
2360        m = g_list_append(m, _("Set Dir Info"));
2361        m = g_list_append(m, _("Change Password"));
2362         */
2363
2364        return m;
2365}
2366
2367static struct prpl *my_protocol = NULL;
2368
2369void jabber_init(struct prpl *ret)
2370{
2371        /* the NULL's aren't required but they're nice to have */
2372        ret->protocol = PROTO_JABBER;
2373        ret->name = jabber_name;
2374        ret->away_states = jabber_away_states;
2375        ret->actions = jabber_actions;
2376        ret->login = jabber_login;
2377        ret->close = jabber_close;
2378        ret->send_im = jabber_send_im;
2379        ret->set_info = jabber_set_info;
2380        ret->get_info = jabber_get_info;
2381        ret->set_away = jabber_set_away;
2382        ret->get_away = jabber_get_away_msg;
2383        ret->set_idle = jabber_set_idle;
2384        ret->add_buddy = jabber_add_buddy;
2385        ret->remove_buddy = jabber_remove_buddy;
2386        ret->add_permit = NULL;
2387        ret->add_deny = NULL;
2388        ret->rem_permit = NULL;
2389        ret->rem_deny = NULL;
2390        ret->set_permit_deny = NULL;
2391        ret->keepalive = jabber_keepalive;
2392        ret->buddy_free = jabber_buddy_free;
2393        ret->alias_buddy = jabber_roster_update;
2394        ret->group_buddy = jabber_group_change;
2395        ret->cmp_buddynames = g_strcasecmp;
2396
2397        my_protocol = ret;
2398}
Note: See TracBrowser for help on using the repository browser.