/* * libyahoo2: libyahoo2.c * * Some code copyright (C) 2002-2004, Philip S Tellis * YMSG16 code copyright (C) 2009, * Siddhesh Poyarekar * * Yahoo Search copyright (C) 2003, Konstantin Klyagin * * Much of this code was taken and adapted from the yahoo module for * gaim released under the GNU GPL. This code is also released under the * GNU GPL. * * This code is derivitive of Gaim * copyright (C) 1998-1999, Mark Spencer * 1998-1999, Adam Fritzler * 1998-2002, Rob Flynn * 2000-2002, Eric Warmenhoven * 2001-2002, Brian Macke * 2001, Anand Biligiri S * 2001, Valdis Kletnieks * 2002, Sean Egan * 2002, Toby Gray * * This library also uses code from other libraries, namely: * Portions from libfaim copyright 1998, 1999 Adam Fritzler * * Portions of Sylpheed copyright 2000-2002 Hiroyuki Yamamoto * * * YMSG16 authentication code based mostly on write-up at: * http://www.carbonize.co.uk/ymsg16.html * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #ifndef _WIN32 #include #endif #include #include #include #if STDC_HEADERS # include #else # if !HAVE_STRCHR # define strchr index # define strrchr rindex # endif char *strchr (), *strrchr (); # if !HAVE_MEMCPY # define memcpy(d, s, n) bcopy ((s), (d), (n)) # define memmove(d, s, n) bcopy ((s), (d), (n)) # endif #endif #include #ifdef __MINGW32__ # include #endif #include #include #include "sha1.h" #include "md5.h" #include "yahoo2.h" #include "yahoo_httplib.h" #include "yahoo_util.h" #include "yahoo_fn.h" #include "yahoo2_callbacks.h" #include "yahoo_debug.h" #if defined(__MINGW32__) && !defined(HAVE_GLIB) #define snprintf _snprintf #define vsnprintf _vsnprintf #endif #include "base64.h" #include "http_client.h" #ifdef USE_STRUCT_CALLBACKS struct yahoo_callbacks *yc = NULL; void yahoo_register_callbacks(struct yahoo_callbacks *tyc) { yc = tyc; } #define YAHOO_CALLBACK(x) yc->x #else #define YAHOO_CALLBACK(x) x #endif static int yahoo_send_data(void *fd, void *data, int len); static void _yahoo_http_connected(int id, void *fd, int error, void *data); static void yahoo_connected(void *fd, int error, void *data); int yahoo_log_message(char *fmt, ...) { char out[1024]; va_list ap; va_start(ap, fmt); vsnprintf(out, sizeof(out), fmt, ap); va_end(ap); return YAHOO_CALLBACK(ext_yahoo_log) ("%s", out); } int yahoo_connect(char *host, int port) { return YAHOO_CALLBACK(ext_yahoo_connect) (host, port); } static enum yahoo_log_level log_level = YAHOO_LOG_NONE; enum yahoo_log_level yahoo_get_log_level() { return log_level; } int yahoo_set_log_level(enum yahoo_log_level level) { enum yahoo_log_level l = log_level; log_level = level; return l; } /* default values for servers */ static char *default_pager_hosts[] = { "scs.msg.yahoo.com", "scsa.msg.yahoo.com", "scsb.msg.yahoo.com", "scsc.msg.yahoo.com", NULL}; static int pager_port = 5050; static int fallback_ports[] = { 23, 25, 80, 20, 119, 8001, 8002, 5050, 0 }; static char filetransfer_host[] = "filetransfer.msg.yahoo.com"; static int filetransfer_port = 80; static char webcam_host[] = "webcam.yahoo.com"; static int webcam_port = 5100; static char webcam_description[] = ""; static char local_host[] = ""; static int conn_type = Y_WCM_DSL; static char profile_url[] = "http://profiles.yahoo.com/"; struct connect_callback_data { struct yahoo_data *yd; int tag; int i; int server_i; }; struct yahoo_pair { int key; char *value; }; struct yahoo_packet { unsigned short int service; unsigned int status; unsigned int id; YList *hash; }; struct yahoo_search_state { int lsearch_type; char *lsearch_text; int lsearch_gender; int lsearch_agerange; int lsearch_photo; int lsearch_yahoo_only; int lsearch_nstart; int lsearch_nfound; int lsearch_ntotal; }; struct data_queue { unsigned char *queue; int len; }; struct yahoo_input_data { struct yahoo_data *yd; struct yahoo_webcam *wcm; struct yahoo_webcam_data *wcd; struct yahoo_search_state *ys; void *fd; enum yahoo_connection_type type; unsigned char *rxqueue; int rxlen; int read_tag; YList *txqueues; int write_tag; }; struct yahoo_server_settings { char *pager_host; int pager_port; char *filetransfer_host; int filetransfer_port; char *webcam_host; int webcam_port; char *webcam_description; char *local_host; int conn_type; char **pager_host_list; }; static void yahoo_process_ft_connection(struct yahoo_input_data *yid, int over); static void yahoo_process_filetransfer(struct yahoo_input_data *yid, struct yahoo_packet *pkt); static void yahoo_process_filetransferinfo(struct yahoo_input_data *yid, struct yahoo_packet *pkt); static void yahoo_process_filetransferaccept(struct yahoo_input_data *yid, struct yahoo_packet *pkt); static void yahoo_https_auth(struct yahoo_input_data *yid, const char *seed, const char *sn); static void *_yahoo_default_server_settings() { struct yahoo_server_settings *yss = y_new0(struct yahoo_server_settings, 1); /* Give preference to the default host list * Make sure that only one of the two is set at any time */ yss->pager_host = NULL; yss->pager_host_list = default_pager_hosts; yss->pager_port = pager_port; yss->filetransfer_host = strdup(filetransfer_host); yss->filetransfer_port = filetransfer_port; yss->webcam_host = strdup(webcam_host); yss->webcam_port = webcam_port; yss->webcam_description = strdup(webcam_description); yss->local_host = strdup(local_host); yss->conn_type = conn_type; return yss; } static void *_yahoo_assign_server_settings(va_list ap) { struct yahoo_server_settings *yss = _yahoo_default_server_settings(); char *key; char *svalue; int nvalue; char **pvalue; while (1) { key = va_arg(ap, char *); if (key == NULL) break; if (!strcmp(key, "pager_host")) { svalue = va_arg(ap, char *); free(yss->pager_host); yss->pager_host = strdup(svalue); yss->pager_host_list = NULL; } else if (!strcmp(key, "pager_host_list")) { pvalue = va_arg(ap, char **); yss->pager_host_list = pvalue; free(yss->pager_host); yss->pager_host = NULL; } else if (!strcmp(key, "pager_port")) { nvalue = va_arg(ap, int); yss->pager_port = nvalue; } else if (!strcmp(key, "filetransfer_host")) { svalue = va_arg(ap, char *); free(yss->filetransfer_host); yss->filetransfer_host = strdup(svalue); } else if (!strcmp(key, "filetransfer_port")) { nvalue = va_arg(ap, int); yss->filetransfer_port = nvalue; } else if (!strcmp(key, "webcam_host")) { svalue = va_arg(ap, char *); free(yss->webcam_host); yss->webcam_host = strdup(svalue); } else if (!strcmp(key, "webcam_port")) { nvalue = va_arg(ap, int); yss->webcam_port = nvalue; } else if (!strcmp(key, "webcam_description")) { svalue = va_arg(ap, char *); free(yss->webcam_description); yss->webcam_description = strdup(svalue); } else if (!strcmp(key, "local_host")) { svalue = va_arg(ap, char *); free(yss->local_host); yss->local_host = strdup(svalue); } else if (!strcmp(key, "conn_type")) { nvalue = va_arg(ap, int); yss->conn_type = nvalue; } else { WARNING(("Unknown key passed to yahoo_init, " "perhaps you didn't terminate the list " "with NULL")); } } return yss; } static void yahoo_free_server_settings(struct yahoo_server_settings *yss) { if (!yss) return; free(yss->pager_host); free(yss->filetransfer_host); free(yss->webcam_host); free(yss->webcam_description); free(yss->local_host); free(yss); } static YList *conns = NULL; static YList *inputs = NULL; static int last_id = 0; static void add_to_list(struct yahoo_data *yd) { conns = y_list_prepend(conns, yd); } static struct yahoo_data *find_conn_by_id(int id) { YList *l; for (l = conns; l; l = y_list_next(l)) { struct yahoo_data *yd = l->data; if (yd->client_id == id) return yd; } return NULL; } static void del_from_list(struct yahoo_data *yd) { conns = y_list_remove(conns, yd); } /* call repeatedly to get the next one */ /* static struct yahoo_input_data * find_input_by_id(int id) { YList *l; for(l = inputs; l; l = y_list_next(l)) { struct yahoo_input_data *yid = l->data; if(yid->yd->client_id == id) return yid; } return NULL; } */ static struct yahoo_input_data *find_input_by_id_and_webcam_user(int id, const char *who) { YList *l; LOG(("find_input_by_id_and_webcam_user")); for (l = inputs; l; l = y_list_next(l)) { struct yahoo_input_data *yid = l->data; if (yid->type == YAHOO_CONNECTION_WEBCAM && yid->yd->client_id == id && yid->wcm && ((who && yid->wcm->user && !strcmp(who, yid->wcm->user)) || !(yid->wcm->user && !who))) return yid; } return NULL; } static struct yahoo_input_data *find_input_by_id_and_type(int id, enum yahoo_connection_type type) { YList *l; LOG(("find_input_by_id_and_type")); for (l = inputs; l; l = y_list_next(l)) { struct yahoo_input_data *yid = l->data; if (yid->type == type && yid->yd->client_id == id) return yid; } return NULL; } static struct yahoo_input_data *find_input_by_id_and_fd(int id, void *fd) { YList *l; LOG(("find_input_by_id_and_fd")); for (l = inputs; l; l = y_list_next(l)) { struct yahoo_input_data *yid = l->data; if (yid->fd == fd && yid->yd->client_id == id) return yid; } return NULL; } static int count_inputs_with_id(int id) { int c = 0; YList *l; LOG(("counting %d", id)); for (l = inputs; l; l = y_list_next(l)) { struct yahoo_input_data *yid = l->data; if (yid->yd->client_id == id) c++; } LOG(("%d", c)); return c; } extern char *yahoo_crypt(char *, char *); /* Free a buddy list */ static void yahoo_free_buddies(YList *list) { YList *l; for (l = list; l; l = l->next) { struct yahoo_buddy *bud = l->data; if (!bud) continue; FREE(bud->group); FREE(bud->id); FREE(bud->real_name); if (bud->yab_entry) { FREE(bud->yab_entry->fname); FREE(bud->yab_entry->lname); FREE(bud->yab_entry->nname); FREE(bud->yab_entry->id); FREE(bud->yab_entry->email); FREE(bud->yab_entry->hphone); FREE(bud->yab_entry->wphone); FREE(bud->yab_entry->mphone); FREE(bud->yab_entry); } FREE(bud); l->data = bud = NULL; } y_list_free(list); } /* Free an identities list */ static void yahoo_free_identities(YList *list) { while (list) { YList *n = list; FREE(list->data); list = y_list_remove_link(list, list); y_list_free_1(n); } } /* Free webcam data */ static void yahoo_free_webcam(struct yahoo_webcam *wcm) { if (wcm) { FREE(wcm->user); FREE(wcm->server); FREE(wcm->key); FREE(wcm->description); FREE(wcm->my_ip); } FREE(wcm); } static void yahoo_free_data(struct yahoo_data *yd) { FREE(yd->user); FREE(yd->password); FREE(yd->cookie_y); FREE(yd->cookie_t); FREE(yd->cookie_b); FREE(yd->cookie_c); FREE(yd->login_cookie); FREE(yd->login_id); yahoo_free_buddies(yd->buddies); yahoo_free_buddies(yd->ignore); yahoo_free_identities(yd->identities); yahoo_free_server_settings(yd->server_settings); FREE(yd); } #define YAHOO_PACKET_HDRLEN (4 + 2 + 2 + 2 + 2 + 4 + 4) static struct yahoo_packet *yahoo_packet_new(enum yahoo_service service, enum ypacket_status status, int id) { struct yahoo_packet *pkt = y_new0(struct yahoo_packet, 1); pkt->service = service; pkt->status = status; pkt->id = id; return pkt; } static void yahoo_packet_hash(struct yahoo_packet *pkt, int key, const char *value) { struct yahoo_pair *pair = y_new0(struct yahoo_pair, 1); pair->key = key; pair->value = strdup(value); pkt->hash = y_list_append(pkt->hash, pair); } static int yahoo_packet_length(struct yahoo_packet *pkt) { YList *l; int len = 0; for (l = pkt->hash; l; l = l->next) { struct yahoo_pair *pair = l->data; int tmp = pair->key; do { tmp /= 10; len++; } while (tmp); len += 2; len += strlen(pair->value); len += 2; } return len; } #define yahoo_put16(buf, data) ( \ (*(buf) = (unsigned char)((data)>>8)&0xff), \ (*((buf)+1) = (unsigned char)(data)&0xff), \ 2) #define yahoo_get16(buf) ((((*(buf))&0xff)<<8) + ((*((buf)+1)) & 0xff)) #define yahoo_put32(buf, data) ( \ (*((buf)) = (unsigned char)((data)>>24)&0xff), \ (*((buf)+1) = (unsigned char)((data)>>16)&0xff), \ (*((buf)+2) = (unsigned char)((data)>>8)&0xff), \ (*((buf)+3) = (unsigned char)(data)&0xff), \ 4) #define yahoo_get32(buf) ((((*(buf) )&0xff)<<24) + \ (((*((buf)+1))&0xff)<<16) + \ (((*((buf)+2))&0xff)<< 8) + \ (((*((buf)+3))&0xff))) static void yahoo_packet_read(struct yahoo_packet *pkt, unsigned char *data, int len) { int pos = 0; while (pos + 1 < len) { char *key, *value = NULL; int accept; int x; struct yahoo_pair *pair = y_new0(struct yahoo_pair, 1); key = malloc(len + 1); x = 0; while (pos + 1 < len) { if (data[pos] == 0xc0 && data[pos + 1] == 0x80) break; key[x++] = data[pos++]; } key[x] = 0; pos += 2; pair->key = strtol(key, NULL, 10); free(key); /* Libyahoo2 developer(s) don't seem to have the time to fix this problem, so for now try to work around it: Sometimes we receive an invalid packet with not any more data at this point. I don't know how to handle this in a clean way, but let's hope this is clean enough: */ if (pos + 1 < len) { accept = x; /* if x is 0 there was no key, so don't accept it */ if (accept) value = malloc(len - pos + 1); x = 0; while (pos + 1 < len) { if (data[pos] == 0xc0 && data[pos + 1] == 0x80) break; if (accept) value[x++] = data[pos++]; } if (accept) value[x] = 0; pos += 2; } else { accept = 0; } if (accept) { pair->value = strdup(value); FREE(value); pkt->hash = y_list_append(pkt->hash, pair); DEBUG_MSG(("Key: %d \tValue: %s", pair->key, pair->value)); } else { FREE(pair); } } } static void yahoo_packet_write(struct yahoo_packet *pkt, unsigned char *data) { YList *l; int pos = 0; for (l = pkt->hash; l; l = l->next) { struct yahoo_pair *pair = l->data; unsigned char buf[100]; snprintf((char *)buf, sizeof(buf), "%d", pair->key); strcpy((char *)data + pos, (char *)buf); pos += strlen((char *)buf); data[pos++] = 0xc0; data[pos++] = 0x80; strcpy((char *)data + pos, pair->value); pos += strlen(pair->value); data[pos++] = 0xc0; data[pos++] = 0x80; } } static void yahoo_dump_unhandled(struct yahoo_packet *pkt) { YList *l; NOTICE(("Service: 0x%02x\tStatus: %d", pkt->service, pkt->status)); for (l = pkt->hash; l; l = l->next) { struct yahoo_pair *pair = l->data; NOTICE(("\t%d => %s", pair->key, pair->value)); } } static void yahoo_packet_dump(unsigned char *data, int len) { if (yahoo_get_log_level() >= YAHOO_LOG_DEBUG) { int i; for (i = 0; i < len; i++) { if ((i % 8 == 0) && i) YAHOO_CALLBACK(ext_yahoo_log) (" "); if ((i % 16 == 0) && i) YAHOO_CALLBACK(ext_yahoo_log) ("\n"); YAHOO_CALLBACK(ext_yahoo_log) ("%02x ", data[i]); } YAHOO_CALLBACK(ext_yahoo_log) ("\n"); for (i = 0; i < len; i++) { if ((i % 8 == 0) && i) YAHOO_CALLBACK(ext_yahoo_log) (" "); if ((i % 16 == 0) && i) YAHOO_CALLBACK(ext_yahoo_log) ("\n"); if (isprint(data[i])) YAHOO_CALLBACK(ext_yahoo_log) (" %c ", data[i]); else YAHOO_CALLBACK(ext_yahoo_log) (" . "); } YAHOO_CALLBACK(ext_yahoo_log) ("\n"); } } /* raw bytes in quasi-big-endian order to base 64 string (NUL-terminated) */ static void to_y64(unsigned char *out, const unsigned char *in, int inlen) { base64_encode_real(in, inlen, out, "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789._-"); } static void yahoo_add_to_send_queue(struct yahoo_input_data *yid, void *data, int length) { struct data_queue *tx = y_new0(struct data_queue, 1); tx->queue = y_new0(unsigned char, length); tx->len = length; memcpy(tx->queue, data, length); yid->txqueues = y_list_append(yid->txqueues, tx); if (!yid->write_tag) yid->write_tag = YAHOO_CALLBACK(ext_yahoo_add_handler) (yid->yd-> client_id, yid->fd, YAHOO_INPUT_WRITE, yid); } static void yahoo_send_packet(struct yahoo_input_data *yid, struct yahoo_packet *pkt, int extra_pad) { int pktlen = yahoo_packet_length(pkt); int len = YAHOO_PACKET_HDRLEN + pktlen; unsigned char *data; int pos = 0; if (yid->fd < 0) return; data = y_new0(unsigned char, len + 1); memcpy(data + pos, "YMSG", 4); pos += 4; pos += yahoo_put16(data + pos, YAHOO_PROTO_VER); /* version [latest 12 0x000c] */ pos += yahoo_put16(data + pos, 0x0000); /* HIWORD pkt length??? */ pos += yahoo_put16(data + pos, pktlen + extra_pad); /* LOWORD pkt length? */ pos += yahoo_put16(data + pos, pkt->service); /* service */ pos += yahoo_put32(data + pos, pkt->status); /* status [4bytes] */ pos += yahoo_put32(data + pos, pkt->id); /* session [4bytes] */ yahoo_packet_write(pkt, data + pos); yahoo_packet_dump(data, len); if (yid->type == YAHOO_CONNECTION_FT) yahoo_send_data(yid->fd, data, len); else yahoo_add_to_send_queue(yid, data, len); FREE(data); } static void yahoo_packet_free(struct yahoo_packet *pkt) { while (pkt->hash) { struct yahoo_pair *pair = pkt->hash->data; YList *tmp; FREE(pair->value); FREE(pair); tmp = pkt->hash; pkt->hash = y_list_remove_link(pkt->hash, pkt->hash); y_list_free_1(tmp); } FREE(pkt); } static int yahoo_send_data(void *fd, void *data, int len) { int ret; int e; if (fd == NULL) return -1; yahoo_packet_dump(data, len); do { ret = YAHOO_CALLBACK(ext_yahoo_write) (fd, data, len); } while (ret == -1 && errno == EINTR); e = errno; if (ret == -1) { LOG(("wrote data: ERR %s", strerror(errno))); } else { LOG(("wrote data: OK")); } errno = e; return ret; } void yahoo_close(int id) { struct yahoo_data *yd = find_conn_by_id(id); if (!yd) return; del_from_list(yd); yahoo_free_data(yd); if (id == last_id) last_id--; } static void yahoo_input_close(struct yahoo_input_data *yid) { inputs = y_list_remove(inputs, yid); LOG(("yahoo_input_close(read)")); YAHOO_CALLBACK(ext_yahoo_remove_handler) (yid->yd->client_id, yid->read_tag); LOG(("yahoo_input_close(write)")); YAHOO_CALLBACK(ext_yahoo_remove_handler) (yid->yd->client_id, yid->write_tag); yid->read_tag = yid->write_tag = 0; if (yid->fd) YAHOO_CALLBACK(ext_yahoo_close) (yid->fd); yid->fd = 0; FREE(yid->rxqueue); if (count_inputs_with_id(yid->yd->client_id) == 0) { LOG(("closing %d", yid->yd->client_id)); yahoo_close(yid->yd->client_id); } yahoo_free_webcam(yid->wcm); if (yid->wcd) FREE(yid->wcd); if (yid->ys) { FREE(yid->ys->lsearch_text); FREE(yid->ys); } FREE(yid); } static int is_same_bud(const void *a, const void *b) { const struct yahoo_buddy *subject = a; const struct yahoo_buddy *object = b; return strcmp(subject->id, object->id); } static char *getcookie(char *rawcookie) { char *cookie = NULL; char *tmpcookie; char *cookieend; if (strlen(rawcookie) < 2) return NULL; tmpcookie = strdup(rawcookie + 2); cookieend = strchr(tmpcookie, ';'); if (cookieend) *cookieend = '\0'; cookie = strdup(tmpcookie); FREE(tmpcookie); /* cookieend=NULL; not sure why this was there since the value is not preserved in the stack -dd */ return cookie; } static char *getlcookie(char *cookie) { char *tmp; char *tmpend; char *login_cookie = NULL; tmpend = strstr(cookie, "n="); if (tmpend) { tmp = strdup(tmpend + 2); tmpend = strchr(tmp, '&'); if (tmpend) *tmpend = '\0'; login_cookie = strdup(tmp); FREE(tmp); } return login_cookie; } static void yahoo_process_notify(struct yahoo_input_data *yid, struct yahoo_packet *pkt) { struct yahoo_data *yd = yid->yd; char *msg = NULL; char *from = NULL; char *to = NULL; int stat = 0; int accept = 0; char *ind = NULL; YList *l; for (l = pkt->hash; l; l = l->next) { struct yahoo_pair *pair = l->data; if (pair->key == 4) from = pair->value; if (pair->key == 5) to = pair->value; if (pair->key == 49) msg = pair->value; if (pair->key == 13) stat = atoi(pair->value); if (pair->key == 14) ind = pair->value; if (pair->key == 16) { /* status == -1 */ NOTICE((pair->value)); return; } } if (!msg) return; if (!strncasecmp(msg, "TYPING", strlen("TYPING"))) YAHOO_CALLBACK(ext_yahoo_typing_notify) (yd->client_id, to, from, stat); else if (!strncasecmp(msg, "GAME", strlen("GAME"))) YAHOO_CALLBACK(ext_yahoo_game_notify) (yd->client_id, to, from, stat, ind); else if (!strncasecmp(msg, "WEBCAMINVITE", strlen("WEBCAMINVITE"))) { if (!strcmp(ind, " ")) { YAHOO_CALLBACK(ext_yahoo_webcam_invite) (yd->client_id, to, from); } else { accept = atoi(ind); /* accept the invitation (-1 = deny 1 = accept) */ if (accept < 0) accept = 0; YAHOO_CALLBACK(ext_yahoo_webcam_invite_reply) (yd-> client_id, to, from, accept); } } else LOG(("Got unknown notification: %s", msg)); } static void yahoo_process_conference(struct yahoo_input_data *yid, struct yahoo_packet *pkt) { struct yahoo_data *yd = yid->yd; char *msg = NULL; char *host = NULL; char *who = NULL; char *room = NULL; char *id = NULL; int utf8 = 0; YList *members = NULL; YList *l; for (l = pkt->hash; l; l = l->next) { struct yahoo_pair *pair = l->data; if (pair->key == 50) host = pair->value; if (pair->key == 52) { /* invite */ members = y_list_append(members, strdup(pair->value)); } if (pair->key == 53) /* logon */ who = pair->value; if (pair->key == 54) /* decline */ who = pair->value; if (pair->key == 55) /* unavailable (status == 2) */ who = pair->value; if (pair->key == 56) /* logoff */ who = pair->value; if (pair->key == 57) room = pair->value; if (pair->key == 58) /* join message */ msg = pair->value; if (pair->key == 14) /* decline/conf message */ msg = pair->value; if (pair->key == 13) ; if (pair->key == 16) /* error */ msg = pair->value; if (pair->key == 1) /* my id */ id = pair->value; if (pair->key == 3) /* message sender */ who = pair->value; if (pair->key == 97) utf8 = atoi(pair->value); } if (!room) return; if (host) { for (l = members; l; l = l->next) { char *w = l->data; if (!strcmp(w, host)) break; } if (!l) members = y_list_append(members, strdup(host)); } /* invite, decline, join, left, message -> status == 1 */ switch (pkt->service) { case YAHOO_SERVICE_CONFINVITE: if (pkt->status == 2) ; else if (members) YAHOO_CALLBACK(ext_yahoo_got_conf_invite) (yd-> client_id, id, host, room, msg, members); else if (msg) YAHOO_CALLBACK(ext_yahoo_error) (yd->client_id, msg, 0, E_CONFNOTAVAIL); break; case YAHOO_SERVICE_CONFADDINVITE: if (pkt->status == 1) YAHOO_CALLBACK(ext_yahoo_got_conf_invite) (yd-> client_id, id, host, room, msg, members); break; case YAHOO_SERVICE_CONFDECLINE: if (who) YAHOO_CALLBACK(ext_yahoo_conf_userdecline) (yd-> client_id, id, who, room, msg); break; case YAHOO_SERVICE_CONFLOGON: if (who) YAHOO_CALLBACK(ext_yahoo_conf_userjoin) (yd->client_id, id, who, room); break; case YAHOO_SERVICE_CONFLOGOFF: if (who) YAHOO_CALLBACK(ext_yahoo_conf_userleave) (yd->client_id, id, who, room); break; case YAHOO_SERVICE_CONFMSG: if (who) YAHOO_CALLBACK(ext_yahoo_conf_message) (yd->client_id, id, who, room, msg, utf8); break; } } static void yahoo_process_chat(struct yahoo_input_data *yid, struct yahoo_packet *pkt) { char *msg = NULL; char *id = NULL; char *who = NULL; char *room = NULL; char *topic = NULL; YList *members = NULL; struct yahoo_chat_member *currentmember = NULL; int msgtype = 1; int utf8 = 0; int firstjoin = 0; int membercount = 0; int chaterr = 0; YList *l; yahoo_dump_unhandled(pkt); for (l = pkt->hash; l; l = l->next) { struct yahoo_pair *pair = l->data; if (pair->key == 1) { /* My identity */ id = pair->value; } if (pair->key == 104) { /* Room name */ room = pair->value; } if (pair->key == 105) { /* Room topic */ topic = pair->value; } if (pair->key == 108) { /* Number of members in this packet */ membercount = atoi(pair->value); } if (pair->key == 109) { /* message sender */ who = pair->value; if (pkt->service == YAHOO_SERVICE_CHATJOIN) { currentmember = y_new0(struct yahoo_chat_member, 1); currentmember->id = strdup(pair->value); members = y_list_append(members, currentmember); } } if (pair->key == 110) { /* age */ if (pkt->service == YAHOO_SERVICE_CHATJOIN) currentmember->age = atoi(pair->value); } if (pair->key == 113) { /* attribs */ if (pkt->service == YAHOO_SERVICE_CHATJOIN) currentmember->attribs = atoi(pair->value); } if (pair->key == 141) { /* alias */ if (pkt->service == YAHOO_SERVICE_CHATJOIN) currentmember->alias = strdup(pair->value); } if (pair->key == 142) { /* location */ if (pkt->service == YAHOO_SERVICE_CHATJOIN) currentmember->location = strdup(pair->value); } if (pair->key == 130) { /* first join */ firstjoin = 1; } if (pair->key == 117) { /* message */ msg = pair->value; } if (pair->key == 124) { /* Message type */ msgtype = atoi(pair->value); } if (pair->key == 114) { /* message error not sure what all the pair values mean */ /* but -1 means no session in room */ chaterr = atoi(pair->value); } } if (!room) { if (pkt->service == YAHOO_SERVICE_CHATLOGOUT) { /* yahoo originated chat logout */ YAHOO_CALLBACK(ext_yahoo_chat_yahoologout) (yid->yd-> client_id, id); return; } if (pkt->service == YAHOO_SERVICE_COMMENT && chaterr) { YAHOO_CALLBACK(ext_yahoo_chat_yahooerror) (yid->yd-> client_id, id); return; } WARNING(("We didn't get a room name, ignoring packet")); return; } switch (pkt->service) { case YAHOO_SERVICE_CHATJOIN: if (y_list_length(members) != membercount) { WARNING(("Count of members doesn't match No. of members we got")); } if (firstjoin && members) { YAHOO_CALLBACK(ext_yahoo_chat_join) (yid->yd->client_id, id, room, topic, members, yid->fd); } else if (who) { if (y_list_length(members) != 1) { WARNING(("Got more than 1 member on a normal join")); } /* this should only ever have one, but just in case */ while (members) { YList *n = members->next; currentmember = members->data; YAHOO_CALLBACK(ext_yahoo_chat_userjoin) (yid-> yd->client_id, id, room, currentmember); y_list_free_1(members); members = n; } } break; case YAHOO_SERVICE_CHATEXIT: if (who) { YAHOO_CALLBACK(ext_yahoo_chat_userleave) (yid->yd-> client_id, id, room, who); } break; case YAHOO_SERVICE_COMMENT: if (who) { YAHOO_CALLBACK(ext_yahoo_chat_message) (yid->yd-> client_id, id, who, room, msg, msgtype, utf8); } break; } } static void yahoo_process_message(struct yahoo_input_data *yid, struct yahoo_packet *pkt) { struct yahoo_data *yd = yid->yd; YList *l; YList *messages = NULL; struct m { int i_31; int i_32; char *to; char *from; long tm; char *msg; int utf8; char *gunk; } *message = y_new0(struct m, 1); for (l = pkt->hash; l; l = l->next) { struct yahoo_pair *pair = l->data; if (pair->key == 1 || pair->key == 4) { if (!message->from) message->from = pair->value; } else if (pair->key == 5) message->to = pair->value; else if (pair->key == 15) message->tm = strtol(pair->value, NULL, 10); else if (pair->key == 97) message->utf8 = atoi(pair->value); /* This comes when the official client sends us a message */ else if (pair->key == 429) message->gunk = pair->value; /* user message *//* sys message */ else if (pair->key == 14 || pair->key == 16) message->msg = pair->value; else if (pair->key == 31) { if (message->i_31) { messages = y_list_append(messages, message); message = y_new0(struct m, 1); } message->i_31 = atoi(pair->value); } else if (pair->key == 32) message->i_32 = atoi(pair->value); else LOG(("yahoo_process_message: status: %d, key: %d, value: %s", pkt->status, pair->key, pair->value)); } messages = y_list_append(messages, message); for (l = messages; l; l = l->next) { message = l->data; if (pkt->service == YAHOO_SERVICE_SYSMESSAGE) { YAHOO_CALLBACK(ext_yahoo_system_message) (yd->client_id, message->to, message->from, message->msg); } else if (pkt->status <= 2 || pkt->status == 5) { /* Confirm message receipt if we got the gunk */ if(message->gunk) { struct yahoo_packet *outpkt; outpkt = yahoo_packet_new(YAHOO_SERVICE_MESSAGE_CONFIRM, YPACKET_STATUS_DEFAU
/***************************************************************************\
*                                                                           *
*  BitlBee - An IRC to IM gateway                                           *
*  Jabber module - Misc. stuff                                              *
*                                                                           *
*  Copyright 2006-2010 Wilmer van der Gaast <wilmer@gaast.net>              
*                                                                           *
*  This program is free software; you can redistribute it and/or modify     *
*  it under the terms of the GNU General Public License as published by     *
*  the Free Software Foundation; either version 2 of the License, or        *
*  (at your option) any later version.                                      *
*                                                                           *
*  This program is distributed in the hope that it will be useful,          *
*  but WITHOUT ANY WARRANTY; without even the implied warranty of           *
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            *
*  GNU General Public License for more details.                             *
*                                                                           *
*  You should have received a copy of the GNU General Public License along  *
*  with this program; if not, write to the Free Software Foundation, Inc.,  *
*  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.              *
*                                                                           *
\***************************************************************************/

#include "jabber.h"
#include "md5.h"
#include "base64.h"

static unsigned int next_id = 1;

char *set_eval_priority( set_t *set, char *value )
{
	account_t *acc = set->data;
	int i;
	
	if( sscanf( value, "%d", &i ) == 1 )
	{
		/* Priority is a signed 8-bit integer, according to RFC 3921. */
		if( i < -128 || i > 127 )
			return SET_INVALID;
	}
	else
		return SET_INVALID;
	
	/* Only run this stuff if the account is online ATM,
	   and if the setting seems to be acceptable. */
	if( acc->ic )
	{
		/* Although set_eval functions usually are very nice and
		   convenient, they have one disadvantage: If I would just
		   call p_s_u() now to send the new prio setting, it would
		   send the old setting because the set->value gets changed
		   after the (this) eval returns a non-NULL value.
		   
		   So now I can choose between implementing post-set
		   functions next to evals, or just do this little hack: */
		
		g_free( set->value );
		set->value = g_strdup( value );
		
		/* (Yes, sorry, I prefer the hack. :-P) */
		
		presence_send_update( acc->ic );
	}
	
	return value;
}

char *set_eval_tls( set_t *set, char *value )
{
	if( g_strcasecmp( value, "try" ) == 0 )
		return value;
	else
		return set_eval_bool( set, value );
}

struct xt_node *jabber_make_packet( char *name, char *type, char *to, struct xt_node *children )
{
	struct xt_node *node;
	
	node = xt_new_node( name, NULL, children );
	
	if( type )
		xt_add_attr( node, "type", type );
	if( to )
		xt_add_attr( node, "to", to );
	
	/* IQ packets should always have an ID, so let's generate one. It
	   might get overwritten by jabber_cache_add() if this packet has
	   to be saved until we receive a response. Cached packets get
	   slightly different IDs so we can recognize them. */
	if( strcmp( name, "iq" ) == 0 )
	{
		char *id = g_strdup_printf( "%s%05x", JABBER_PACKET_ID, ( next_id++ ) & 0xfffff );
		xt_add_attr( node, "id", id );
		g_free( id );
	}
	
	return node;
}

struct xt_node *jabber_make_error_packet( struct xt_node *orig, char *err_cond, char *err_type, char *err_code )
{
	struct xt_node *node, *c;
	char *to;
	
	/* Create the "defined-condition" tag. */
	c = xt_new_node( err_cond, NULL, NULL );
	xt_add_attr( c, "xmlns", XMLNS_STANZA_ERROR );
	
	/* Put it in an <error> tag. */
	c = xt_new_node( "error", NULL, c );
	xt_add_attr( c, "type", err_type );
	
	/* Add the error code, if present */
	if (err_code)
		xt_add_attr( c, "code", err_code );
	
	/* To make the actual error packet, we copy the original packet and
	   add our <error>/type="error" tag. Including the original packet
	   is recommended, so let's just do it. */
	node = xt_dup( orig );
	xt_add_child( node, c );
	xt_add_attr( node, "type", "error" );
	
	/* Return to sender. */
	if( ( to = xt_find_attr( node, "from" ) ) )
	{
		xt_add_attr( node, "to", to );
		xt_remove_attr( node, "from" );
	}
		
	return node;
}

/* Cache a node/packet for later use. Mainly useful for IQ packets if you need
   them when you receive the response. Use this BEFORE sending the packet so
   it'll get a new id= tag, and do NOT free() the packet after sending it! */
void jabber_cache_add( struct im_connection *ic, struct xt_node *node, jabber_cache_event func )
{
	struct jabber_data *jd = ic->proto_data;
	struct jabber_cache_entry *entry = g_new0( struct jabber_cache_entry, 1 );
	md5_state_t id_hash;
	md5_byte_t id_sum[16];
	char *id, *asc_hash;
	
	next_id ++;
	
	id_hash = jd->cached_id_prefix;
	md5_append( &id_hash, (md5_byte_t*) &next_id, sizeof( next_id ) );
	md5_finish( &id_hash, id_sum );
	asc_hash = base64_encode( id_sum, 12 );
	
	id = g_strdup_printf( "%s%s", JABBER_CACHED_ID, asc_hash );
	xt_add_attr( node, "id", id );
	g_free( id );
	g_free( asc_hash );
	
	entry->node = node;
	entry->func = func;
	entry->saved_at = time( NULL );
	g_hash_table_insert( jd->node_cache, xt_find_attr( node, "id" ), entry );
}

void jabber_cache_entry_free( gpointer data )
{
	struct jabber_cache_entry *entry = data;
	
	xt_free_node( entry->node );
	g_free( entry );
}

gboolean jabber_cache_clean_entry( gpointer key, gpointer entry, gpointer nullpointer );

/* This one should be called from time to time (from keepalive, in this case)
   to make sure things don't stay in the node cache forever. By marking nodes
   during the first run and deleting marked nodes during a next run, every
   node should be available in the cache for at least a minute (assuming the
   function is indeed called every minute). */
void jabber_cache_clean( struct im_connection *ic )
{
	struct jabber_data *jd = ic->proto_data;
	time_t threshold = time( NULL ) - JABBER_CACHE_MAX_AGE;
	
	g_hash_table_foreach_remove( jd->node_cache, jabber_cache_clean_entry, &threshold );
}

gboolean jabber_cache_clean_entry( gpointer key, gpointer entry_, gpointer threshold_ )
{
	struct jabber_cache_entry *entry = entry_;
	time_t *threshold = threshold_;
	
	return entry->saved_at < *threshold;
}

xt_status jabber_cache_handle_packet( struct im_connection *ic, struct xt_node *node )
{
	struct jabber_data *jd = ic->proto_data;
	struct jabber_cache_entry *entry;
	char *s;
	
	if( ( s = xt_find_attr( node, "id" ) ) == NULL ||
	    strncmp( s, JABBER_CACHED_ID, strlen( JABBER_CACHED_ID ) ) != 0 )
	{
		/* Silently ignore it, without an ID (or a non-cache
		   ID) we don't know how to handle the packet and we
		   probably don't have to. */
		return XT_HANDLED;
	}
	
	entry = g_hash_table_lookup( jd->node_cache, s );
	
	if( entry == NULL )
	{
		/*
		There's no longer an easy way to see if we generated this
		one or someone else, and there's a ten-minute timeout anyway,
		so meh.
		
		imcb_log( ic, "Warning: Received %s-%s packet with unknown/expired ID %s!",
		              node->name, xt_find_attr( node, "type" ) ? : "(no type)", s );
		*/
	}
	else if( entry->func )
	{
		return entry->func( ic, node, entry->node );
	}
	
	return XT_HANDLED;
}

const struct jabber_away_state jabber_away_state_list[] =
{
	{ "away",  "Away" },
	{ "chat",  "Free for Chat" },   /* WTF actually uses this? */
	{ "dnd",   "Do not Disturb" },
	{ "xa",    "Extended Away" },
	{ "",      NULL }
};

const struct jabber_away_state *jabber_away_state_by_code( char *code )
{
	int i;
	
	if( code == NULL )
		return NULL;
	
	for( i = 0; jabber_away_state_list[i].full_name; i ++ )
		if( g_strcasecmp( jabber_away_state_list[i].code, code ) == 0 )
			return jabber_away_state_list + i;
	
	return NULL;
}

const struct jabber_away_state *jabber_away_state_by_name( char *name )
{
	int i;
	
	if( name == NULL )
		return NULL;
	
	for( i = 0; jabber_away_state_list[i].full_name; i ++ )
		if( g_strcasecmp( jabber_away_state_list[i].full_name, name ) == 0 )
			return jabber_away_state_list + i;
	
	return NULL;
}

struct jabber_buddy_ask_data
{
	struct im_connection *ic;
	char *handle;
	char *realname;
};

static void jabber_buddy_ask_yes( void *data )
{
	struct jabber_buddy_ask_data *bla = data;
	
	presence_send_request( bla->ic, bla->handle, "subscribed" );
	
	imcb_ask_add( bla->ic, bla->handle, NULL );
	
	g_free( bla->handle );
	g_free( bla );
}

static void jabber_buddy_ask_no( void *data )
{
	struct jabber_buddy_ask_data *bla = data;
	
	presence_send_request( bla->ic, bla->handle, "subscribed" );
	
	g_free( bla->handle );
	g_free( bla );
}

void jabber_buddy_ask( struct im_connection *ic, char *handle )
{
	struct jabber_buddy_ask_data *bla = g_new0( struct jabber_buddy_ask_data, 1 );
	char *buf;
	
	bla->ic = ic;
	bla->handle = g_strdup( handle );
	
	buf = g_strdup_printf( "The user %s wants to add you to his/her buddy list.", handle );
	imcb_ask( ic, buf, bla, jabber_buddy_ask_yes, jabber_buddy_ask_no );
	g_free( buf );
}

/* Returns a new string. Don't leak it! */
char *jabber_normalize( const char *orig )
{
	int len, i;
	char *new;
	
	len = strlen( orig );
	new = g_new( char, len + 1 );
	
	/* So it turns out the /resource part is case sensitive. Yeah, and
	   it's Unicode but feck Unicode. :-P So stop once we see a slash. */
	for( i = 0; i < len && orig[i] != '/' ; i ++ )
		new[i] = tolower( orig[i] );
	for( ; orig[i]; i ++ )
		new[i] = orig[i];
	
	new[i] = 0;
	return new;
}

/* Adds a buddy/resource to our list. Returns NULL if full_jid is not really a
   FULL jid or if we already have this buddy/resource. XXX: No, great, actually
   buddies from transports don't (usually) have resources. So we'll really have
   to deal with that properly. Set their ->resource property to NULL. Do *NOT*
   allow to mix this stuff, though... */
struct jabber_buddy *jabber_buddy_add( struct im_connection *ic, char *full_jid_ )
{
	struct jabber_data *jd = ic->proto_data;
	struct jabber_buddy *bud, *new, *bi;
	char *s, *full_jid;
	
	full_jid = jabber_normalize( full_jid_ );
	
	if( ( s = strchr( full_jid, '/' ) ) )
		*s = 0;
	
	new = g_new0( struct jabber_buddy, 1 );
	
	if( ( bud = g_hash_table_lookup( jd->buddies, full_jid ) ) )
	{
		/* The first entry is always a bare JID. If there are more, we
		   should ignore the first one here. */
		if( bud->next )
			bud = bud->next;
		
		/* If this is a transport buddy or whatever, it can't have more
		   than one instance, so this is always wrong: */
		if( s == NULL || bud->resource == NULL )
		{
			if( s ) *s = '/';
			g_free( new );
			g_free( full_jid );
			return NULL;
		}
		
		new->bare_jid = bud->bare_jid;
		
		/* We already have another resource for this buddy, add the
		   new one to the list. */
		for( bi = bud; bi; bi = bi->next )
		{
			/* Check for dupes. */
			if( strcmp( bi->resource, s + 1 ) == 0 )
			{
				*s = '/';
				g_free( new );
				g_free( full_jid );
				return NULL;
			}
			/* Append the new item to the list. */
			else if( bi->next == NULL )
			{
				bi->next = new;
				break;
			}
		}
	}
	else
	{
		new->full_jid = new->bare_jid = g_strdup( full_jid );
		g_hash_table_insert( jd->buddies, new->bare_jid, new );
		
		if( s )
		{
			new->next = g_new0( struct jabber_buddy, 1 );
			new->next->bare_jid = new->bare_jid;
			new = new->next;
		}
	}
	
	if( s )
	{
		*s = '/';
		new->full_jid = full_jid;
		new->resource = strchr( new->full_jid, '/' ) + 1;
	}
	else
	{
		/* Let's waste some more bytes of RAM instead of to make
		   memory management a total disaster here. And it saves
		   me one g_free() call in this function. :-P */
		new->full_jid = full_jid;
	}
	
	return new;
}

/* Finds a buddy from our structures. Can find both full- and bare JIDs. When
   asked for a bare JID, it uses the "resource_select" setting to see which
   resource to pick. */
struct jabber_buddy *jabber_buddy_by_jid( struct im_connection *ic, char *jid_, get_buddy_flags_t flags )
{
	struct jabber_data *jd = ic->proto_data;
	struct jabber_buddy *bud, *head;
	char *s, *jid;
	
	jid = jabber_normalize( jid_ );
	
	if( ( s = strchr( jid, '/' ) ) )
	{
		int bare_exists = 0;
		
		*s = 0;
		if( ( bud = g_hash_table_lookup( jd->buddies, jid ) ) )
		{
			bare_exists = 1;
			
			if( bud->next )
				bud = bud->next;
			
			/* Just return the first one for this bare JID. */
			if( flags & GET_BUDDY_FIRST )
			{
				*s = '/';
				g_free( jid );
				return bud;
			}
			
			/* Is this one of those no-resource buddies? */
			if( bud->resource == NULL )
			{
				*s = '/';
				g_free( jid );
				return NULL;
			}
			
			/* See if there's an exact match. */
			for( ; bud; bud = bud->next )
				if( strcmp( bud->resource, s + 1 ) == 0 )
					break;
		}
		
		if( bud == NULL && ( flags & GET_BUDDY_CREAT ) &&
		    ( bare_exists || bee_user_by_handle( ic->bee, ic, jid ) ) )
		{
			*s = '/';
			bud = jabber_buddy_add( ic, jid );
		}
		
		g_free( jid );
		return bud;
	}
	else
	{
		struct jabber_buddy *best_prio, *best_time;
		char *set;
		
		head = g_hash_table_lookup( jd->buddies, jid );
		bud = ( head && head->next ) ? head->next : head;
		
		g_free( jid );
		
		if( bud == NULL )
			/* No match. Create it now? */
			return ( ( flags & GET_BUDDY_CREAT ) &&
			         bee_user_by_handle( ic->bee, ic, jid_ ) ) ?
			           jabber_buddy_add( ic, jid_ ) : NULL;
		else if( bud->resource && ( flags & GET_BUDDY_EXACT ) )
			/* We want an exact match, so in thise case there shouldn't be a /resource. */
			return NULL;
		else if( bud->resource == NULL || bud->next == NULL )
			/* No need for selection if there's only one option. */
			return bud;
		else if( flags & GET_BUDDY_FIRST )
			/* Looks like the caller doesn't care about details. */
			return bud;
		else if( flags & GET_BUDDY_BARE )
			return head;
		
		best_prio = best_time = bud;
		for( ; bud; bud = bud->next )
		{
			if( bud->priority > best_prio->priority )
				best_prio = bud;
			if( bud->last_msg > best_time->last_msg )
				best_time = bud;
		}
		
		if( ( set = set_getstr( &ic->acc->set, "resource_select" ) ) == NULL )
			return NULL;
		else if( strcmp( set, "priority" ) == 0 )
			return best_prio;
		else if( flags & GET_BUDDY_BARE_OK ) /* && strcmp( set, "activity" ) == 0 */
		{
			if( best_time->