Fri Jul 3 20:35:35 2009

Asterisk developer's documentation


chan_gtalk.c

Go to the documentation of this file.
00001 /*
00002  * Asterisk -- An open source telephony toolkit.
00003  *
00004  * Copyright (C) 1999 - 2005, Digium, Inc.
00005  *
00006  * Matt O'Gorman <mogorman@digium.com>
00007  *
00008  * See http://www.asterisk.org for more information about
00009  * the Asterisk project. Please do not directly contact
00010  * any of the maintainers of this project for assistance;
00011  * the project provides a web site, mailing lists and IRC
00012  * channels for your use.
00013  *
00014  * This program is free software, distributed under the terms of
00015  * the GNU General Public License Version 2. See the LICENSE file
00016  * at the top of the source tree.
00017  */
00018 
00019 /*! \file
00020  *
00021  * \author Matt O'Gorman <mogorman@digium.com>
00022  *
00023  * \brief Gtalk Channel Driver, until google/libjingle works with jingle spec
00024  * 
00025  * \ingroup channel_drivers
00026  */
00027 
00028 /*** MODULEINFO
00029    <depend>iksemel</depend>
00030    <use>gnutls</use>
00031  ***/
00032 
00033 #include "asterisk.h"
00034 
00035 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
00036 
00037 #include <stdlib.h>
00038 #include <stdio.h>
00039 #include <string.h>
00040 #include <unistd.h>
00041 #include <sys/socket.h>
00042 #include <errno.h>
00043 #include <stdlib.h>
00044 #include <fcntl.h>
00045 #include <netdb.h>
00046 #include <netinet/in.h>
00047 #include <arpa/inet.h>
00048 #include <sys/signal.h>
00049 #include <iksemel.h>
00050 #include <pthread.h>
00051 
00052 #ifdef HAVE_GNUTLS
00053 #include <gcrypt.h>
00054 GCRY_THREAD_OPTION_PTHREAD_IMPL;
00055 #endif /* HAVE_GNUTLS */
00056 
00057 #include "asterisk/lock.h"
00058 #include "asterisk/channel.h"
00059 #include "asterisk/config.h"
00060 #include "asterisk/logger.h"
00061 #include "asterisk/module.h"
00062 #include "asterisk/pbx.h"
00063 #include "asterisk/options.h"
00064 #include "asterisk/lock.h"
00065 #include "asterisk/sched.h"
00066 #include "asterisk/io.h"
00067 #include "asterisk/rtp.h"
00068 #include "asterisk/acl.h"
00069 #include "asterisk/callerid.h"
00070 #include "asterisk/file.h"
00071 #include "asterisk/cli.h"
00072 #include "asterisk/app.h"
00073 #include "asterisk/musiconhold.h"
00074 #include "asterisk/manager.h"
00075 #include "asterisk/stringfields.h"
00076 #include "asterisk/utils.h"
00077 #include "asterisk/causes.h"
00078 #include "asterisk/astobj.h"
00079 #include "asterisk/abstract_jb.h"
00080 #include "asterisk/jabber.h"
00081 
00082 #define GOOGLE_CONFIG "gtalk.conf"
00083 
00084 #define GOOGLE_NS "http://www.google.com/session"
00085 
00086 
00087 /*! Global jitterbuffer configuration - by default, jb is disabled */
00088 static struct ast_jb_conf default_jbconf =
00089 {
00090    .flags = 0,
00091    .max_size = -1,
00092    .resync_threshold = -1,
00093    .impl = ""
00094 };
00095 static struct ast_jb_conf global_jbconf;
00096 
00097 enum gtalk_protocol {
00098    AJI_PROTOCOL_UDP = 1,
00099    AJI_PROTOCOL_SSLTCP = 2,
00100 };
00101 
00102 enum gtalk_connect_type {
00103    AJI_CONNECT_STUN = 1,
00104    AJI_CONNECT_LOCAL = 2,
00105    AJI_CONNECT_RELAY = 3,
00106 };
00107 
00108 struct gtalk_pvt {
00109    ast_mutex_t lock;                /*!< Channel private lock */
00110    time_t laststun;
00111    struct gtalk *parent;            /*!< Parent client */
00112    char sid[100];
00113    char us[AJI_MAX_JIDLEN];
00114    char them[AJI_MAX_JIDLEN];
00115    char ring[10];                   /*!< Message ID of ring */
00116    iksrule *ringrule;               /*!< Rule for matching RING request */
00117    int initiator;                   /*!< If we're the initiator */
00118    int alreadygone;
00119    int capability;
00120    struct ast_codec_pref prefs;
00121    struct gtalk_candidate *theircandidates;
00122    struct gtalk_candidate *ourcandidates;
00123    char cid_num[80];                /*!< Caller ID num */
00124    char cid_name[80];               /*!< Caller ID name */
00125    char exten[80];                  /*!< Called extension */
00126    struct ast_channel *owner;       /*!< Master Channel */
00127    struct ast_rtp *rtp;             /*!< RTP audio session */
00128    struct ast_rtp *vrtp;            /*!< RTP video session */
00129    int jointcapability;             /*!< Supported capability at both ends (codecs ) */
00130    int peercapability;
00131    struct gtalk_pvt *next; /* Next entity */
00132 };
00133 
00134 struct gtalk_candidate {
00135    char name[100];
00136    enum gtalk_protocol protocol;
00137    double preference;
00138    char username[100];
00139    char password[100];
00140    enum gtalk_connect_type type;
00141    char network[6];
00142    int generation;
00143    char ip[16];
00144    int port;
00145    int receipt;
00146    struct gtalk_candidate *next;
00147 };
00148 
00149 struct gtalk {
00150    ASTOBJ_COMPONENTS(struct gtalk);
00151    struct aji_client *connection;
00152    struct aji_buddy *buddy;
00153    struct gtalk_pvt *p;
00154    struct ast_codec_pref prefs;
00155    int amaflags;        /*!< AMA Flags */
00156    char user[AJI_MAX_JIDLEN];
00157    char context[AST_MAX_CONTEXT];
00158    char accountcode[AST_MAX_ACCOUNT_CODE];   /*!< Account code */
00159    int capability;
00160    ast_group_t callgroup;  /*!< Call group */
00161    ast_group_t pickupgroup;   /*!< Pickup group */
00162    int callingpres;     /*!< Calling presentation */
00163    int allowguest;
00164    char language[MAX_LANGUAGE];  /*!<  Default language for prompts */
00165    char musicclass[MAX_MUSICCLASS]; /*!<  Music on Hold class */
00166 };
00167 
00168 struct gtalk_container {
00169    ASTOBJ_CONTAINER_COMPONENTS(struct gtalk);
00170 };
00171 
00172 static const char desc[] = "Gtalk Channel";
00173 
00174 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
00175 
00176 AST_MUTEX_DEFINE_STATIC(gtalklock); /*!< Protect the interface list (of gtalk_pvt's) */
00177 
00178 /* Forward declarations */
00179 static struct ast_channel *gtalk_request(const char *type, int format, void *data, int *cause);
00180 static int gtalk_digit(struct ast_channel *ast, char digit, unsigned int duration);
00181 static int gtalk_digit_begin(struct ast_channel *ast, char digit);
00182 static int gtalk_digit_end(struct ast_channel *ast, char digit, unsigned int duration);
00183 static int gtalk_call(struct ast_channel *ast, char *dest, int timeout);
00184 static int gtalk_hangup(struct ast_channel *ast);
00185 static int gtalk_answer(struct ast_channel *ast);
00186 static int gtalk_action(struct gtalk *client, struct gtalk_pvt *p, const char *action);
00187 static void gtalk_free_pvt(struct gtalk *client, struct gtalk_pvt *p);
00188 static int gtalk_newcall(struct gtalk *client, ikspak *pak);
00189 static struct ast_frame *gtalk_read(struct ast_channel *ast);
00190 static int gtalk_write(struct ast_channel *ast, struct ast_frame *f);
00191 static int gtalk_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
00192 static int gtalk_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
00193 static int gtalk_sendhtml(struct ast_channel *ast, int subclass, const char *data, int datalen);
00194 static struct gtalk_pvt *gtalk_alloc(struct gtalk *client, const char *us, const char *them, const char *sid);
00195 static int gtalk_do_reload(int fd, int argc, char **argv);
00196 static int gtalk_show_channels(int fd, int argc, char **argv);
00197 /*----- RTP interface functions */
00198 static int gtalk_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp,
00199                         struct ast_rtp *vrtp, int codecs, int nat_active);
00200 static enum ast_rtp_get_result gtalk_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
00201 static int gtalk_get_codec(struct ast_channel *chan);
00202 
00203 /*! \brief PBX interface structure for channel registration */
00204 static const struct ast_channel_tech gtalk_tech = {
00205    .type = "Gtalk",
00206    .description = "Gtalk Channel Driver",
00207    .capabilities = ((AST_FORMAT_MAX_AUDIO << 1) - 1),
00208    .requester = gtalk_request,
00209    .send_digit_begin = gtalk_digit_begin,
00210    .send_digit_end = gtalk_digit_end,
00211    .bridge = ast_rtp_bridge,
00212    .call = gtalk_call,
00213    .hangup = gtalk_hangup,
00214    .answer = gtalk_answer,
00215    .read = gtalk_read,
00216    .write = gtalk_write,
00217    .exception = gtalk_read,
00218    .indicate = gtalk_indicate,
00219    .fixup = gtalk_fixup,
00220    .send_html = gtalk_sendhtml,
00221    .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER
00222 };
00223 
00224 static struct sockaddr_in bindaddr = { 0, }; /*!< The address we bind to */
00225 
00226 static struct sched_context *sched; /*!< The scheduling context */
00227 static struct io_context *io; /*!< The IO context */
00228 static struct in_addr __ourip;
00229 
00230 
00231 /*! \brief RTP driver interface */
00232 static struct ast_rtp_protocol gtalk_rtp = {
00233    type: "Gtalk",
00234    get_rtp_info: gtalk_get_rtp_peer,
00235    set_rtp_peer: gtalk_set_rtp_peer,
00236    get_codec: gtalk_get_codec,
00237 };
00238 
00239 static char show_channels_usage[] = 
00240 "Usage: gtalk show channels\n" 
00241 "       Shows current state of the Gtalk channels.\n";
00242 
00243 static char reload_usage[] = 
00244 "Usage: gtalk reload\n" 
00245 "       Reload gtalk channel driver.\n";
00246 
00247 
00248 static struct ast_cli_entry gtalk_cli[] = {
00249    {{ "gtalk", "reload", NULL}, gtalk_do_reload, "Reload GoogleTalk configuration", reload_usage },
00250    {{ "gtalk", "show", "channels", NULL}, gtalk_show_channels, "Show GoogleTalk channels", show_channels_usage },
00251  };
00252 
00253 
00254 
00255 static char externip[16];
00256 
00257 static struct gtalk_container gtalk_list;
00258 
00259 static void gtalk_member_destroy(struct gtalk *obj)
00260 {
00261    free(obj);
00262 }
00263 
00264 static struct gtalk *find_gtalk(char *name, char *connection)
00265 {
00266    struct gtalk *gtalk = NULL;
00267    char *domain = NULL , *s = NULL;
00268 
00269    if(strchr(connection, '@')) {
00270       s = ast_strdupa(connection);
00271       domain = strsep(&s, "@");
00272       ast_verbose("OOOOH domain = %s\n", domain);
00273    }
00274    gtalk = ASTOBJ_CONTAINER_FIND(&gtalk_list, name);
00275    if (!gtalk && strchr(name, '@'))
00276       gtalk = ASTOBJ_CONTAINER_FIND_FULL(&gtalk_list, name, user,,, strcasecmp);
00277 
00278    if (!gtalk) {
00279       /* guest call */
00280       ASTOBJ_CONTAINER_TRAVERSE(&gtalk_list, 1, {
00281          ASTOBJ_RDLOCK(iterator);
00282          if (!strcasecmp(iterator->name, "guest")) {
00283             gtalk = iterator;
00284          }
00285          ASTOBJ_UNLOCK(iterator);
00286 
00287          if (gtalk)
00288             break;
00289       });
00290 
00291    }
00292    return gtalk;
00293 }
00294 
00295 
00296 static int add_codec_to_answer(const struct gtalk_pvt *p, int codec, iks *dcodecs)
00297 {
00298    int res = 0;
00299    char *format = ast_getformatname(codec);
00300 
00301    if (!strcasecmp("ulaw", format)) {
00302       iks *payload_eg711u, *payload_pcmu;
00303       payload_pcmu = iks_new("payload-type");
00304       payload_eg711u = iks_new("payload-type");
00305    
00306       if(!payload_eg711u || !payload_pcmu) {
00307          if(payload_pcmu)
00308             iks_delete(payload_pcmu);
00309          if(payload_eg711u)
00310             iks_delete(payload_eg711u);
00311          ast_log(LOG_WARNING,"Failed to allocate iks node");
00312          return -1;
00313       }
00314       iks_insert_attrib(payload_pcmu, "id", "0");
00315       iks_insert_attrib(payload_pcmu, "name", "PCMU");
00316       iks_insert_attrib(payload_pcmu, "clockrate","8000");
00317       iks_insert_attrib(payload_pcmu, "bitrate","64000");
00318       iks_insert_attrib(payload_eg711u, "id", "100");
00319       iks_insert_attrib(payload_eg711u, "name", "EG711U");
00320       iks_insert_attrib(payload_eg711u, "clockrate","8000");
00321       iks_insert_attrib(payload_eg711u, "bitrate","64000");
00322       iks_insert_node(dcodecs, payload_pcmu);
00323       iks_insert_node(dcodecs, payload_eg711u);
00324       res ++;
00325    }
00326    if (!strcasecmp("alaw", format)) {
00327       iks *payload_eg711a, *payload_pcma;
00328       payload_pcma = iks_new("payload-type");
00329       payload_eg711a = iks_new("payload-type");
00330       if(!payload_eg711a || !payload_pcma) {
00331          if(payload_eg711a)
00332             iks_delete(payload_eg711a);
00333          if(payload_pcma)
00334             iks_delete(payload_pcma);
00335          ast_log(LOG_WARNING,"Failed to allocate iks node");
00336          return -1;
00337       }
00338       iks_insert_attrib(payload_pcma, "id", "8");
00339       iks_insert_attrib(payload_pcma, "name", "PCMA");
00340       iks_insert_attrib(payload_pcma, "clockrate","8000");
00341       iks_insert_attrib(payload_pcma, "bitrate","64000");
00342       payload_eg711a = iks_new("payload-type");
00343       iks_insert_attrib(payload_eg711a, "id", "101");
00344       iks_insert_attrib(payload_eg711a, "name", "EG711A");
00345       iks_insert_attrib(payload_eg711a, "clockrate","8000");
00346       iks_insert_attrib(payload_eg711a, "bitrate","64000");
00347       iks_insert_node(dcodecs, payload_pcma);
00348       iks_insert_node(dcodecs, payload_eg711a);
00349       res ++;
00350    }
00351    if (!strcasecmp("ilbc", format)) {
00352       iks *payload_ilbc = iks_new("payload-type");
00353       if(!payload_ilbc) {
00354          ast_log(LOG_WARNING,"Failed to allocate iks node");
00355          return -1;
00356       }
00357       iks_insert_attrib(payload_ilbc, "id", "97");
00358       iks_insert_attrib(payload_ilbc, "name", "iLBC");
00359       iks_insert_attrib(payload_ilbc, "clockrate","8000");
00360       iks_insert_attrib(payload_ilbc, "bitrate","13300");
00361       iks_insert_node(dcodecs, payload_ilbc);
00362       res ++;
00363    }
00364    if (!strcasecmp("g723", format)) {
00365       iks *payload_g723 = iks_new("payload-type");
00366       if(!payload_g723) {
00367          ast_log(LOG_WARNING,"Failed to allocate iks node");
00368          return -1;
00369       }
00370       iks_insert_attrib(payload_g723, "id", "4");
00371       iks_insert_attrib(payload_g723, "name", "G723");
00372       iks_insert_attrib(payload_g723, "clockrate","8000");
00373       iks_insert_attrib(payload_g723, "bitrate","6300");
00374       iks_insert_node(dcodecs, payload_g723);
00375       res ++;
00376    }
00377    if (!strcasecmp("speex", format)) {
00378       iks *payload_speex = iks_new("payload-type");
00379       if(!payload_speex) {
00380          ast_log(LOG_WARNING,"Failed to allocate iks node");
00381          return -1;
00382       }
00383       iks_insert_attrib(payload_speex, "id", "110");
00384       iks_insert_attrib(payload_speex, "name", "speex");
00385       iks_insert_attrib(payload_speex, "clockrate","8000");
00386       iks_insert_attrib(payload_speex, "bitrate","11000");
00387       iks_insert_node(dcodecs, payload_speex);
00388       res++;
00389    }
00390    if (!strcasecmp("gsm", format)) {
00391       iks *payload_gsm = iks_new("payload-type");
00392       if(!payload_gsm) {
00393          ast_log(LOG_WARNING,"Failed to allocate iks node");
00394          return -1;
00395       }
00396       iks_insert_attrib(payload_gsm, "id", "103");
00397       iks_insert_attrib(payload_gsm, "name", "gsm");
00398       iks_insert_node(dcodecs, payload_gsm);
00399       res++;
00400    }
00401    ast_rtp_lookup_code(p->rtp, 1, codec);
00402    return res;
00403 }
00404 
00405 static int gtalk_invite(struct gtalk_pvt *p, char *to, char *from, char *sid, int initiator)
00406 {
00407    struct gtalk *client = p->parent;
00408    iks *iq, *gtalk, *dcodecs, *payload_telephone, *transport;
00409    int x;
00410    int pref_codec = 0;
00411    int alreadysent = 0;
00412    int codecs_num = 0;
00413 
00414    iq = iks_new("iq");
00415    gtalk = iks_new("session");
00416    dcodecs = iks_new("description");
00417    transport = iks_new("transport");
00418    payload_telephone = iks_new("payload-type");
00419    if (!(iq && gtalk && dcodecs && transport && payload_telephone)){
00420       if(iq)
00421          iks_delete(iq);
00422       if(gtalk)
00423          iks_delete(gtalk);
00424       if(dcodecs)
00425          iks_delete(dcodecs);
00426       if(transport)
00427          iks_delete(transport);
00428       if(payload_telephone)
00429          iks_delete(payload_telephone);
00430 
00431       ast_log(LOG_ERROR, "Could not allocate iksemel nodes\n");
00432       return 0;
00433    }
00434    iks_insert_attrib(dcodecs, "xmlns", "http://www.google.com/session/phone");
00435    iks_insert_attrib(dcodecs, "xml:lang", "en");
00436 
00437    for (x = 0; x < 32; x++) {
00438       if (!(pref_codec = ast_codec_pref_index(&client->prefs, x)))
00439          break;
00440       if (!(client->capability & pref_codec))
00441          continue;
00442       if (alreadysent & pref_codec)
00443          continue;
00444       codecs_num = add_codec_to_answer(p, pref_codec, dcodecs);
00445       alreadysent |= pref_codec;
00446    }
00447    
00448    if (codecs_num) {
00449       /* only propose DTMF within an audio session */
00450       iks_insert_attrib(payload_telephone, "id", "106");
00451       iks_insert_attrib(payload_telephone, "name", "telephone-event");
00452       iks_insert_attrib(payload_telephone, "clockrate", "8000");
00453    }
00454    iks_insert_attrib(transport,"xmlns","http://www.google.com/transport/p2p");
00455    
00456    iks_insert_attrib(iq, "type", "set");
00457    iks_insert_attrib(iq, "to", to);
00458    iks_insert_attrib(iq, "from", from);
00459    iks_insert_attrib(iq, "id", client->connection->mid);
00460    ast_aji_increment_mid(client->connection->mid);
00461 
00462    iks_insert_attrib(gtalk, "xmlns", "http://www.google.com/session");
00463    iks_insert_attrib(gtalk, "type",initiator ? "initiate": "accept");
00464    iks_insert_attrib(gtalk, "initiator", initiator ? from : to);
00465    iks_insert_attrib(gtalk, "id", sid);
00466    iks_insert_node(iq, gtalk);
00467    iks_insert_node(gtalk, dcodecs);
00468    iks_insert_node(gtalk, transport);
00469    iks_insert_node(dcodecs, payload_telephone);
00470 
00471    iks_send(client->connection->p, iq);
00472    iks_delete(payload_telephone);
00473    iks_delete(transport);
00474    iks_delete(dcodecs);
00475    iks_delete(gtalk);
00476    iks_delete(iq);
00477    return 1;
00478 }
00479 
00480 static int gtalk_invite_response(struct gtalk_pvt *p, char *to , char *from, char *sid, int initiator)
00481 {
00482    iks *iq, *session, *transport;
00483    iq = iks_new("iq");
00484    session = iks_new("session");
00485    transport = iks_new("transport");
00486    if(!(iq && session && transport)) {
00487       if(iq)
00488          iks_delete(iq);
00489       if(session)
00490          iks_delete(session);
00491       if(transport)
00492          iks_delete(transport);
00493       ast_log(LOG_ERROR, " Unable to allocate IKS node\n");
00494       return -1;
00495    }
00496    iks_insert_attrib(iq, "from", from);
00497    iks_insert_attrib(iq, "to", to);
00498    iks_insert_attrib(iq, "type", "set");
00499    iks_insert_attrib(iq, "id",p->parent->connection->mid);
00500    ast_aji_increment_mid(p->parent->connection->mid);
00501    iks_insert_attrib(session, "type", "transport-accept");
00502    iks_insert_attrib(session, "id", sid);
00503    iks_insert_attrib(session, "initiator", initiator ? from : to);
00504    iks_insert_attrib(session, "xmlns", "http://www.google.com/session");
00505    iks_insert_attrib(transport, "xmlns", "http://www.google.com/transport/p2p");
00506    iks_insert_node(iq,session);
00507    iks_insert_node(session,transport);
00508    iks_send(p->parent->connection->p, iq);
00509    iks_delete(transport);
00510    iks_delete(session);
00511    iks_delete(iq);
00512    return 1;
00513 
00514 }
00515 
00516 static int gtalk_ringing_ack(void *data, ikspak *pak)
00517 {
00518    struct gtalk_pvt *p = data;
00519 
00520    if (p->ringrule)
00521       iks_filter_remove_rule(p->parent->connection->f, p->ringrule);
00522    p->ringrule = NULL;
00523    if (p->owner)
00524       ast_queue_control(p->owner, AST_CONTROL_RINGING);
00525    return IKS_FILTER_EAT;
00526 }
00527 
00528 static int gtalk_answer(struct ast_channel *ast)
00529 {
00530    struct gtalk_pvt *p = ast->tech_pvt;
00531    int res = 0;
00532    
00533    if (option_debug)
00534       ast_log(LOG_DEBUG, "Answer!\n");
00535    ast_mutex_lock(&p->lock);
00536    gtalk_invite(p, p->them, p->us,p->sid, 0);
00537    ast_mutex_unlock(&p->lock);
00538    return res;
00539 }
00540 
00541 static enum ast_rtp_get_result gtalk_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
00542 {
00543    struct gtalk_pvt *p = chan->tech_pvt;
00544    enum ast_rtp_get_result res = AST_RTP_GET_FAILED;
00545 
00546    if (!p)
00547       return res;
00548 
00549    ast_mutex_lock(&p->lock);
00550    if (p->rtp){
00551       *rtp = p->rtp;
00552       res = AST_RTP_TRY_PARTIAL;
00553    }
00554    ast_mutex_unlock(&p->lock);
00555 
00556    return res;
00557 }
00558 
00559 static int gtalk_get_codec(struct ast_channel *chan)
00560 {
00561    struct gtalk_pvt *p = chan->tech_pvt;
00562    return p->peercapability;
00563 }
00564 
00565 static int gtalk_set_rtp_peer(struct ast_channel *chan, struct ast_rtp *rtp, struct ast_rtp *vrtp, int codecs, int nat_active)
00566 {
00567    struct gtalk_pvt *p;
00568 
00569    p = chan->tech_pvt;
00570    if (!p)
00571       return -1;
00572    ast_mutex_lock(&p->lock);
00573 
00574 /* if (rtp)
00575       ast_rtp_get_peer(rtp, &p->redirip);
00576    else
00577       memset(&p->redirip, 0, sizeof(p->redirip));
00578    p->redircodecs = codecs; */
00579 
00580    /* Reset lastrtprx timer */
00581    ast_mutex_unlock(&p->lock);
00582    return 0;
00583 }
00584 
00585 static int gtalk_response(struct gtalk *client, char *from, ikspak *pak, const char *reasonstr, const char *reasonstr2)
00586 {
00587    iks *response = NULL, *error = NULL, *reason = NULL;
00588    int res = -1;
00589 
00590    response = iks_new("iq");
00591    if (response) {
00592       iks_insert_attrib(response, "type", "result");
00593       iks_insert_attrib(response, "from", from);
00594       iks_insert_attrib(response, "to", iks_find_attrib(pak->x, "from"));
00595       iks_insert_attrib(response, "id", iks_find_attrib(pak->x, "id"));
00596       if (reasonstr) {
00597          error = iks_new("error");
00598          if (error) {
00599             iks_insert_attrib(error, "type", "cancel");
00600             reason = iks_new(reasonstr);
00601             if (reason)
00602                iks_insert_node(error, reason);
00603             iks_insert_node(response, error);
00604          }
00605       }
00606       iks_send(client->connection->p, response);
00607       if (reason)
00608          iks_delete(reason);
00609       if (error)
00610          iks_delete(error);
00611       iks_delete(response);
00612       res = 0;
00613    }
00614    return res;
00615 }
00616 
00617 static int gtalk_is_answered(struct gtalk *client, ikspak *pak)
00618 {
00619    struct gtalk_pvt *tmp;
00620    char *from;
00621    iks *codec;
00622    char s1[BUFSIZ], s2[BUFSIZ], s3[BUFSIZ];
00623    int peernoncodeccapability;
00624 
00625    ast_log(LOG_DEBUG, "The client is %s\n", client->name);
00626    /* Make sure our new call doesn't exist yet */
00627    for (tmp = client->p; tmp; tmp = tmp->next) {
00628       if (iks_find_with_attrib(pak->x, "session", "id", tmp->sid))
00629          break;
00630    }
00631 
00632    /* codec points to the first <payload-type/> tag */
00633    codec = iks_child(iks_child(iks_child(pak->x)));
00634    while (codec) {
00635       ast_rtp_set_m_type(tmp->rtp, atoi(iks_find_attrib(codec, "id")));
00636       ast_rtp_set_rtpmap_type(tmp->rtp, atoi(iks_find_attrib(codec, "id")), "audio", iks_find_attrib(codec, "name"), 0);
00637       codec = iks_next(codec);
00638    }
00639    
00640    /* Now gather all of the codecs that we are asked for */
00641    ast_rtp_get_current_formats(tmp->rtp, &tmp->peercapability, &peernoncodeccapability);
00642    
00643    /* at this point, we received an awser from the remote Gtalk client,
00644       which allows us to compare capabilities */
00645    tmp->jointcapability = tmp->capability & tmp->peercapability;
00646    if (!tmp->jointcapability) {
00647       ast_log(LOG_WARNING, "Capabilities don't match : us - %s, peer - %s, combined - %s \n", ast_getformatname_multiple(s1, BUFSIZ, tmp->capability),
00648          ast_getformatname_multiple(s2, BUFSIZ, tmp->peercapability),
00649          ast_getformatname_multiple(s3, BUFSIZ, tmp->jointcapability));
00650       /* close session if capabilities don't match */
00651       ast_queue_hangup(tmp->owner);
00652 
00653       return -1;
00654 
00655    }  
00656    
00657    from = iks_find_attrib(pak->x, "to");
00658    if(!from)
00659       from = client->connection->jid->full;
00660 
00661    if (tmp) {
00662       if (tmp->owner)
00663          ast_queue_control(tmp->owner, AST_CONTROL_ANSWER);
00664    } else
00665       ast_log(LOG_NOTICE, "Whoa, didn't find call!\n");
00666    gtalk_response(client, from, pak, NULL, NULL);
00667    return 1;
00668 }
00669 
00670 static int gtalk_is_accepted(struct gtalk *client, ikspak *pak)
00671 {
00672    struct gtalk_pvt *tmp;
00673    char *from;
00674 
00675    ast_log(LOG_DEBUG, "The client is %s\n", client->name);
00676    /* find corresponding call */
00677    for (tmp = client->p; tmp; tmp = tmp->next) {
00678       if (iks_find_with_attrib(pak->x, "session", "id", tmp->sid))
00679          break;
00680    }
00681 
00682    from = iks_find_attrib(pak->x, "to");
00683    if(!from)
00684       from = client->connection->jid->full;
00685 
00686    if (!tmp)
00687       ast_log(LOG_NOTICE, "Whoa, didn't find call!\n");
00688 
00689    /* answer 'iq' packet to let the remote peer know that we're alive */
00690    gtalk_response(client, from, pak, NULL, NULL);
00691    return 1;
00692 }
00693 
00694 static int gtalk_handle_dtmf(struct gtalk *client, ikspak *pak)
00695 {
00696    struct gtalk_pvt *tmp;
00697    iks *dtmfnode = NULL, *dtmfchild = NULL;
00698    char *dtmf;
00699    char *from;
00700    /* Make sure our new call doesn't exist yet */
00701    for (tmp = client->p; tmp; tmp = tmp->next) {
00702       if (iks_find_with_attrib(pak->x, "session", "id", tmp->sid) || iks_find_with_attrib(pak->x, "gtalk", "sid", tmp->sid))
00703          break;
00704    }
00705    from = iks_find_attrib(pak->x, "to");
00706    if(!from)
00707       from = client->connection->jid->full;
00708 
00709 
00710    if (tmp) {
00711       if(iks_find_with_attrib(pak->x, "dtmf-method", "method", "rtp")) {
00712          gtalk_response(client, from, pak,
00713                "feature-not-implemented xmlns='urn:ietf:params:xml:ns:xmpp-stanzas'",
00714                "unsupported-dtmf-method xmlns='http://jabber.org/protocol/gtalk/info/dtmf#errors'");
00715          return -1;
00716       }
00717       if ((dtmfnode = iks_find(pak->x, "dtmf"))) {
00718          if((dtmf = iks_find_attrib(dtmfnode, "code"))) {
00719             if(iks_find_with_attrib(pak->x, "dtmf", "action", "button-up")) {
00720                struct ast_frame f = {AST_FRAME_DTMF_BEGIN, };
00721                f.subclass = dtmf[0];
00722                ast_queue_frame(tmp->owner, &f);
00723                ast_verbose("GOOGLE! DTMF-relay event received: %c\n", f.subclass);
00724             } else if(iks_find_with_attrib(pak->x, "dtmf", "action", "button-down")) {
00725                struct ast_frame f = {AST_FRAME_DTMF_END, };
00726                f.subclass = dtmf[0];
00727                ast_queue_frame(tmp->owner, &f);
00728                ast_verbose("GOOGLE! DTMF-relay event received: %c\n", f.subclass);
00729             } else if(iks_find_attrib(pak->x, "dtmf")) { /* 250 millasecond default */
00730                struct ast_frame f = {AST_FRAME_DTMF, };
00731                f.subclass = dtmf[0];
00732                ast_queue_frame(tmp->owner, &f);
00733                ast_verbose("GOOGLE! DTMF-relay event received: %c\n", f.subclass);
00734             }
00735          }
00736       } else if ((dtmfnode = iks_find_with_attrib(pak->x, "gtalk", "action", "session-info"))) {
00737          if((dtmfchild = iks_find(dtmfnode, "dtmf"))) {
00738             if((dtmf = iks_find_attrib(dtmfchild, "code"))) {
00739                if(iks_find_with_attrib(dtmfnode, "dtmf", "action", "button-up")) {
00740                   struct ast_frame f = {AST_FRAME_DTMF_END, };
00741                   f.subclass = dtmf[0];
00742                   ast_queue_frame(tmp->owner, &f);
00743                   ast_verbose("GOOGLE! DTMF-relay event received: %c\n", f.subclass);
00744                } else if(iks_find_with_attrib(dtmfnode, "dtmf", "action", "button-down")) {
00745                   struct ast_frame f = {AST_FRAME_DTMF_BEGIN, };
00746                   f.subclass = dtmf[0];
00747                   ast_queue_frame(tmp->owner, &f);
00748                   ast_verbose("GOOGLE! DTMF-relay event received: %c\n", f.subclass);
00749                }
00750             }
00751          }
00752       }
00753       gtalk_response(client, from, pak, NULL, NULL);
00754       return 1;
00755    } else
00756       ast_log(LOG_NOTICE, "Whoa, didn't find call!\n");
00757 
00758    gtalk_response(client, from, pak, NULL, NULL);
00759    return 1;
00760 }
00761 
00762 static int gtalk_hangup_farend(struct gtalk *client, ikspak *pak)
00763 {
00764    struct gtalk_pvt *tmp;
00765    char *from;
00766 
00767    ast_log(LOG_DEBUG, "The client is %s\n", client->name);
00768    /* Make sure our new call doesn't exist yet */
00769    for (tmp = client->p; tmp; tmp = tmp->next) {
00770       if (iks_find_with_attrib(pak->x, "session", "id", tmp->sid))
00771          break;
00772    }
00773    from = iks_find_attrib(pak->x, "to");
00774    if(!from)
00775       from = client->connection->jid->full;
00776 
00777    if (tmp) {
00778       tmp->alreadygone = 1;
00779       if (tmp->owner)
00780          ast_queue_hangup(tmp->owner);
00781    } else
00782       ast_log(LOG_NOTICE, "Whoa, didn't find call!\n");
00783    gtalk_response(client, from, pak, NULL, NULL);
00784    return 1;
00785 }
00786 
00787 static int gtalk_create_candidates(struct gtalk *client, struct gtalk_pvt *p, char *sid, char *from, char *to)
00788 {
00789    struct gtalk_candidate *tmp;
00790    struct aji_client *c = client->connection;
00791    struct gtalk_candidate *ours1 = NULL, *ours2 = NULL;
00792    struct sockaddr_in sin;
00793    struct sockaddr_in dest;
00794    struct in_addr us;
00795    iks *iq, *gtalk, *candidate, *transport;
00796    char user[17], pass[17], preference[5], port[7];
00797 
00798 
00799    iq = iks_new("iq");
00800    gtalk = iks_new("session");
00801    candidate = iks_new("candidate");
00802    transport = iks_new("transport");
00803    if (!iq || !gtalk || !candidate || !transport) {
00804       ast_log(LOG_ERROR, "Memory allocation error\n");
00805       goto safeout;
00806    }
00807    ours1 = ast_calloc(1, sizeof(*ours1));
00808    ours2 = ast_calloc(1, sizeof(*ours2));
00809    if (!ours1 || !ours2)
00810       goto safeout;
00811 
00812    iks_insert_attrib(transport, "xmlns","http://www.google.com/transport/p2p");
00813    iks_insert_node(iq, gtalk);
00814    iks_insert_node(gtalk,transport);
00815    iks_insert_node(transport, candidate);
00816 
00817    for (; p; p = p->next) {
00818       if (!strcasecmp(p->sid, sid))
00819          break;
00820    }
00821 
00822    if (!p) {
00823       ast_log(LOG_NOTICE, "No matching gtalk session - SID %s!\n", sid);
00824       goto safeout;
00825    }
00826 
00827    ast_rtp_get_us(p->rtp, &sin);
00828    ast_find_ourip(&us, bindaddr);
00829 
00830    /* Setup our gtalk candidates */
00831    ast_copy_string(ours1->name, "rtp", sizeof(ours1->name));
00832    ours1->port = ntohs(sin.sin_port);
00833    ours1->preference = 1;
00834    snprintf(user, sizeof(user), "%08lx%08lx", ast_random(), ast_random());
00835    snprintf(pass, sizeof(pass), "%08lx%08lx", ast_random(), ast_random());
00836    ast_copy_string(ours1->username, user, sizeof(ours1->username));
00837    ast_copy_string(ours1->password, pass, sizeof(ours1->password));
00838    ast_copy_string(ours1->ip, ast_inet_ntoa(us), sizeof(ours1->ip));
00839    ours1->protocol = AJI_PROTOCOL_UDP;
00840    ours1->type = AJI_CONNECT_LOCAL;
00841    ours1->generation = 0;
00842    p->ourcandidates = ours1;
00843 
00844    if (!ast_strlen_zero(externip)) {
00845       /* XXX We should really stun for this one not just go with externip XXX */
00846       snprintf(user, sizeof(user), "%08lx%08lx", ast_random(), ast_random());
00847       snprintf(pass, sizeof(pass), "%08lx%08lx", ast_random(), ast_random());
00848       ast_copy_string(ours2->username, user, sizeof(ours2->username));
00849       ast_copy_string(ours2->password, pass, sizeof(ours2->password));
00850       ast_copy_string(ours2->ip, externip, sizeof(ours2->ip));
00851       ast_copy_string(ours2->name, "rtp", sizeof(ours1->name));
00852       ours2->port = ntohs(sin.sin_port);
00853       ours2->preference = 0.9;
00854       ours2->protocol = AJI_PROTOCOL_UDP;
00855       ours2->type = AJI_CONNECT_STUN;
00856       ours2->generation = 0;
00857       ours1->next = ours2;
00858       ours2 = NULL;
00859    }
00860    ours1 = NULL;
00861    dest.sin_addr = __ourip;
00862    dest.sin_port = sin.sin_port;
00863 
00864 
00865    for (tmp = p->ourcandidates; tmp; tmp = tmp->next) {
00866       snprintf(port, sizeof(port), "%d", tmp->port);
00867       snprintf(preference, sizeof(preference), "%.2f", tmp->preference);
00868       iks_insert_attrib(iq, "from", to);
00869       iks_insert_attrib(iq, "to", from);
00870       iks_insert_attrib(iq, "type", "set");
00871       iks_insert_attrib(iq, "id", c->mid);
00872       ast_aji_increment_mid(c->mid);
00873       iks_insert_attrib(gtalk, "type", "transport-info");
00874       iks_insert_attrib(gtalk, "id", sid);
00875       iks_insert_attrib(gtalk, "initiator", (p->initiator) ? to : from);
00876       iks_insert_attrib(gtalk, "xmlns", GOOGLE_NS);
00877       iks_insert_attrib(candidate, "name", tmp->name);
00878       iks_insert_attrib(candidate, "address", tmp->ip);
00879       iks_insert_attrib(candidate, "port", port);
00880       iks_insert_attrib(candidate, "username", tmp->username);
00881       iks_insert_attrib(candidate, "password", tmp->password);
00882       iks_insert_attrib(candidate, "preference", preference);
00883       if (tmp->protocol == AJI_PROTOCOL_UDP)
00884          iks_insert_attrib(candidate, "protocol", "udp");
00885       if (tmp->protocol == AJI_PROTOCOL_SSLTCP)
00886          iks_insert_attrib(candidate, "protocol", "ssltcp");
00887       if (tmp->type == AJI_CONNECT_STUN)
00888          iks_insert_attrib(candidate, "type", "stun");
00889       if (tmp->type == AJI_CONNECT_LOCAL)
00890          iks_insert_attrib(candidate, "type", "local");
00891       if (tmp->type == AJI_CONNECT_RELAY)
00892          iks_insert_attrib(candidate, "type", "relay");
00893       iks_insert_attrib(candidate, "network", "0");
00894       iks_insert_attrib(candidate, "generation", "0");
00895       iks_send(c->p, iq);
00896    }
00897    p->laststun = 0;
00898 
00899 safeout:
00900    if (ours1)
00901       free(ours1);
00902    if (ours2)
00903       free(ours2);
00904    if (iq)
00905       iks_delete(iq);
00906    if (gtalk)
00907       iks_delete(gtalk);
00908    if (candidate)
00909       iks_delete(candidate);
00910    if(transport)
00911       iks_delete(transport);
00912    return 1;
00913 }
00914 
00915 static struct gtalk_pvt *gtalk_alloc(struct gtalk *client, const char *us, const char *them, const char *sid)
00916 {
00917    struct gtalk_pvt *tmp = NULL;
00918    struct aji_resource *resources = NULL;
00919    struct aji_buddy *buddy;
00920    char idroster[200];
00921    char *data, *exten = NULL;
00922 
00923    if (option_debug)
00924       ast_log(LOG_DEBUG, "The client is %s for alloc\n", client->name);
00925    if (!sid && !strchr(them, '/')) {   /* I started call! */
00926       if (!strcasecmp(client->name, "guest")) {
00927          buddy = ASTOBJ_CONTAINER_FIND(&client->connection->buddies, them);
00928          if (buddy)
00929             resources = buddy->resources;
00930       } else if (client->buddy)
00931          resources = client->buddy->resources;
00932       while (resources) {
00933          if (resources->cap->jingle) {
00934             break;
00935          }
00936          resources = resources->next;
00937       }
00938       if (resources)
00939          snprintf(idroster, sizeof(idroster), "%s/%s", them, resources->resource);
00940       else {
00941          ast_log(LOG_ERROR, "no gtalk capable clients to talk to.\n");
00942          return NULL;
00943       }
00944    }
00945    if (!(tmp = ast_calloc(1, sizeof(*tmp)))) {
00946       return NULL;
00947    }
00948    if (sid) {
00949       ast_copy_string(tmp->sid, sid, sizeof(tmp->sid));
00950       ast_copy_string(tmp->them, them, sizeof(tmp->them));
00951       ast_copy_string(tmp->us, us, sizeof(tmp->us));
00952    } else {
00953       snprintf(tmp->sid, sizeof(tmp->sid), "%08lx%08lx", ast_random(), ast_random());
00954       ast_copy_string(tmp->them, idroster, sizeof(tmp->them));
00955       ast_copy_string(tmp->us, us, sizeof(tmp->us));
00956       tmp->initiator = 1;
00957    }
00958    /* clear codecs */
00959    tmp->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
00960    ast_rtp_pt_clear(tmp->rtp);
00961 
00962    /* add user configured codec capabilites */
00963    if (client->capability)
00964       tmp->capability = client->capability;
00965    else if (global_capability)
00966       tmp->capability = global_capability;
00967 
00968    tmp->parent = client;
00969    if (!tmp->rtp) {
00970       ast_log(LOG_WARNING, "Out of RTP sessions?\n");
00971       free(tmp);
00972       return NULL;
00973    }
00974 
00975    /* Set CALLERID(name) to the full JID of the remote peer */
00976    ast_copy_string(tmp->cid_name, tmp->them, sizeof(tmp->cid_name));
00977 
00978    if(strchr(tmp->us, '/')) {
00979       data = ast_strdupa(tmp->us);
00980       exten = strsep(&data, "/");
00981    } else
00982       exten = tmp->us;
00983    ast_copy_string(tmp->exten,  exten, sizeof(tmp->exten));
00984    ast_mutex_init(&tmp->lock);
00985    ast_mutex_lock(&gtalklock);
00986    tmp->next = client->p;
00987    client->p = tmp;
00988    ast_mutex_unlock(&gtalklock);
00989    return tmp;
00990 }
00991 
00992 /*! \brief Start new gtalk channel */
00993 static struct ast_channel *gtalk_new(struct gtalk *client, struct gtalk_pvt *i, int state, const char *title)
00994 {
00995    struct ast_channel *tmp;
00996    int fmt;
00997    int what;
00998    const char *n2;
00999 
01000    if (title)
01001       n2 = title;
01002    else
01003       n2 = i->us;
01004    tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, client->accountcode, i->exten, client->context, client->amaflags, "Gtalk/%s-%04lx", n2, ast_random() & 0xffff);
01005    if (!tmp) {
01006       ast_log(LOG_WARNING, "Unable to allocate Gtalk channel structure!\n");
01007       return NULL;
01008    }
01009    tmp->tech = &gtalk_tech;
01010 
01011    /* Select our native format based on codec preference until we receive
01012       something from another device to the contrary. */
01013    if (i->jointcapability)
01014       what = i->jointcapability;
01015    else if (i->capability)
01016       what = i->capability;
01017    else
01018       what = global_capability;
01019    tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | (i->jointcapability & AST_FORMAT_VIDEO_MASK);
01020    fmt = ast_best_codec(tmp->nativeformats);
01021 
01022    if (i->rtp) {
01023       ast_rtp_setstun(i->rtp, 1);
01024       tmp->fds[0] = ast_rtp_fd(i->rtp);
01025       tmp->fds[1] = ast_rtcp_fd(i->rtp);
01026    }
01027    if (i->vrtp) {
01028       ast_rtp_setstun(i->rtp, 1);
01029       tmp->fds[2] = ast_rtp_fd(i->vrtp);
01030       tmp->fds[3] = ast_rtcp_fd(i->vrtp);
01031    }
01032    if (state == AST_STATE_RING)
01033       tmp->rings = 1;
01034    tmp->adsicpe = AST_ADSI_UNAVAILABLE;
01035    tmp->writeformat = fmt;
01036    tmp->rawwriteformat = fmt;
01037    tmp->readformat = fmt;
01038    tmp->rawreadformat = fmt;
01039    tmp->tech_pvt = i;
01040 
01041    tmp->callgroup = client->callgroup;
01042    tmp->pickupgroup = client->pickupgroup;
01043    tmp->cid.cid_pres = client->callingpres;
01044    if (!ast_strlen_zero(client->accountcode))
01045       ast_string_field_set(tmp, accountcode, client->accountcode);
01046    if (client->amaflags)
01047       tmp->amaflags = client->amaflags;
01048    if (!ast_strlen_zero(client->language))
01049       ast_string_field_set(tmp, language, client->language);
01050    if (!ast_strlen_zero(client->musicclass))
01051       ast_string_field_set(tmp, musicclass, client->musicclass);
01052    i->owner = tmp;
01053    ast_module_ref(ast_module_info->self);
01054    ast_copy_string(tmp->context, client->context, sizeof(tmp->context));
01055    ast_copy_string(tmp->exten, i->exten, sizeof(tmp->exten));
01056 
01057    if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
01058       tmp->cid.cid_dnid = ast_strdup(i->exten);
01059    tmp->priority = 1;
01060    if (i->rtp)
01061       ast_jb_configure(tmp, &global_jbconf);
01062    if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
01063       ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
01064       tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
01065       ast_hangup(tmp);
01066       tmp = NULL;
01067    }
01068 
01069    return tmp;
01070 }
01071 
01072 static int gtalk_action(struct gtalk *client, struct gtalk_pvt *p, const char *action)
01073 {
01074    iks *request, *session = NULL;
01075    int res = -1;
01076 
01077    request = iks_new("iq");
01078    if (request) {
01079       iks_insert_attrib(request, "type", "set");
01080       iks_insert_attrib(request, "from", p->us);
01081       iks_insert_attrib(request, "to", p->them);
01082       iks_insert_attrib(request, "id", client->connection->mid);
01083       ast_aji_increment_mid(client->connection->mid);
01084       session = iks_new("session");
01085       if (session) {
01086          iks_insert_attrib(session, "type", action);
01087          iks_insert_attrib(session, "id", p->sid);
01088          iks_insert_attrib(session, "initiator", p->initiator ? p->us : p->them);
01089          iks_insert_attrib(session, "xmlns", "http://www.google.com/session");
01090          iks_insert_node(request, session);
01091          iks_send(client->connection->p, request);
01092          iks_delete(session);
01093          res = 0;
01094       }
01095       iks_delete(request);
01096    }
01097    return res;
01098 }
01099 
01100 static void gtalk_free_candidates(struct gtalk_candidate *candidate)
01101 {
01102    struct gtalk_candidate *last;
01103    while (candidate) {
01104       last = candidate;
01105       candidate = candidate->next;
01106       free(last);
01107    }
01108 }
01109 
01110 static void gtalk_free_pvt(struct gtalk *client, struct gtalk_pvt *p)
01111 {
01112    struct gtalk_pvt *cur, *prev = NULL;
01113    cur = client->p;
01114    while (cur) {
01115       if (cur == p) {
01116          if (prev)
01117             prev->next = p->next;
01118          else
01119             client->p = p->next;
01120          break;
01121       }
01122       prev = cur;
01123       cur = cur->next;
01124    }
01125    if (p->ringrule)
01126       iks_filter_remove_rule(p->parent->connection->f, p->ringrule);
01127    if (p->owner)
01128       ast_log(LOG_WARNING, "Uh oh, there's an owner, this is going to be messy.\n");
01129    if (p->rtp)
01130       ast_rtp_destroy(p->rtp);
01131    if (p->vrtp)
01132       ast_rtp_destroy(p->vrtp);
01133    gtalk_free_candidates(p->theircandidates);
01134    free(p);
01135 }
01136 
01137 
01138 static int gtalk_newcall(struct gtalk *client, ikspak *pak)
01139 {
01140    struct gtalk_pvt *p, *tmp = client->p;
01141    struct ast_channel *chan;
01142    int res;
01143    iks *codec;
01144    char *from = NULL;
01145    char s1[BUFSIZ], s2[BUFSIZ], s3[BUFSIZ];
01146    int peernoncodeccapability;
01147 
01148    /* Make sure our new call doesn't exist yet */
01149    from = iks_find_attrib(pak->x,"to");
01150    if(!from)
01151       from = client->connection->jid->full;
01152    
01153    while (tmp) {
01154       if (iks_find_with_attrib(pak->x, "session", "id", tmp->sid)) {
01155          ast_log(LOG_NOTICE, "Ignoring duplicate call setup on SID %s\n", tmp->sid);
01156          gtalk_response(client, from, pak, "out-of-order", NULL);
01157          return -1;
01158       }
01159       tmp = tmp->next;
01160    }
01161 
01162    if (!strcasecmp(client->name, "guest")){
01163       /* the guest account is not tied to any configured XMPP client,
01164          let's set it now */
01165       client->connection = ast_aji_get_client(from);
01166       if (!client->connection) {
01167          ast_log(LOG_ERROR, "No XMPP client to talk to, us (partial JID) : %s\n", from);
01168          return -1;
01169       }
01170    }
01171 
01172    p = gtalk_alloc(client, from, pak->from->full, iks_find_attrib(pak->query, "id"));
01173    if (!p) {
01174       ast_log(LOG_WARNING, "Unable to allocate gtalk structure!\n");
01175       return -1;
01176    }
01177 
01178    chan = gtalk_new(client, p, AST_STATE_DOWN, pak->from->user);
01179    if (!chan) {
01180       gtalk_free_pvt(client, p);
01181       return -1;
01182    }
01183 
01184    ast_mutex_lock(&p->lock);
01185    ast_copy_string(p->them, pak->from->full, sizeof(p->them));
01186    if (iks_find_attrib(pak->query, "id")) {
01187       ast_copy_string(p->sid, iks_find_attrib(pak->query, "id"),
01188             sizeof(p->sid));
01189    }
01190 
01191    /* codec points to the first <payload-type/> tag */   
01192    codec = iks_child(iks_child(iks_child(pak->x)));
01193    
01194    while (codec) {
01195       ast_rtp_set_m_type(p->rtp, atoi(iks_find_attrib(codec, "id")));
01196       ast_rtp_set_rtpmap_type(p->rtp, atoi(iks_find_attrib(codec, "id")), "audio", iks_find_attrib(codec, "name"), 0);
01197       codec = iks_next(codec);
01198    }
01199    
01200    /* Now gather all of the codecs that we are asked for */
01201    ast_rtp_get_current_formats(p->rtp, &p->peercapability, &peernoncodeccapability);
01202    p->jointcapability = p->capability & p->peercapability;
01203    ast_mutex_unlock(&p->lock);
01204       
01205    ast_setstate(chan, AST_STATE_RING);
01206    if (!p->jointcapability) {
01207       ast_log(LOG_WARNING, "Capabilities don't match : us - %s, peer - %s, combined - %s \n", ast_getformatname_multiple(s1, BUFSIZ, p->capability),
01208          ast_getformatname_multiple(s2, BUFSIZ, p->peercapability),
01209          ast_getformatname_multiple(s3, BUFSIZ, p->jointcapability));
01210       /* close session if capabilities don't match */
01211       gtalk_action(client, p, "reject");
01212       p->alreadygone = 1;
01213       gtalk_hangup(chan);
01214       ast_channel_free(chan);
01215       return -1;
01216    }  
01217 
01218    res = ast_pbx_start(chan);
01219    
01220    switch (res) {
01221    case AST_PBX_FAILED:
01222       ast_log(LOG_WARNING, "Failed to start PBX :(\n");
01223       gtalk_response(client, from, pak, "service-unavailable", NULL);
01224       break;
01225    case AST_PBX_CALL_LIMIT:
01226       ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
01227       gtalk_response(client, from, pak, "service-unavailable", NULL);
01228       break;
01229    case AST_PBX_SUCCESS:
01230       gtalk_response(client, from, pak, NULL, NULL);
01231       gtalk_invite_response(p, p->them, p->us,p->sid, 0);
01232       gtalk_create_candidates(client, p, p->sid, p->them, p->us);
01233       /* nothing to do */
01234       break;
01235    }
01236 
01237    return 1;
01238 }
01239 
01240 static int gtalk_update_stun(struct gtalk *client, struct gtalk_pvt *p)
01241 {
01242    struct gtalk_candidate *tmp;
01243    struct hostent *hp;
01244    struct ast_hostent ahp;
01245    struct sockaddr_in sin;
01246    struct sockaddr_in aux;
01247 
01248    if (time(NULL) == p->laststun)
01249       return 0;
01250 
01251    tmp = p->theircandidates;
01252    p->laststun = time(NULL);
01253    while (tmp) {
01254       char username[256];
01255 
01256       /* Find the IP address of the host */
01257       hp = ast_gethostbyname(tmp->ip, &ahp);
01258       sin.sin_family = AF_INET;
01259       memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
01260       sin.sin_port = htons(tmp->port);
01261       snprintf(username, sizeof(username), "%s%s", tmp->username,
01262           p->ourcandidates->username);
01263       
01264       /* Find out the result of the STUN */
01265       ast_rtp_get_peer(p->rtp, &aux);
01266 
01267       /* If the STUN result is different from the IP of the hostname,
01268          lock on the stun IP of the hostname advertised by the
01269          remote client */
01270       if (aux.sin_addr.s_addr && 
01271           aux.sin_addr.s_addr != sin.sin_addr.s_addr)
01272          ast_rtp_stun_request(p->rtp, &aux, username);
01273       else 
01274          ast_rtp_stun_request(p->rtp, &sin, username);
01275       
01276       if (aux.sin_addr.s_addr && option_debug > 3) {
01277          ast_log(LOG_DEBUG, "Receiving RTP traffic from IP %s, matches with remote candidate's IP %s\n", ast_inet_ntoa(aux.sin_addr), tmp->ip);
01278          ast_log(LOG_DEBUG, "Sending STUN request to %s\n", tmp->ip);
01279       }
01280 
01281       tmp = tmp->next;
01282    }
01283    return 1;
01284 }
01285 
01286 static int gtalk_add_candidate(struct gtalk *client, ikspak *pak)
01287 {
01288    struct gtalk_pvt *p = NULL, *tmp = NULL;
01289    struct aji_client *c = client->connection;
01290    struct gtalk_candidate *newcandidate = NULL;
01291    iks *traversenodes = NULL, *receipt = NULL;
01292    char *from;
01293 
01294    from = iks_find_attrib(pak->x,"to");
01295    if(!from)
01296       from = c->jid->full;
01297 
01298    for (tmp = client->p; tmp; tmp = tmp->next) {
01299       if (iks_find_with_attrib(pak->x, "session", "id", tmp->sid)) {
01300          p = tmp;
01301          break;
01302       }
01303    }
01304 
01305    if (!p)
01306       return -1;
01307 
01308    traversenodes = pak->query;
01309    while(traversenodes) {
01310       if(!strcasecmp(iks_name(traversenodes), "session")) {
01311          traversenodes = iks_child(traversenodes);
01312          continue;
01313       }
01314       if(!strcasecmp(iks_name(traversenodes), "transport")) {
01315          traversenodes = iks_child(traversenodes);
01316          continue;
01317       }
01318       if(!strcasecmp(iks_name(traversenodes), "candidate")) {
01319          newcandidate = ast_calloc(1, sizeof(*newcandidate));
01320          if (!newcandidate)
01321             return 0;
01322          ast_copy_string(newcandidate->name, iks_find_attrib(traversenodes, "name"),
01323                      sizeof(newcandidate->name));
01324          ast_copy_string(newcandidate->ip, iks_find_attrib(traversenodes, "address"),
01325                      sizeof(newcandidate->ip));
01326          newcandidate->port = atoi(iks_find_attrib(traversenodes, "port"));
01327          ast_copy_string(newcandidate->username, iks_find_attrib(traversenodes, "username"),
01328                      sizeof(newcandidate->username));
01329          ast_copy_string(newcandidate->password, iks_find_attrib(traversenodes, "password"),
01330                      sizeof(newcandidate->password));
01331          newcandidate->preference = atof(iks_find_attrib(traversenodes, "preference"));
01332          if (!strcasecmp(iks_find_attrib(traversenodes, "protocol"), "udp"))
01333             newcandidate->protocol = AJI_PROTOCOL_UDP;
01334          if (!strcasecmp(iks_find_attrib(traversenodes, "protocol"), "ssltcp"))
01335             newcandidate->protocol = AJI_PROTOCOL_SSLTCP;
01336       
01337          if (!strcasecmp(iks_find_attrib(traversenodes, "type"), "stun"))
01338             newcandidate->type = AJI_CONNECT_STUN;
01339          if (!strcasecmp(iks_find_attrib(traversenodes, "type"), "local"))
01340             newcandidate->type = AJI_CONNECT_LOCAL;
01341          if (!strcasecmp(iks_find_attrib(traversenodes, "type"), "relay"))
01342             newcandidate->type = AJI_CONNECT_RELAY;
01343          ast_copy_string(newcandidate->network, iks_find_attrib(traversenodes, "network"),
01344                      sizeof(newcandidate->network));
01345          newcandidate->generation = atoi(iks_find_attrib(traversenodes, "generation"));
01346          newcandidate->next = NULL;
01347       
01348          newcandidate->next = p->theircandidates;
01349          p->theircandidates = newcandidate;
01350          p->laststun = 0;
01351          gtalk_update_stun(p->parent, p);
01352          newcandidate = NULL;
01353       }
01354       traversenodes = iks_next(traversenodes);
01355    }
01356    
01357    receipt = iks_new("iq");
01358    iks_insert_attrib(receipt, "type", "result");
01359    iks_insert_attrib(receipt, "from", from);
01360    iks_insert_attrib(receipt, "to", iks_find_attrib(pak->x, "from"));
01361    iks_insert_attrib(receipt, "id", iks_find_attrib(pak->x, "id"));
01362    iks_send(c->p, receipt);
01363    iks_delete(receipt);
01364 
01365    return 1;
01366 }
01367 
01368 static struct ast_frame *gtalk_rtp_read(struct ast_channel *ast, struct gtalk_pvt *p)
01369 {
01370    struct ast_frame *f;
01371 
01372    if (!p->rtp)
01373       return &ast_null_frame;
01374    f = ast_rtp_read(p->rtp);
01375    gtalk_update_stun(p->parent, p);
01376    if (p->owner) {
01377       /* We already hold the channel lock */
01378       if (f->frametype == AST_FRAME_VOICE) {
01379          if (f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
01380             if (option_debug)
01381                ast_log(LOG_DEBUG, "Oooh, format changed to %d\n", f->subclass);
01382             p->owner->nativeformats =
01383                (p->owner->nativeformats & AST_FORMAT_VIDEO_MASK) | f->subclass;
01384             ast_set_read_format(p->owner, p->owner->readformat);
01385             ast_set_write_format(p->owner, p->owner->writeformat);
01386          }
01387 /*       if ((ast_test_flag(p, SIP_DTMF) == SIP_DTMF_INBAND) && p->vad) {
01388             f = ast_dsp_process(p->owner, p->vad, f);
01389             if (option_debug && f && (f->frametype == AST_FRAME_DTMF))
01390                ast_log(LOG_DEBUG, "* Detected inband DTMF '%c'\n", f->subclass);
01391               } */
01392       }
01393    }
01394    return f;
01395 }
01396 
01397 static struct ast_frame *gtalk_read(struct ast_channel *ast)
01398 {
01399    struct ast_frame *fr;
01400    struct gtalk_pvt *p = ast->tech_pvt;
01401 
01402    ast_mutex_lock(&p->lock);
01403    fr = gtalk_rtp_read(ast, p);
01404    ast_mutex_unlock(&p->lock);
01405    return fr;
01406 }
01407 
01408 /*! \brief Send frame to media channel (rtp) */
01409 static int gtalk_write(struct ast_channel *ast, struct ast_frame *frame)
01410 {
01411    struct gtalk_pvt *p = ast->tech_pvt;
01412    int res = 0;
01413 
01414    switch (frame->frametype) {
01415    case AST_FRAME_VOICE:
01416       if (!(frame->subclass & ast->nativeformats)) {
01417          ast_log(LOG_WARNING,
01418                "Asked to transmit frame type %d, while native formats is %d (read/write = %d/%d)\n",
01419                frame->subclass, ast->nativeformats, ast->readformat,
01420                ast->writeformat);
01421          return 0;
01422       }
01423       if (p) {
01424          ast_mutex_lock(&p->lock);
01425          if (p->rtp) {
01426             res = ast_rtp_write(p->rtp, frame);
01427          }
01428          ast_mutex_unlock(&p->lock);
01429       }
01430       break;
01431    case AST_FRAME_VIDEO:
01432       if (p) {
01433          ast_mutex_lock(&p->lock);
01434          if (p->vrtp) {
01435             res = ast_rtp_write(p->vrtp, frame);
01436          }
01437          ast_mutex_unlock(&p->lock);
01438       }
01439       break;
01440    case AST_FRAME_IMAGE:
01441       return 0;
01442       break;
01443    default:
01444       ast_log(LOG_WARNING, "Can't send %d type frames with Gtalk write\n",
01445             frame->frametype);
01446       return 0;
01447    }
01448 
01449    return res;
01450 }
01451 
01452 static int gtalk_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
01453 {
01454    struct gtalk_pvt *p = newchan->tech_pvt;
01455    ast_mutex_lock(&p->lock);
01456 
01457    if ((p->owner != oldchan)) {
01458       ast_mutex_unlock(&p->lock);
01459       return -1;
01460    }
01461    if (p->owner == oldchan)
01462       p->owner = newchan;
01463    ast_mutex_unlock(&p->lock);
01464    return 0;
01465 }
01466 
01467 static int gtalk_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
01468 {
01469    int res = 0;
01470 
01471    switch (condition) {
01472    case AST_CONTROL_HOLD:
01473       ast_moh_start(ast, data, NULL);
01474       break;
01475    case AST_CONTROL_UNHOLD:
01476       ast_moh_stop(ast);
01477       break;
01478    default:
01479       ast_log(LOG_NOTICE, "Don't know how to indicate condition '%d'\n", condition);
01480       res = -1;
01481    }
01482 
01483    return res;
01484 }
01485 
01486 static int gtalk_digit_begin(struct ast_channel *chan, char digit)
01487 {
01488    return gtalk_digit(chan, digit, 0);
01489 }
01490 
01491 static int gtalk_digit_end(struct ast_channel *chan, char digit, unsigned int duration)
01492 {
01493    return gtalk_digit(chan, digit, duration);
01494 }
01495 
01496 static int gtalk_digit(struct ast_channel *ast, char digit, unsigned int duration)
01497 {
01498    struct gtalk_pvt *p = ast->tech_pvt;
01499    struct gtalk *client = p->parent;
01500    iks *iq, *gtalk, *dtmf;
01501    char buffer[2] = {digit, '\0'};
01502    iq = iks_new("iq");
01503    gtalk = iks_new("gtalk");
01504    dtmf = iks_new("dtmf");
01505    if(!iq || !gtalk || !dtmf) {
01506       if(iq)
01507          iks_delete(iq);
01508       if(gtalk)
01509          iks_delete(gtalk);
01510       if(dtmf)
01511          iks_delete(dtmf);
01512       ast_log(LOG_ERROR, "Did not send dtmf do to memory issue\n");
01513       return -1;
01514    }
01515 
01516    iks_insert_attrib(iq, "type", "set");
01517    iks_insert_attrib(iq, "to", p->them);
01518    iks_insert_attrib(iq, "from", p->us);
01519    iks_insert_attrib(iq, "id", client->connection->mid);
01520    ast_aji_increment_mid(client->connection->mid);
01521    iks_insert_attrib(gtalk, "xmlns", "http://jabber.org/protocol/gtalk");
01522    iks_insert_attrib(gtalk, "action", "session-info");
01523    iks_insert_attrib(gtalk, "initiator", p->initiator ? p->us: p->them);
01524    iks_insert_attrib(gtalk, "sid", p->sid);
01525    iks_insert_attrib(dtmf, "xmlns", "http://jabber.org/protocol/gtalk/info/dtmf");
01526    iks_insert_attrib(dtmf, "code", buffer);
01527    iks_insert_node(iq, gtalk);
01528    iks_insert_node(gtalk, dtmf);
01529 
01530    ast_mutex_lock(&p->lock);
01531    if (ast->dtmff.frametype == AST_FRAME_DTMF_BEGIN || duration == 0) {
01532       iks_insert_attrib(dtmf, "action", "button-down");
01533    } else if (ast->dtmff.frametype == AST_FRAME_DTMF_END || duration != 0) {
01534       iks_insert_attrib(dtmf, "action", "button-up");
01535    }
01536    iks_send(client->connection->p, iq);
01537    iks_delete(iq);
01538    iks_delete(gtalk);
01539    iks_delete(dtmf);
01540    ast_mutex_unlock(&p->lock);
01541    return 0;
01542 }
01543 
01544 static int gtalk_sendhtml(struct ast_channel *ast, int subclass, const char *data, int datalen)
01545 {
01546    ast_log(LOG_NOTICE, "XXX Implement gtalk sendhtml XXX\n");
01547 
01548    return -1;
01549 }
01550 
01551 /* Not in use right now.
01552 static int gtalk_auto_congest(void *nothing)
01553 {
01554    struct gtalk_pvt *p = nothing;
01555 
01556    ast_mutex_lock(&p->lock);
01557    if (p->owner) {
01558       if (!ast_channel_trylock(p->owner)) {
01559          ast_log(LOG_NOTICE, "Auto-congesting %s\n", p->owner->name);
01560          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
01561          ast_channel_unlock(p->owner);
01562       }
01563    }
01564    ast_mutex_unlock(&p->lock);
01565    return 0;
01566 }
01567 */
01568 
01569 /*! \brief Initiate new call, part of PBX interface 
01570  *    dest is the dial string */
01571 static int gtalk_call(struct ast_channel *ast, char *dest, int timeout)
01572 {
01573    struct gtalk_pvt *p = ast->tech_pvt;
01574 
01575    if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
01576       ast_log(LOG_WARNING, "gtalk_call called on %s, neither down nor reserved\n", ast->name);
01577       return -1;
01578    }
01579 
01580    ast_setstate(ast, AST_STATE_RING);
01581    if (!p->ringrule) {
01582       ast_copy_string(p->ring, p->parent->connection->mid, sizeof(p->ring));
01583       p->ringrule = iks_filter_add_rule(p->parent->connection->f, gtalk_ringing_ack, p,
01584                      IKS_RULE_ID, p->ring, IKS_RULE_DONE);
01585    } else
01586       ast_log(LOG_WARNING, "Whoa, already have a ring rule!\n");
01587 
01588    gtalk_invite(p, p->them, p->us, p->sid, 1);
01589    gtalk_create_candidates(p->parent, p, p->sid, p->them, p->us);
01590 
01591    return 0;
01592 }
01593 
01594 /*! \brief Hangup a call through the gtalk proxy channel */
01595 static int gtalk_hangup(struct ast_channel *ast)
01596 {
01597    struct gtalk_pvt *p = ast->tech_pvt;
01598    struct gtalk *client;
01599 
01600    ast_mutex_lock(&p->lock);
01601    client = p->parent;
01602    p->owner = NULL;
01603    ast->tech_pvt = NULL;
01604    if (!p->alreadygone)
01605       gtalk_action(client, p, "terminate");
01606    ast_mutex_unlock(&p->lock);
01607 
01608    gtalk_free_pvt(client, p);
01609    ast_module_unref(ast_module_info->self);
01610 
01611    return 0;
01612 }
01613 
01614 /*! \brief Part of PBX interface */
01615 static struct ast_channel *gtalk_request(const char *type, int format, void *data, int *cause)
01616 {
01617    struct gtalk_pvt *p = NULL;
01618    struct gtalk *client = NULL;
01619    char *sender = NULL, *to = NULL, *s = NULL;
01620    struct ast_channel *chan = NULL;
01621 
01622    if (data) {
01623       s = ast_strdupa(data);
01624       if (s) {
01625          sender = strsep(&s, "/");
01626          if (sender && (sender[0] != '\0'))
01627             to = strsep(&s, "/");
01628          if (!to) {
01629             ast_log(LOG_ERROR, "Bad arguments in Gtalk Dialstring: %s\n", (char*) data);
01630             return NULL;
01631          }
01632       }
01633    }
01634 
01635    client = find_gtalk(to, sender);
01636    if (!client) {
01637       ast_log(LOG_WARNING, "Could not find recipient.\n");
01638       return NULL;
01639    }
01640    if (!strcasecmp(client->name, "guest")){
01641       /* the guest account is not tied to any configured XMPP client,
01642          let's set it now */
01643       client->connection = ast_aji_get_client(sender);
01644       if (!client->connection) {
01645          ast_log(LOG_ERROR, "No XMPP client to talk to, us (partial JID) : %s\n", sender);
01646          ASTOBJ_UNREF(client, gtalk_member_destroy);
01647          return NULL;
01648       }
01649    }
01650 
01651    ASTOBJ_WRLOCK(client);
01652    p = gtalk_alloc(client, strchr(sender, '@') ? sender : client->connection->jid->full, strchr(to, '@') ? to : client->user, NULL);
01653    if (p)
01654       chan = gtalk_new(client, p, AST_STATE_DOWN, to);
01655 
01656    ASTOBJ_UNLOCK(client);
01657    return chan;
01658 }
01659 
01660 /*! \brief CLI command "gtalk show channels" */
01661 static int gtalk_show_channels(int fd, int argc, char **argv)
01662 {
01663 #define FORMAT  "%-30.30s  %-30.30s  %-15.15s  %-5.5s %-5.5s \n"
01664    struct gtalk_pvt *p;
01665    struct ast_channel *chan;
01666    int numchans = 0;
01667    char them[AJI_MAX_JIDLEN];
01668    char *jid = NULL;
01669    char *resource = NULL;
01670 
01671    if (argc != 3)
01672       return RESULT_SHOWUSAGE;
01673 
01674    ast_mutex_lock(&gtalklock);
01675    ast_cli(fd, FORMAT, "Channel", "Jabber ID", "Resource", "Read", "Write");
01676    ASTOBJ_CONTAINER_TRAVERSE(&gtalk_list, 1, {
01677       ASTOBJ_WRLOCK(iterator);
01678       p = iterator->p;
01679       while(p) {
01680          chan = p->owner;
01681          ast_copy_string(them, p->them, sizeof(them));
01682          jid = them;
01683          resource = strchr(them, '/');
01684          if (!resource)
01685             resource = "None";
01686          else {
01687             *resource = '\0';
01688             resource ++;
01689          }
01690          if (chan)
01691             ast_cli(fd, FORMAT, 
01692                chan->name,
01693                jid,
01694                resource,
01695                ast_getformatname(chan->readformat),
01696                ast_getformatname(chan->writeformat)               
01697                );
01698          else 
01699             ast_log(LOG_WARNING, "No available channel\n");
01700          numchans ++;
01701          p = p->next;
01702       }
01703       ASTOBJ_UNLOCK(iterator);
01704    });
01705 
01706    ast_mutex_unlock(&gtalklock);
01707 
01708    ast_cli(fd, "%d active gtalk channel%s\n", numchans, (numchans != 1) ? "s" : "");
01709    return RESULT_SUCCESS;
01710 #undef FORMAT
01711 }
01712 
01713 /*! \brief CLI command "gtalk show channels" */
01714 static int gtalk_do_reload(int fd, int argc, char **argv)
01715 {
01716    ast_verbose("IT DOES WORK!\n");
01717    return RESULT_SUCCESS;
01718 }
01719 
01720 static int gtalk_parser(void *data, ikspak *pak)
01721 {
01722    struct gtalk *client = ASTOBJ_REF((struct gtalk *) data);
01723 
01724    if (iks_find_with_attrib(pak->x, "session", "type", "initiate")) {
01725       /* New call */
01726       gtalk_newcall(client, pak);
01727    } else if (iks_find_with_attrib(pak->x, "session", "type", "candidates") || iks_find_with_attrib(pak->x, "session", "type", "transport-info")) {
01728       if (option_debug > 2)
01729          ast_log(LOG_DEBUG, "About to add candidate!\n");
01730       gtalk_add_candidate(client, pak);
01731       if (option_debug > 2)
01732          ast_log(LOG_DEBUG, "Candidate Added!\n");
01733    } else if (iks_find_with_attrib(pak->x, "session", "type", "accept")) {
01734       gtalk_is_answered(client, pak);
01735    } else if (iks_find_with_attrib(pak->x, "session", "type", "transport-accept")) {
01736       gtalk_is_accepted(client, pak);
01737    } else if (iks_find_with_attrib(pak->x, "session", "type", "content-info") || iks_find_with_attrib(pak->x, "gtalk", "action", "session-info")) {
01738       gtalk_handle_dtmf(client, pak);
01739    } else if (iks_find_with_attrib(pak->x, "session", "type", "terminate")) {
01740       gtalk_hangup_farend(client, pak);
01741    } else if (iks_find_with_attrib(pak->x, "session", "type", "reject")) {
01742       gtalk_hangup_farend(client, pak);
01743    }
01744    ASTOBJ_UNREF(client, gtalk_member_destroy);
01745    return IKS_FILTER_EAT;
01746 }
01747 
01748 /* Not using this anymore probably take out soon 
01749 static struct gtalk_candidate *gtalk_create_candidate(char *args)
01750 {
01751    char *name, *type, *preference, *protocol;
01752    struct gtalk_candidate *res;
01753    res = malloc(sizeof(struct gtalk_candidate));
01754    memset(res, 0, sizeof(struct gtalk_candidate));
01755    if (args)
01756       name = args;
01757    if ((args = strchr(args, ','))) {
01758       *args = '\0';
01759       args++;
01760       preference = args;
01761    }
01762    if ((args = strchr(args, ','))) {
01763       *args = '\0';
01764       args++;
01765       protocol = args;
01766    }
01767    if ((args = strchr(args, ','))) {
01768       *args = '\0';
01769       args++;
01770       type = args;
01771    }
01772    if (name)
01773       ast_copy_string(res->name, name, sizeof(res->name));
01774    if (preference) {
01775       res->preference = atof(preference);
01776    }
01777    if (protocol) {
01778       if (!strcasecmp("udp", protocol))
01779          res->protocol = AJI_PROTOCOL_UDP;
01780       if (!strcasecmp("ssltcp", protocol))
01781          res->protocol = AJI_PROTOCOL_SSLTCP;
01782    }
01783    if (type) {
01784       if (!strcasecmp("stun", type))
01785          res->type = AJI_CONNECT_STUN;
01786       if (!strcasecmp("local", type))
01787          res->type = AJI_CONNECT_LOCAL;
01788       if (!strcasecmp("relay", type))
01789          res->type = AJI_CONNECT_RELAY;
01790    }
01791 
01792    return res;
01793 }
01794 */
01795 
01796 static int gtalk_create_member(char *label, struct ast_variable *var, int allowguest,
01797                         struct ast_codec_pref prefs, char *context,
01798                         struct gtalk *member)
01799 {
01800    struct aji_client *client;
01801 
01802    if (!member)
01803       ast_log(LOG_WARNING, "Out of memory.\n");
01804 
01805    ast_copy_string(member->name, label, sizeof(member->name));
01806    ast_copy_string(member->user, label, sizeof(member->user));
01807    ast_copy_string(member->context, context, sizeof(member->context));
01808    member->allowguest = allowguest;
01809    member->prefs = prefs;
01810    while (var) {
01811 #if 0
01812       struct gtalk_candidate *candidate = NULL;
01813 #endif
01814       if (!strcasecmp(var->name, "username"))
01815          ast_copy_string(member->user, var->value, sizeof(member->user));
01816       else if (!strcasecmp(var->name, "disallow"))
01817          ast_parse_allow_disallow(&member->prefs, &member->capability, var->value, 0);
01818       else if (!strcasecmp(var->name, "allow"))
01819          ast_parse_allow_disallow(&member->prefs, &member->capability, var->value, 1);
01820       else if (!strcasecmp(var->name, "context"))
01821          ast_copy_string(member->context, var->value, sizeof(member->context));
01822 #if 0
01823       else if (!strcasecmp(var->name, "candidate")) {
01824          candidate = gtalk_create_candidate(var->value);
01825          if (candidate) {
01826             candidate->next = member->ourcandidates;
01827             member->ourcandidates = candidate;
01828          }
01829       }
01830 #endif
01831       else if (!strcasecmp(var->name, "connection")) {
01832          if ((client = ast_aji_get_client(var->value))) {
01833             member->connection = client;
01834             iks_filter_add_rule(client->f, gtalk_parser, member, 
01835                       IKS_RULE_TYPE, IKS_PAK_IQ, 
01836                       IKS_RULE_FROM_PARTIAL, member->user,
01837                       IKS_RULE_NS, "http://www.google.com/session",
01838                       IKS_RULE_DONE);
01839 
01840          } else {
01841             ast_log(LOG_ERROR, "connection referenced not found!\n");
01842             return 0;
01843          }
01844       }
01845       var = var->next;
01846    }
01847    if (member->connection && member->user)
01848       member->buddy = ASTOBJ_CONTAINER_FIND(&member->connection->buddies, member->user);
01849    else {
01850       ast_log(LOG_ERROR, "No Connection or Username!\n");
01851    }
01852    return 1;
01853 }
01854 
01855 static int gtalk_load_config(void)
01856 {
01857    char *cat = NULL;
01858    struct ast_config *cfg = NULL;
01859    char context[AST_MAX_CONTEXT];
01860    int allowguest = 1;
01861    struct ast_variable *var;
01862    struct gtalk *member;
01863    struct ast_codec_pref prefs;
01864    struct aji_client_container *clients;
01865    struct gtalk_candidate *global_candidates = NULL;
01866    struct hostent *hp;
01867    struct ast_hostent ahp;
01868 
01869    cfg = ast_config_load(GOOGLE_CONFIG);
01870    if (!cfg)
01871       return 0;
01872 
01873    /* Copy the default jb config over global_jbconf */
01874    memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
01875 
01876    cat = ast_category_browse(cfg, NULL);
01877    for (var = ast_variable_browse(cfg, "general"); var; var = var->next) {
01878       /* handle jb conf */
01879       if (!ast_jb_read_conf(&global_jbconf, var->name, var->value))
01880          continue;
01881 
01882       if (!strcasecmp(var->name, "allowguest"))
01883          allowguest =
01884             (ast_true(ast_variable_retrieve(cfg, "general", "allowguest"))) ? 1 : 0;
01885       else if (!strcasecmp(var->name, "disallow"))
01886          ast_parse_allow_disallow(&prefs, &global_capability, var->value, 0);
01887       else if (!strcasecmp(var->name, "allow"))
01888          ast_parse_allow_disallow(&prefs, &global_capability, var->value, 1);
01889       else if (!strcasecmp(var->name, "context"))
01890          ast_copy_string(context, var->value, sizeof(context));
01891       else if (!strcasecmp(var->name, "bindaddr")) {
01892          if (!(hp = ast_gethostbyname(var->value, &ahp))) {
01893             ast_log(LOG_WARNING, "Invalid address: %s\n", var->value);
01894          } else {
01895             memcpy(&bindaddr.sin_addr, hp->h_addr, sizeof(bindaddr.sin_addr));
01896          }
01897       }
01898 /*  Idea to allow for custom candidates  */
01899 /*
01900       else if (!strcasecmp(var->name, "candidate")) {
01901          candidate = gtalk_create_candidate(var->value);
01902          if (candidate) {
01903             candidate->next = global_candidates;
01904             global_candidates = candidate;
01905          }
01906       }
01907 */
01908    }
01909    while (cat) {
01910       if (strcasecmp(cat, "general")) {
01911          var = ast_variable_browse(cfg, cat);
01912          member = (struct gtalk *) malloc(sizeof(struct gtalk));
01913          memset(member, 0, sizeof(struct gtalk));
01914          ASTOBJ_INIT(member);
01915          ASTOBJ_WRLOCK(member);
01916          if (!strcasecmp(cat, "guest")) {
01917             ast_copy_string(member->name, "guest", sizeof(member->name));
01918             ast_copy_string(member->user, "guest", sizeof(member->user));
01919             ast_copy_string(member->context, context, sizeof(member->context));
01920             member->allowguest = allowguest;
01921             member->prefs = prefs;
01922             while (var) {
01923                if (!strcasecmp(var->name, "disallow"))
01924                   ast_parse_allow_disallow(&member->prefs, &member->capability,
01925                                      var->value, 0);
01926                else if (!strcasecmp(var->name, "allow"))
01927                   ast_parse_allow_disallow(&member->prefs, &member->capability,
01928                                      var->value, 1);
01929                else if (!strcasecmp(var->name, "context"))
01930                   ast_copy_string(member->context, var->value,
01931                               sizeof(member->context));
01932 /*  Idea to allow for custom candidates  */
01933 /*
01934                else if (!strcasecmp(var->name, "candidate")) {
01935                   candidate = gtalk_create_candidate(var->value);
01936                   if (candidate) {
01937                      candidate->next = member->ourcandidates;
01938                      member->ourcandidates = candidate;
01939                   }
01940                }
01941 */
01942                var = var->next;
01943             }
01944             ASTOBJ_UNLOCK(member);
01945             clients = ast_aji_get_clients();
01946             if (clients) {
01947                ASTOBJ_CONTAINER_TRAVERSE(clients, 1, {
01948                   ASTOBJ_WRLOCK(iterator);
01949                   ASTOBJ_WRLOCK(member);
01950                   member->connection = NULL;
01951                   iks_filter_add_rule(iterator->f, gtalk_parser, member, IKS_RULE_TYPE, IKS_PAK_IQ, IKS_RULE_NS, "http://www.google.com/session", IKS_RULE_DONE);
01952                   iks_filter_add_rule(iterator->f, gtalk_parser, member, IKS_RULE_TYPE, IKS_PAK_IQ, IKS_RULE_NS, "http://jabber.org/protocol/gtalk", IKS_RULE_DONE);
01953                   ASTOBJ_UNLOCK(member);
01954                   ASTOBJ_UNLOCK(iterator);
01955                });
01956                ASTOBJ_CONTAINER_LINK(&gtalk_list, member);
01957                ASTOBJ_UNREF(member, gtalk_member_destroy);
01958             } else {
01959                ASTOBJ_UNLOCK(member);
01960                ASTOBJ_UNREF(member, gtalk_member_destroy);
01961             }
01962          } else {
01963             ASTOBJ_UNLOCK(member);
01964             if (gtalk_create_member(cat, var, allowguest, prefs, context, member))
01965                ASTOBJ_CONTAINER_LINK(&gtalk_list, member);
01966             ASTOBJ_UNREF(member, gtalk_member_destroy);
01967          }
01968       }
01969       cat = ast_category_browse(cfg, cat);
01970    }
01971    gtalk_free_candidates(global_candidates);
01972    return 1;
01973 }
01974 
01975 /*! \brief Load module into PBX, register channel */
01976 static int load_module(void)
01977 {
01978    char *jabber_loaded = ast_module_helper("", "res_jabber.so", 0, 0, 0, 0);
01979    free(jabber_loaded);
01980    if (!jabber_loaded) {
01981       /* If embedded, check for a different module name */
01982       jabber_loaded = ast_module_helper("", "res_jabber", 0, 0, 0, 0);
01983       free(jabber_loaded);
01984       if (!jabber_loaded) {
01985          ast_log(LOG_ERROR, "chan_gtalk.so depends upon res_jabber.so\n");
01986          return AST_MODULE_LOAD_DECLINE;
01987       }
01988    }
01989 
01990 #ifdef HAVE_GNUTLS   
01991         gcry_control (GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread);
01992 #endif /* HAVE_GNUTLS */
01993 
01994    ASTOBJ_CONTAINER_INIT(&gtalk_list);
01995    if (!gtalk_load_config()) {
01996       ast_log(LOG_ERROR, "Unable to read config file %s. Not loading module.\n", GOOGLE_CONFIG);
01997       return 0;
01998    }
01999 
02000    sched = sched_context_create();
02001    if (!sched) 
02002       ast_log(LOG_WARNING, "Unable to create schedule context\n");
02003 
02004    io = io_context_create();
02005    if (!io) 
02006       ast_log(LOG_WARNING, "Unable to create I/O context\n");
02007 
02008    if (ast_find_ourip(&__ourip, bindaddr)) {
02009       ast_log(LOG_WARNING, "Unable to get own IP address, Gtalk disabled\n");
02010       return 0;
02011    }
02012 
02013    ast_rtp_proto_register(&gtalk_rtp);
02014    ast_cli_register_multiple(gtalk_cli, sizeof(gtalk_cli) / sizeof(gtalk_cli[0]));
02015 
02016    /* Make sure we can register our channel type */
02017    if (ast_channel_register(&gtalk_tech)) {
02018       ast_log(LOG_ERROR, "Unable to register channel class %s\n", gtalk_tech.type);
02019       return -1;
02020    }
02021    return 0;
02022 }
02023 
02024 /*! \brief Reload module */
02025 static int reload(void)
02026 {
02027    return 0;
02028 }
02029 
02030 /*! \brief Unload the gtalk channel from Asterisk */
02031 static int unload_module(void)
02032 {
02033    struct gtalk_pvt *privates = NULL;
02034    ast_cli_unregister_multiple(gtalk_cli, sizeof(gtalk_cli) / sizeof(gtalk_cli[0]));
02035    /* First, take us out of the channel loop */
02036    ast_channel_unregister(&gtalk_tech);
02037    ast_rtp_proto_unregister(&gtalk_rtp);
02038 
02039    if (!ast_mutex_lock(&gtalklock)) {
02040       /* Hangup all interfaces if they have an owner */
02041       ASTOBJ_CONTAINER_TRAVERSE(&gtalk_list, 1, {
02042          ASTOBJ_WRLOCK(iterator);
02043          privates = iterator->p;
02044          while(privates) {
02045             if (privates->owner)
02046                ast_softhangup(privates->owner, AST_SOFTHANGUP_APPUNLOAD);
02047             privates = privates->next;
02048          }
02049          iterator->p = NULL;
02050          ASTOBJ_UNLOCK(iterator);
02051       });
02052       ast_mutex_unlock(&gtalklock);
02053    } else {
02054       ast_log(LOG_WARNING, "Unable to lock the monitor\n");
02055       return -1;
02056    }
02057    ASTOBJ_CONTAINER_DESTROYALL(&gtalk_list, gtalk_member_destroy);
02058    ASTOBJ_CONTAINER_DESTROY(&gtalk_list);
02059    return 0;
02060 }
02061 
02062 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Gtalk Channel Driver",
02063       .load = load_module,
02064       .unload = unload_module,
02065       .reload = reload,
02066           );

Generated on Fri Jul 3 20:35:35 2009 for Asterisk - the Open Source PBX by  doxygen 1.5.9