security_events: Fix error caused by DTD validation error
[asterisk/asterisk.git] / res / res_pktccops.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 2009, Attila Domjan
5  *
6  * Attila Domjan <attila.domjan.hu@gmail.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*!\file
20  *
21  * \brief PacketCable COPS
22  * 
23  * \author Attila Domjan <attila.domjan.hu@gmail.com>
24  *
25  * \note 
26  * This module is an add-on to chan_mgcp. It adds support for the
27  * PacketCable MGCP variation called NCS. Res_pktccops implements COPS
28  * (RFC 2748), a protocol used to manage dynamic bandwith allocation in
29  * CMTS's (HFC gateways). When you use NCS, you need to talk COPS with
30  * the CMTS to complete the calls.
31  */
32
33 /*** MODULEINFO
34         <defaultenabled>no</defaultenabled>
35         <support_level>extended</support_level>
36  ***/
37
38 #include "asterisk.h"
39
40 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
41
42 #include <sys/types.h>
43 #include <sys/socket.h>
44 #include <fcntl.h>
45 #include <netdb.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <unistd.h>
49 #include <string.h>
50 #include <time.h>
51 #include <errno.h>
52 #include <arpa/inet.h>
53 #include <signal.h>
54
55 #include "asterisk/file.h"
56 #include "asterisk/logger.h"
57 #include "asterisk/channel.h"
58 #include "asterisk/config.h"
59 #include "asterisk/options.h"
60 #include "asterisk/pbx.h"
61 #include "asterisk/module.h"
62 #include "asterisk/cli.h"
63 #include "asterisk/lock.h"
64 #define AST_API_MODULE
65 #include "asterisk/pktccops.h"
66
67 #define DEFAULT_COPS_PORT "2126"
68
69 #define COPS_HEADER_SIZE 8
70 #define COPS_OBJECT_HEADER_SIZE 4
71 #define GATE_SET_OBJ_SIZE 144
72 #define GATEID_OBJ_SIZE 8
73 #define GATE_INFO_OBJ_SIZE 24
74
75 #define PKTCCOPS_SCOMMAND_GATE_ALLOC 1
76 #define PKTCCOPS_SCOMMAND_GATE_ALLOC_ACK 2
77 #define PKTCCOPS_SCOMMAND_GATE_ALLOC_ERR 3
78 #define PKTCCOPS_SCOMMAND_GATE_SET 4
79 #define PKTCCOPS_SCOMMAND_GATE_SET_ACK 5
80 #define PKTCCOPS_SCOMMAND_GATE_SET_ERR 6
81 #define PKTCCOPS_SCOMMAND_GATE_INFO 7
82 #define PKTCCOPS_SCOMMAND_GATE_INFO_ACK 8
83 #define PKTCCOPS_SCOMMAND_GATE_INFO_ERR 9
84 #define PKTCCOPS_SCOMMAND_GATE_DELETE 10
85 #define PKTCCOPS_SCOMMAND_GATE_DELETE_ACK 11
86 #define PKTCCOPS_SCOMMAND_GATE_DELETE_ERR 12
87 #define PKTCCOPS_SCOMMAND_GATE_OPEN 13
88 #define PKTCCOPS_SCOMMAND_GATE_CLOSE 14
89
90 AST_MUTEX_DEFINE_STATIC(pktccops_lock);
91 static pthread_t pktccops_thread = AST_PTHREADT_NULL;
92 static uint16_t cops_trid = 0;
93
94 struct pktcobj {
95         uint16_t length;
96         unsigned char cnum;
97         unsigned char ctype;
98         char *contents;
99         struct pktcobj *next; 
100 };
101
102 struct copsmsg {
103         unsigned char verflag;
104         unsigned char opcode;
105         uint16_t clienttype;
106         uint32_t length;
107         struct pktcobj *object;
108         char *msg; /* != NULL if not packet cable message received */
109 };
110
111 struct gatespec {
112         int direction; /* 0-DS, 1-US */
113         int protocolid;
114         int flags; /* 0x00 */
115         int sessionclass; /* normal voip: 0x01, high priority voip: 0x02, unspecified: 0x00 */
116         uint32_t srcip;
117         uint32_t dstip;
118         uint16_t srcp;
119         uint16_t dstp;
120         int diffserv;
121         uint16_t t1;
122         uint16_t t7;
123         uint16_t t8;
124         uint32_t r; /* Token Bucket Rate */
125         uint32_t b; /* token Bucket Size */
126         uint32_t p; /* Peak Data Rate */
127         uint32_t m; /* Minimum Policed Size*/
128         uint32_t mm; /* Maximum Policed Size */
129         uint32_t rate;
130         uint32_t s; /* Allowable Jitter*/
131 };
132
133
134 struct cops_cmts {
135         AST_LIST_ENTRY(cops_cmts) list;
136         char name[80];
137         char host[80];
138         char port[80];
139         uint16_t t1;    
140         uint16_t t7;
141         uint16_t t8;
142         uint32_t keepalive;
143
144         uint32_t handle;
145         int state;
146         time_t contime;
147         time_t katimer;
148         int sfd;
149         int need_delete;
150 };
151
152 struct cops_ippool {
153         AST_LIST_ENTRY(cops_ippool) list;
154         uint32_t start;
155         uint32_t stop;
156         struct cops_cmts *cmts;
157 };
158
159 static uint16_t t1 = 250;
160 static uint16_t t7 = 200;
161 static uint16_t t8 = 300;
162 static uint32_t keepalive = 60;
163 static int pktccopsdebug = 0;
164 static int pktcreload = 0;
165 static int gateinfoperiod = 60;
166 static int gatetimeout = 150;
167
168 AST_LIST_HEAD_STATIC(cmts_list, cops_cmts);
169 AST_LIST_HEAD_STATIC(ippool_list, cops_ippool);
170 AST_LIST_HEAD_STATIC(gate_list, cops_gate);
171
172 static int pktccops_add_ippool(struct cops_ippool *ippool);
173 static struct cops_gate *cops_gate_cmd(int cmd, struct cops_cmts *cmts, uint16_t trid, uint32_t mta, uint32_t actcount, float bitrate, uint32_t psize, uint32_t ssip, uint16_t ssport, struct cops_gate *gate);
174 static void pktccops_unregister_ippools(void);
175 static int load_pktccops_config(void);
176
177 static uint32_t ftoieeef(float n)
178 {
179         uint32_t res;
180         memcpy(&res, &n, 4);
181         return htonl(res);
182 }
183
184 static uint16_t cops_constructgatespec(struct gatespec *gs, char *res)
185 {
186         if (res == NULL) {
187                 return 0;
188         }
189         
190         *res = (char) gs->direction;
191         *(res + 1) = (char) gs->protocolid;
192         *(res + 2) = (char) gs->flags;
193         *(res + 3) = (char) gs->sessionclass;
194
195         *((uint32_t *) (res + 4)) = gs->srcip;
196         *((uint32_t *) (res + 8)) = gs->dstip;
197
198         *((uint16_t *) (res + 12)) = gs->srcp;
199         *((uint16_t *) (res + 14)) = gs->dstp;
200
201         *(res + 16) = (char) gs->diffserv;
202         *(res + 17) = 0; /* reserved */
203         *(res + 18) = 0; /* reserved */
204         *(res + 19) = 0; /* reserved */
205
206         *((uint16_t *) (res + 20)) = gs->t1;
207         *(res + 22) = 0; /* reserved */
208         *(res + 23) = 0; /* reserved */
209
210         *((uint16_t *) (res + 24)) = gs->t7;
211         *((uint16_t *) (res + 26)) = gs->t8;
212
213         *((uint32_t *) (res + 28)) = gs->r;
214         *((uint32_t *) (res + 32)) = gs->b;
215         *((uint32_t *) (res + 36)) = gs->p;
216         *((uint32_t *) (res + 40)) = gs->m;
217         *((uint32_t *) (res + 44)) = gs->mm;
218         *((uint32_t *) (res + 48)) = gs->rate;
219         *((uint32_t *) (res + 52)) = gs->s;
220         return 56; /* length */
221 };
222
223 static uint16_t cops_construct_gate (int cmd, char *p,  uint16_t trid,
224                 uint32_t mtahost, uint32_t actcount, float rate, uint32_t psizegateid,
225                 uint32_t ssip, uint16_t ssport, uint32_t gateid, struct cops_cmts *cmts)
226 {
227         struct gatespec gs;
228         int offset = 0;
229         
230         ast_debug(3, "CMD: %d\n", cmd);
231
232         /* Transaction Identifier 8 octets */
233         *(p + offset++) = 0;
234         *(p + offset++) = 8; /* length */
235         *(p + offset++) = 1; /* snum */
236         *(p + offset++) = 1; /* stype */
237         *((uint16_t *) (p + offset)) = htons(trid);
238         offset += 2;
239         *(p + offset++) = 0;
240         *(p + offset++) = (cmd == GATE_DEL) ? PKTCCOPS_SCOMMAND_GATE_DELETE : (cmd != GATE_INFO) ? PKTCCOPS_SCOMMAND_GATE_SET : PKTCCOPS_SCOMMAND_GATE_INFO; /* 4: GATE-SET, 7: GATE-INFO */
241
242         /*Subscriper Identifier 8 octets */
243         *(p + offset++) = 0;
244         *(p + offset++) = 8; /* length */
245         *(p + offset++) = 2; /* snum */
246         *(p + offset++) = 1; /* stype */
247         *((uint32_t *) (p + offset)) = htonl(mtahost);
248         offset += 4;
249         
250         if (cmd == GATE_INFO || cmd == GATE_SET_HAVE_GATEID || cmd == GATE_DEL) {
251                 /* Gate ID 8 Octets */
252                 *(p + offset++) = 0;
253                 *(p + offset++) = 8; /* length */
254                 *(p + offset++) = 3; /* snum */
255                 *(p + offset++) = 1; /* stype */
256                 *((uint32_t *) (p + offset)) = htonl(gateid);
257                 offset += 4;
258                 if (cmd == GATE_INFO || cmd == GATE_DEL) {
259                         return offset;
260                 }
261         
262         }
263
264         /* Activity Count 8 octets */
265         *(p + offset++) = 0;
266         *(p + offset++) = 8; /* length */
267         *(p + offset++) = 4; /* snum */
268         *(p + offset++) = 1; /* stype */
269         *((uint32_t *) (p + offset)) = htonl(actcount);
270         offset += 4;
271
272
273         /* Gate Spec 2*60 Octets */
274         gs.direction = 0; /* DS */
275         gs.protocolid = 17; /* UDP */
276         gs.flags = 0;
277         gs.sessionclass = 1;
278         gs.srcip = htonl(ssip);
279         gs.dstip = htonl(mtahost);
280         gs.srcp = htons(ssport);
281         gs.dstp = 0;
282 /*      gs.diffserv = 0xa0;*/
283         gs.diffserv = 0;
284         gs.t1 = htons(cmts->t1);
285         gs.t7 = htons(cmts->t7);
286         gs.t8 = htons(cmts->t8);
287         gs.r = ftoieeef(rate);
288         gs.b = ftoieeef(psizegateid);
289         gs.p = ftoieeef(rate);
290         gs.m = htonl((uint32_t) psizegateid);
291         gs.mm = htonl((uint32_t) psizegateid);
292         gs.rate = ftoieeef(rate);
293         gs.s = htonl(800);
294
295
296         *(p + offset) = 0;
297         offset++;
298         *(p + offset) = 60; /* length */
299         offset++;
300         *(p + offset) = 5; /* snum */
301         offset++;
302         *(p + offset) = 1; /* stype */
303         offset++;
304         offset += cops_constructgatespec(&gs, p + offset);
305
306
307         gs.direction = 1; /* US */
308         gs.srcip = htonl(mtahost);
309         gs.dstip = htonl(ssip);
310         gs.srcp = 0;
311         gs.dstp = htons(ssport);
312         *(p + offset) = 0;
313         offset++;
314         *(p + offset) = 60; /* length */
315         offset++;
316         *(p + offset) = 5; /* snum */
317         offset++;
318         *(p + offset) = 1; /* stype */
319         offset++;
320         offset += cops_constructgatespec(&gs, p + offset);
321
322         return(offset);
323 }
324
325 static int cops_getmsg (int sfd, struct copsmsg *recmsg)
326 {
327         int len, lent;
328         char buf[COPS_HEADER_SIZE];
329         struct pktcobj *pobject = NULL;
330         uint16_t *ubuf = (uint16_t *) buf;
331         recmsg->msg = NULL;
332         recmsg->object = NULL;
333         len = recv(sfd, buf, COPS_HEADER_SIZE, MSG_DONTWAIT);
334         if (len < COPS_HEADER_SIZE) {
335                 return len;
336         }
337         recmsg->verflag = *buf;
338         recmsg->opcode = *(buf + 1);
339         recmsg->clienttype = ntohs(*((uint16_t *) (buf + 2)));
340         recmsg->length = ntohl(*((uint32_t *) (buf + 4)));
341         /* Eg KA msg*/
342         if (recmsg->clienttype != 0x8008 ) {
343                 if (!(recmsg->msg = malloc(recmsg->length - COPS_HEADER_SIZE))) {
344                         return -1;
345                 }
346                 lent = recv(sfd, recmsg->msg, recmsg->length - COPS_HEADER_SIZE, MSG_DONTWAIT);
347                 if (lent < recmsg->length - COPS_HEADER_SIZE) {
348                         return lent;
349                 }
350                 len += len;
351         } else {
352                 /* PacketCable Objects */
353                 while (len < recmsg->length) {
354                         if (len == COPS_HEADER_SIZE) {
355                                 /* 1st round */
356                                 if (!(recmsg->object = malloc(sizeof(struct pktcobj)))) {
357                                         return -1;
358                                 }
359                                 pobject = recmsg->object;
360                         } else {
361                                 if (!(pobject->next = malloc(sizeof(struct pktcobj)))) {
362                                         return -1;
363                                 }
364                                 pobject = pobject->next;
365                         }
366                         pobject->next = NULL;
367                         lent = recv(sfd, buf, COPS_OBJECT_HEADER_SIZE, MSG_DONTWAIT);
368                         if (lent < COPS_OBJECT_HEADER_SIZE) {
369                                 ast_debug(3, "Too short object header len: %i\n", lent);
370                                 return lent;
371                         }
372                         len += lent;
373                         pobject->length = ntohs(*ubuf);
374                         pobject->cnum = *(buf + 2);
375                         pobject->ctype = *(buf + 3);
376                         if (!(pobject->contents = malloc(pobject->length - COPS_OBJECT_HEADER_SIZE))) {
377                                 return -1;
378                         }
379                         lent = recv(sfd, pobject->contents, pobject->length - COPS_OBJECT_HEADER_SIZE, MSG_DONTWAIT);
380                         if (lent < pobject->length - COPS_OBJECT_HEADER_SIZE) {
381                                 ast_debug(3, "Too short object content len: %i\n", lent);
382                                 return lent;
383                         }
384                         len += lent;
385                 }
386         }
387         return len;
388 }
389
390 static int cops_sendmsg (int sfd, struct copsmsg * sendmsg)
391 {
392         char *buf;
393         int bufpos;
394         struct pktcobj *pobject;
395         
396         if (sfd < 0) {
397                 return -1;
398         }
399
400         ast_debug(3, "COPS: sending opcode: %i len: %i\n", sendmsg->opcode, sendmsg->length);
401         if (sendmsg->length < COPS_HEADER_SIZE) {
402                 ast_log(LOG_WARNING, "COPS: invalid msg size!!!\n");
403                 return -1;
404         }
405         if (!(buf = malloc((size_t) sendmsg->length))) {
406                 return -1;
407         }
408         *buf = sendmsg->verflag ;
409         *(buf + 1) = sendmsg->opcode;
410         *((uint16_t *)(buf + 2)) = htons(sendmsg->clienttype);
411         *((uint32_t *)(buf + 4)) = htonl(sendmsg->length);
412
413         if (sendmsg->msg != NULL) {
414                 memcpy(buf + COPS_HEADER_SIZE, sendmsg->msg, sendmsg->length - COPS_HEADER_SIZE);
415         } else if (sendmsg->object != NULL) {
416                 bufpos = 8;
417                 pobject = sendmsg->object;
418                 while(pobject != NULL) {
419                         ast_debug(3, "COPS: Sending Object : cnum: %i ctype %i len: %i\n", pobject->cnum, pobject->ctype, pobject->length);
420                         if (sendmsg->length < bufpos + pobject->length) {
421                                 ast_log(LOG_WARNING, "COPS: Invalid msg size len: %i objectlen: %i\n", sendmsg->length, pobject->length);
422                                 free(buf);
423                                 return -1;
424                         }
425                         *(uint16_t *) (buf + bufpos) = htons(pobject->length);
426                         *(buf + bufpos + 2) = pobject->cnum;
427                         *(buf + bufpos + 3) = pobject->ctype;
428                         if (sendmsg->length < pobject->length + bufpos) {
429                                 ast_log(LOG_WARNING, "COPS: Error sum of object len more the msg len %i < %i\n", sendmsg->length, pobject->length + bufpos);
430                                 free(buf);
431                                 return -1;
432                         }
433                         memcpy((buf + bufpos + 4), pobject->contents, pobject->length - 4);
434                         bufpos += pobject->length;
435                         pobject = pobject->next;
436                 }
437         }
438         
439         errno = 0;
440 #ifdef HAVE_MSG_NOSIGNAL
441 #define SENDFLAGS       MSG_NOSIGNAL | MSG_DONTWAIT
442 #else
443 #define SENDFLAGS       MSG_DONTWAIT
444 #endif
445         if (send(sfd, buf, sendmsg->length, SENDFLAGS) == -1) {
446                 ast_log(LOG_WARNING, "COPS: Send failed errno=%i\n", errno);
447                 free(buf);
448                 return -2;
449         }
450 #undef SENDFLAGS
451         free(buf);
452         return 0;
453 }
454
455 static void cops_freemsg(struct copsmsg *p)
456 {
457         struct pktcobj *pnext;
458         free(p->msg);
459         p->msg = NULL;
460         while (p->object != NULL) {
461                         pnext = p->object->next;
462                         ast_free(p->object->contents);
463                         p->object->contents = NULL;
464                         ast_free(p->object);
465                         p->object = pnext;
466         }
467         p->object = NULL;
468 }
469
470 struct cops_gate * AST_OPTIONAL_API_NAME(ast_pktccops_gate_alloc)(int cmd,
471                 struct cops_gate *gate, uint32_t mta, uint32_t actcount, float bitrate,
472                 uint32_t psize, uint32_t ssip, uint16_t ssport,
473                 int (* const got_dq_gi) (struct cops_gate *gate),
474                 int (* const gate_remove) (struct cops_gate *gate))
475 {
476         while (pktcreload) {
477                 sched_yield();
478         }
479
480         if (cmd == GATE_SET_HAVE_GATEID && gate) {
481                 ast_debug(3, "------- gate modify gateid 0x%x ssip: 0x%x\n", gate->gateid, ssip);
482                 /* TODO implement it */
483                 ast_log(LOG_WARNING, "Modify GateID not implemented\n");
484         } 
485         
486         if ((gate = cops_gate_cmd(cmd, NULL, cops_trid++, mta, actcount, bitrate, psize, ssip, ssport, gate))) {
487                 ast_debug(3, "COPS: Allocating gate for mta: 0x%x\n", mta);
488                 gate->got_dq_gi = got_dq_gi;
489                 gate->gate_remove = gate_remove;
490                 return(gate);
491         } else {
492                 ast_debug(3, "COPS: Couldn't allocate gate for mta: 0x%x\n", mta); 
493                 return NULL;
494         }
495 }
496
497 static struct cops_gate *cops_gate_cmd(int cmd, struct cops_cmts *cmts,
498                 uint16_t trid, uint32_t mta, uint32_t actcount, float bitrate,
499                 uint32_t psize, uint32_t ssip, uint16_t ssport, struct cops_gate *gate)
500 {
501         struct copsmsg *gateset;
502         struct cops_gate *new;
503         struct cops_ippool *ippool;
504
505         if (cmd == GATE_DEL) {
506                 if (gate == NULL) {
507                         return NULL;
508                 } else {
509                         cmts = gate->cmts;
510                 }
511         }
512
513         if (!cmts) {
514                 AST_LIST_LOCK(&ippool_list);
515                 AST_LIST_TRAVERSE(&ippool_list, ippool, list) {
516                         if (mta >= ippool->start && mta <= ippool->stop) {
517                                 cmts = ippool->cmts;
518                                 break;
519                         }
520                 }
521                 AST_LIST_UNLOCK(&ippool_list);
522                 if (!cmts) {
523                         ast_log(LOG_WARNING, "COPS: couldn't find cmts for mta: 0x%x\n", mta);
524                         return NULL;
525                 }
526                 if (cmts->sfd < 0) {
527                         ast_log(LOG_WARNING, "CMTS: %s not connected\n", cmts->name);
528                         return NULL;
529                 }
530         }
531
532         if (cmd == GATE_SET) {
533                 new = ast_calloc(1, sizeof(*new));
534                 new->gateid = 0;
535                 new->trid = trid;
536                 new->mta = mta;
537                 new->state = GATE_ALLOC_PROGRESS;
538                 new->checked = time(NULL);
539                 new->allocated = time(NULL);
540                 new->cmts = cmts;
541                 new->got_dq_gi = NULL;
542                 new->gate_remove = NULL;
543                 new->gate_open = NULL;
544                 new->tech_pvt = NULL;
545                 new->deltimer = 0;
546                 AST_LIST_LOCK(&gate_list);
547                 AST_LIST_INSERT_HEAD(&gate_list, new, list);
548                 AST_LIST_UNLOCK(&gate_list);
549                 gate = new;
550         } else {
551                 if (gate) {
552                         gate->trid = trid;
553                 }
554         }
555         
556         gate->in_transaction = time(NULL);
557
558         if (!(gateset = malloc(sizeof(struct copsmsg)))) {
559                 free(gateset);
560                 return NULL;
561         }
562         gateset->msg = NULL;
563         gateset->verflag = 0x10;
564         gateset->opcode = 2; /* Decision */
565         gateset->clienttype = 0x8008; /* =PacketCable */
566         
567         /* Handle object */
568         gateset->object = malloc(sizeof(struct pktcobj));
569         if (!gateset->object) {
570                 cops_freemsg(gateset);
571                 free(gateset);
572                 return NULL;
573         }
574         gateset->object->length = COPS_OBJECT_HEADER_SIZE + 4;
575         gateset->object->cnum = 1; /* Handle */
576         gateset->object->ctype = 1; /* client */
577         if (!(gateset->object->contents = malloc(sizeof(uint32_t)))) {
578                 cops_freemsg(gateset);
579                 free(gateset);
580                 return NULL;
581         }
582         *((uint32_t *) gateset->object->contents) = htonl(cmts->handle);
583
584         /* Context Object */
585         if (!(gateset->object->next = malloc(sizeof(struct pktcobj)))) {
586                 cops_freemsg(gateset);
587                 free(gateset);
588                 return NULL;
589         }
590         gateset->object->next->length = COPS_OBJECT_HEADER_SIZE + 4;
591         gateset->object->next->cnum = 2; /* Context */
592         gateset->object->next->ctype = 1; /* Context */
593         if (!(gateset->object->next->contents = malloc(sizeof(uint32_t)))) {
594                 cops_freemsg(gateset);
595                 free(gateset);
596                 return NULL;
597         }
598         *((uint32_t *) gateset->object->next->contents) = htonl(0x00080000); /* R-Type = 8 configuration request, M-Type = 0 */
599
600         /* Decision Object: Flags */
601         if (!(gateset->object->next->next = malloc(sizeof(struct pktcobj)))) {
602                 cops_freemsg(gateset);
603                 free(gateset);
604                 return NULL;
605         }
606         gateset->object->next->next->length = COPS_OBJECT_HEADER_SIZE + 4;
607         gateset->object->next->next->cnum = 6; /* Decision */
608         gateset->object->next->next->ctype = 1; /* Flags */
609         if (!(gateset->object->next->next->contents = malloc(sizeof(uint32_t)))) {
610                 cops_freemsg(gateset);
611                 free(gateset);
612                 return NULL;
613         }
614         *((uint32_t *) gateset->object->next->next->contents) = htonl(0x00010001); /* Install, Trigger Error */
615
616         /* Decision Object: Data */
617         if (!(gateset->object->next->next->next = malloc(sizeof(struct pktcobj)))) {
618                 cops_freemsg(gateset);
619                 free(gateset);
620                 return NULL;
621         }
622         gateset->object->next->next->next->length = COPS_OBJECT_HEADER_SIZE + ((cmd != GATE_INFO && cmd != GATE_DEL) ? GATE_SET_OBJ_SIZE : GATE_INFO_OBJ_SIZE) + ((cmd == GATE_SET_HAVE_GATEID) ? GATEID_OBJ_SIZE : 0);
623         gateset->object->next->next->next->cnum = 6; /* Decision */
624         gateset->object->next->next->next->ctype = 4; /* Decision Data */
625         gateset->object->next->next->next->contents = malloc(((cmd != GATE_INFO && cmd != GATE_DEL) ? GATE_SET_OBJ_SIZE : GATE_INFO_OBJ_SIZE) + ((cmd == GATE_SET_HAVE_GATEID) ? GATEID_OBJ_SIZE : 0));
626         if (!gateset->object->next->next->next->contents) {
627                 cops_freemsg(gateset);
628                 free(gateset);
629                 return NULL;
630         }
631         gateset->object->next->next->next->next = NULL;
632         
633         gateset->length = COPS_HEADER_SIZE + gateset->object->length + gateset->object->next->length + gateset->object->next->next->length + gateset->object->next->next->next->length;
634
635         if ((cmd == GATE_INFO || cmd == GATE_SET_HAVE_GATEID || cmd == GATE_DEL) && gate) {
636                 ast_debug(1, "Construct gate with gateid: 0x%x\n", gate->gateid);
637                 cops_construct_gate(cmd, gateset->object->next->next->next->contents, trid, mta, actcount, bitrate, psize, ssip, ssport, gate->gateid, cmts);
638         } else {
639                 ast_debug(1, "Construct new gate\n");
640                 cops_construct_gate(cmd, gateset->object->next->next->next->contents, trid, mta, actcount, bitrate, psize, ssip, ssport, 0, cmts);
641         }
642         if (pktccopsdebug) {
643                 ast_debug(3, "send cmd\n");
644         }
645         cops_sendmsg(cmts->sfd, gateset);
646         cops_freemsg(gateset);
647         free(gateset);
648         return gate;
649 }
650
651 static int cops_connect(char *host, char *port)
652 {
653         int s, sfd = -1, flags;
654         struct addrinfo hints;
655         struct addrinfo *rp;
656         struct addrinfo *result;
657 #ifdef HAVE_SO_NOSIGPIPE
658         int trueval = 1;
659 #endif
660
661         memset(&hints, 0, sizeof(struct addrinfo));
662
663         hints.ai_family = AF_UNSPEC;    
664         hints.ai_socktype = SOCK_STREAM;
665         hints.ai_flags = 0;
666         hints.ai_protocol = 0;
667
668         s = getaddrinfo(host, port, &hints, &result);
669         if (s != 0) {
670                 ast_log(LOG_WARNING, "COPS: getaddrinfo: %s\n", gai_strerror(s));
671                 return -1;
672         }
673
674         for (rp = result; rp != NULL; rp = rp->ai_next) {
675                 sfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
676                 if (sfd == -1) {
677                         ast_log(LOG_WARNING, "Failed socket\n");
678                 }
679                 flags = fcntl(sfd, F_GETFL);
680                 fcntl(sfd, F_SETFL, flags | O_NONBLOCK);
681 #ifdef HAVE_SO_NOSIGPIPE
682                 setsockopt(sfd, SOL_SOCKET, SO_NOSIGPIPE, &trueval, sizeof(trueval));
683 #endif
684                 connect(sfd, rp->ai_addr, rp->ai_addrlen);
685                 if (sfd == -1) {
686                         ast_log(LOG_WARNING, "Failed connect\n");
687                 }
688         }
689         freeaddrinfo(result);
690
691         ast_debug(3, "Connecting to cmts:  %s:%s\n", host, port);
692         return(sfd);
693 }
694
695 #define PKTCCOPS_DESTROY_CURRENT_GATE   \
696                 AST_LIST_REMOVE_CURRENT(list);  \
697                 if (gate->gate_remove) {        \
698                         gate->gate_remove(gate);    \
699                 }                               \
700                 ast_free(gate);
701
702 static void *do_pktccops(void *data)
703 {
704         int res, nfds, len;
705         struct copsmsg *recmsg, *sendmsg;
706         struct copsmsg recmsgb, sendmsgb;
707         struct pollfd *pfds = NULL, *tmp;
708         struct pktcobj *pobject;
709         struct cops_cmts *cmts;
710         struct cops_gate *gate;
711         char *sobjp;
712         uint16_t snst, sobjlen, scommand, recvtrid, actcount, reason, subreason;
713         uint32_t gateid, subscrid, pktcerror;
714         time_t last_exec = 0;
715
716         recmsg = &recmsgb;
717         sendmsg = &sendmsgb;
718
719         ast_debug(3, "COPS: thread started\n");
720
721         for (;;) {
722                 ast_free(pfds);
723                 pfds = NULL;
724                 nfds = 0;
725                 AST_LIST_LOCK(&cmts_list);
726                 AST_LIST_TRAVERSE(&cmts_list, cmts, list) {
727                         if (last_exec != time(NULL)) {
728                                 if (cmts->state == 2 && cmts->katimer + cmts->keepalive < time(NULL)) {
729                                         ast_log(LOG_WARNING, "KA timer (%is) expired cmts: %s\n",  cmts->keepalive, cmts->name);
730                                         cmts->state = 0;
731                                         cmts->katimer = -1;
732                                         close(cmts->sfd);
733                                         cmts->sfd = -1;
734                                 }
735                         }
736                         if (cmts->sfd > 0) {
737                                 if (!(tmp = ast_realloc(pfds, (nfds + 1) * sizeof(*pfds)))) {
738                                         continue;
739                                 }
740                                 pfds = tmp;
741                                 pfds[nfds].fd = cmts->sfd;
742                                 pfds[nfds].events = POLLIN;
743                                 pfds[nfds].revents = 0;
744                                 nfds++;
745                         } else {
746                                 cmts->sfd = cops_connect(cmts->host, cmts->port);
747                                 if (cmts->sfd > 0) {
748                                         cmts->state = 1;
749                                         if (cmts->sfd > 0) {
750                                                 if (!(tmp = ast_realloc(pfds, (nfds + 1) * sizeof(*pfds)))) {
751                                                         continue;
752                                                 }
753                                                 pfds = tmp;
754                                                 pfds[nfds].fd = cmts->sfd;
755                                                 pfds[nfds].events = POLLIN;
756                                                 pfds[nfds].revents = 0;
757                                                 nfds++;
758                                         }
759                                 }
760                         }
761                 }
762                 AST_LIST_UNLOCK(&cmts_list);
763
764                 if (last_exec != time(NULL)) {
765                         last_exec = time(NULL);
766                         AST_LIST_LOCK(&gate_list);
767                         AST_LIST_TRAVERSE_SAFE_BEGIN(&gate_list, gate, list) {
768                                 if (gate) {
769                                         if (gate->deltimer && gate->deltimer < time(NULL)) {
770                                                 gate->deltimer = time(NULL) + 5;
771                                                 gate->trid = cops_trid++;
772                                                 cops_gate_cmd(GATE_DEL, gate->cmts, gate->trid, 0, 0, 0, 0, 0, 0, gate);
773                                                 ast_debug(3, "COPS: requested Gate-Del: CMTS: %s gateid: 0x%x\n", (gate->cmts) ? gate->cmts->name : "null", gate->gateid);
774                                         }
775                                         if (time(NULL) - gate->checked > gatetimeout) {
776                                                 ast_debug(3, "COPS: remove from list GATE, CMTS: %s gateid: 0x%x\n", (gate->cmts) ? gate->cmts->name : "null", gate->gateid);
777                                                 gate->state = GATE_TIMEOUT;
778                                                 PKTCCOPS_DESTROY_CURRENT_GATE;
779                                         } else if (time(NULL) - gate->checked > gateinfoperiod && (gate->state == GATE_ALLOCATED || gate->state == GATE_OPEN)) {
780                                                 if (gate->cmts && (!gate->in_transaction || ( gate->in_transaction + 5 ) < time(NULL))) {
781                                                         gate->trid = cops_trid++;
782                                                         ast_debug(3, "COPS: Gate-Info send to CMTS: %s gateid: 0x%x\n", gate->cmts->name, gate->gateid);
783                                                         cops_gate_cmd(GATE_INFO, gate->cmts, gate->trid, gate->mta, 0, 0, 0, 0, 0, gate);
784                                                 }
785                                         }
786                                 }
787                         }
788                         AST_LIST_TRAVERSE_SAFE_END;
789                         AST_LIST_UNLOCK(&gate_list);
790                 }
791
792                 if (pktcreload == 2) {
793                         pktcreload = 0;
794                 }
795                 if ((res = ast_poll(pfds, nfds, 1000))) {
796                         AST_LIST_LOCK(&cmts_list);
797                         AST_LIST_TRAVERSE(&cmts_list, cmts, list) {
798                                 int idx;
799                                 if ((idx = ast_poll_fd_index(pfds, nfds, cmts->sfd)) > -1 && (pfds[idx].revents & POLLIN)) {
800                                         len = cops_getmsg(cmts->sfd, recmsg);
801                                         if (len > 0) {
802                                                 ast_debug(3, "COPS: got from %s:\n Header: versflag=0x%.2x opcode=%i clienttype=0x%.4x msglength=%i\n",
803                                                         cmts->name, recmsg->verflag, recmsg->opcode, recmsg->clienttype, recmsg->length);
804                                                 if (recmsg->object != NULL) {
805                                                         pobject = recmsg->object;
806                                                         while (pobject != NULL) {
807                                                                 ast_debug(3, " OBJECT: length=%i cnum=%i ctype=%i\n", pobject->length, pobject->cnum, pobject->ctype);
808                                                                 if (recmsg->opcode == 1 && pobject->cnum == 1 && pobject->ctype == 1 ) {
809                                                                         cmts->handle = ntohl(*((uint32_t *) pobject->contents));
810                                                                         ast_debug(3, "    REQ client handle: %i\n", cmts->handle);
811                                                                         cmts->state = 2;
812                                                                         cmts->katimer = time(NULL);
813                                                                 } else if (pobject->cnum == 9 && pobject->ctype == 1) {
814                                                                         sobjp = pobject->contents;
815                                                                         subscrid = 0;
816                                                                         recvtrid = 0;
817                                                                         scommand = 0;
818                                                                         pktcerror = 0;
819                                                                         actcount = 0;
820                                                                         gateid = 0;
821                                                                         reason = 0;
822                                                                         subreason = 0;
823                                                                         while (sobjp < (pobject->contents + pobject->length - 4)) {
824                                                                                 sobjlen = ntohs(*((uint16_t *) sobjp));
825                                                                                 snst = ntohs(*((uint16_t *) (sobjp + 2)));
826                                                                                 ast_debug(3, "   S-Num S-type: 0x%.4x len: %i\n", snst, sobjlen);
827                                                                                 if (snst == 0x0101 ) {
828                                                                                         recvtrid = ntohs(*((uint16_t *) (sobjp + 4)));
829                                                                                         scommand = ntohs(*((uint16_t *) (sobjp + 6)));                                  
830                                                                                         ast_debug(3, "     Transaction Identifier command: %i trid %i\n", scommand, recvtrid);
831                                                                                 } else if (snst == 0x0201) {
832                                                                                         subscrid = ntohl(*((uint32_t *) (sobjp + 4)));
833                                                                                         ast_debug(3, "     Subscriber ID: 0x%.8x\n", subscrid);
834                                                                                 } else if (snst == 0x0301) {
835                                                                                         gateid = ntohl(*((uint32_t *) (sobjp + 4)));
836                                                                                         ast_debug(3, "      Gate ID: 0x%x 0x%.8x\n", gateid, gateid);
837                                                                                 } else if (snst == 0x0401) {
838                                                                                         actcount = ntohs(*((uint16_t *) (sobjp + 6)));
839                                                                                         ast_debug(3, "      Activity Count: %i\n", actcount);
840                                                                                 } else if (snst == 0x0901) {
841                                                                                         pktcerror = ntohl(*((uint32_t *) (sobjp + 4)));
842                                                                                         ast_debug(3, "      PKTC Error: 0x%.8x\n", pktcerror);
843                                                                                 } else if (snst == 0x0d01) {
844                                                                                         reason = ntohs(*((uint16_t *) (sobjp + 4)));
845                                                                                         subreason = ntohs(*((uint16_t *) (sobjp + 6)));
846                                                                                         ast_debug(3, "      Reason: %u Subreason: %u\n", reason, subreason);
847                                                                                 }
848                                                                                 sobjp += sobjlen;
849                                                                                 if (!sobjlen)
850                                                                                         break;
851                                                                         }
852                                                                         if (scommand == PKTCCOPS_SCOMMAND_GATE_CLOSE || scommand == PKTCCOPS_SCOMMAND_GATE_OPEN) {
853                                                                                 AST_LIST_LOCK(&gate_list);
854                                                                                 AST_LIST_TRAVERSE_SAFE_BEGIN(&gate_list, gate, list) {
855                                                                                         if (gate->cmts == cmts && gate->gateid == gateid) {
856                                                                                                 if (scommand == PKTCCOPS_SCOMMAND_GATE_CLOSE && gate->state != GATE_CLOSED && gate->state != GATE_CLOSED_ERR ) {
857                                                                                                         ast_debug(3, "COPS Gate Close Gate ID: 0x%x TrId: %i CMTS: %s\n", gateid, recvtrid, cmts->name);
858                                                                                                         if (subreason) {
859                                                                                                                 gate->state = GATE_CLOSED_ERR;
860                                                                                                                 PKTCCOPS_DESTROY_CURRENT_GATE;
861                                                                                                         } else {
862                                                                                                                 gate->state = GATE_CLOSED;
863                                                                                                                 PKTCCOPS_DESTROY_CURRENT_GATE;
864                                                                                                         }
865                                                                                                         break;
866                                                                                                 } else if (scommand == PKTCCOPS_SCOMMAND_GATE_OPEN && gate->state == GATE_ALLOCATED) {
867                                                                                                         ast_debug(3, "COPS Gate Open Gate ID: 0x%x TrId: %i CMTS: %s\n", gateid, recvtrid, cmts->name);
868                                                                                                         gate->state = GATE_OPEN;
869                                                                                                         if (gate->gate_open) {
870                                                                                                                 ast_debug(3, "Calling GATE-OPEN callback function\n");
871                                                                                                                 gate->gate_open(gate);
872                                                                                                                 gate->gate_open = NULL;
873                                                                                                         }
874                                                                                                         break;
875                                                                                                 } 
876                                                                                         }
877                                                                                 }
878                                                                                 AST_LIST_TRAVERSE_SAFE_END;
879                                                                                 AST_LIST_UNLOCK(&gate_list);
880                                                                         } else if (scommand == PKTCCOPS_SCOMMAND_GATE_SET_ACK || scommand == PKTCCOPS_SCOMMAND_GATE_SET_ERR || scommand == PKTCCOPS_SCOMMAND_GATE_INFO_ACK || scommand == PKTCCOPS_SCOMMAND_GATE_INFO_ERR || scommand == PKTCCOPS_SCOMMAND_GATE_DELETE_ACK) {
881                                                                                 AST_LIST_LOCK(&gate_list);
882                                                                                 AST_LIST_TRAVERSE_SAFE_BEGIN(&gate_list, gate, list) {
883                                                                                         if (gate->cmts == cmts && gate->trid == recvtrid) {
884                                                                                                 gate->gateid = gateid;
885                                                                                                 gate->checked = time(NULL);
886                                                                                                 if (scommand == PKTCCOPS_SCOMMAND_GATE_SET_ACK) {
887                                                                                                         ast_debug(3, "COPS Gate Set Ack Gate ID: 0x%x TrId: %i CMTS: %s\n", gateid, recvtrid, cmts->name);
888                                                                                                         gate->state = GATE_ALLOCATED;
889                                                                                                         if (gate->got_dq_gi) {
890                                                                                                                 gate->got_dq_gi(gate);
891                                                                                                                 gate->got_dq_gi = NULL;
892                                                                                                         }
893                                                                                                 } else if (scommand == PKTCCOPS_SCOMMAND_GATE_SET_ERR) {
894                                                                                                         ast_debug(3, "COPS Gate Set Error TrId: %i ErrorCode: 0x%.8x CMTS: %s\n ", recvtrid, pktcerror, cmts->name);
895                                                                                                         gate->state = GATE_ALLOC_FAILED;
896                                                                                                         if (gate->got_dq_gi) {
897                                                                                                                 gate->got_dq_gi(gate);
898                                                                                                                 gate->got_dq_gi = NULL;
899                                                                                                         }
900                                                                                                         PKTCCOPS_DESTROY_CURRENT_GATE;
901                                                                                                 } else if (scommand == PKTCCOPS_SCOMMAND_GATE_INFO_ACK) {
902                                                                                                         ast_debug(3, "COPS Gate Info Ack Gate ID: 0x%x TrId: %i CMTS: %s\n", gateid, recvtrid, cmts->name);
903                                                                                                 } else if (scommand == PKTCCOPS_SCOMMAND_GATE_INFO_ERR) {
904                                                                                                         ast_debug(3, "COPS Gate Info Error Gate ID: 0x%x TrId: %i CMTS: %s\n", gateid, recvtrid, cmts->name);
905                                                                                                         gate->state = GATE_ALLOC_FAILED;
906                                                                                                         PKTCCOPS_DESTROY_CURRENT_GATE;
907                                                                                                 } else if (scommand == PKTCCOPS_SCOMMAND_GATE_DELETE_ACK) {
908                                                                                                         ast_debug(3, "COPS Gate Deleted Gate ID: 0x%x TrId: %i CMTS: %s\n", gateid, recvtrid, cmts->name);
909                                                                                                         gate->state = GATE_DELETED;
910                                                                                                         PKTCCOPS_DESTROY_CURRENT_GATE;
911                                                                                                 }
912                                                                                                 gate->in_transaction = 0;
913                                                                                                 break;
914                                                                                         }
915                                                                                 }
916                                                                                 AST_LIST_TRAVERSE_SAFE_END;
917                                                                                 AST_LIST_UNLOCK(&gate_list);
918                                                                         }
919                                                                 }
920                                                                 pobject = pobject->next;
921                                                         }
922                                                 }
923
924                                                 if (recmsg->opcode == 6 && recmsg->object && recmsg->object->cnum == 11 && recmsg->object->ctype == 1) {
925                                                         ast_debug(3, "COPS: Client open %s\n", cmts->name);
926                                                         sendmsg->msg = NULL;
927                                                         sendmsg->verflag = 0x10;
928                                                         sendmsg->opcode = 7; /* Client Accept */
929                                                         sendmsg->clienttype = 0x8008; /* =PacketCable */
930                                                         sendmsg->length = COPS_HEADER_SIZE + COPS_OBJECT_HEADER_SIZE + 4;
931                                                         sendmsg->object = malloc(sizeof(struct pktcobj));
932                                                         sendmsg->object->length = 4 + COPS_OBJECT_HEADER_SIZE;
933                                                         sendmsg->object->cnum = 10; /* keppalive timer*/
934                                                         sendmsg->object->ctype = 1;
935                                                         sendmsg->object->contents = malloc(sizeof(uint32_t));
936                                                         *((uint32_t *) sendmsg->object->contents) = htonl(cmts->keepalive & 0x0000ffff);
937                                                         sendmsg->object->next = NULL;
938                                                         cops_sendmsg(cmts->sfd, sendmsg);
939                                                         cops_freemsg(sendmsg);
940                                                 } else if (recmsg->opcode == 9) {
941                                                         ast_debug(3, "COPS: Keepalive Request got echoing back %s\n", cmts->name);
942                                                         cops_sendmsg(cmts->sfd, recmsg);
943                                                         cmts->state = 2;
944                                                         cmts->katimer = time(NULL);
945                                                 }
946                                         } 
947                                         if (len <= 0) {
948                                                 ast_debug(3, "COPS: lost connection to %s\n", cmts->name);
949                                                 close(cmts->sfd);
950                                                 cmts->sfd = -1;
951                                                 cmts->state = 0;
952                                         }
953                                         cops_freemsg(recmsg);
954                                 }
955                         }
956                         AST_LIST_UNLOCK(&cmts_list);                    
957                 }
958                 if (pktcreload) {
959                         ast_debug(3, "Reloading pktccops...\n");
960                         AST_LIST_LOCK(&gate_list);
961                         AST_LIST_LOCK(&cmts_list);
962                         pktccops_unregister_ippools();
963                         AST_LIST_TRAVERSE(&cmts_list, cmts, list) {
964                                 cmts->need_delete = 1;
965                         }
966                         load_pktccops_config();
967                         AST_LIST_TRAVERSE_SAFE_BEGIN(&cmts_list, cmts, list) {
968                                 if (cmts && cmts->need_delete) {
969                                         AST_LIST_TRAVERSE(&gate_list, gate, list) {
970                                                 if (gate->cmts == cmts) {
971                                                         ast_debug(3, "Null gate %s\n", gate->cmts->name);
972                                                         gate->cmts = NULL;
973                                                 }
974                                                 gate->in_transaction = 0;
975                                         }
976                                         AST_LIST_UNLOCK(&gate_list);
977                                         ast_debug(3, "removing cmts: %s\n", cmts->name);
978                                         if (cmts->sfd > 0) {
979                                                 close(cmts->sfd);
980                                         }
981                                         AST_LIST_REMOVE_CURRENT(list);
982                                         free(cmts);
983                                 }
984                         }
985                         AST_LIST_TRAVERSE_SAFE_END;
986                         AST_LIST_UNLOCK(&cmts_list);
987                         AST_LIST_UNLOCK(&gate_list);
988                         pktcreload = 2;
989                 }
990                 pthread_testcancel();
991         }
992         return NULL;
993 }
994
995 static int restart_pktc_thread(void)
996 {
997         if (pktccops_thread == AST_PTHREADT_STOP) {
998                 return 0;
999         }
1000         if (ast_mutex_lock(&pktccops_lock)) {
1001                 ast_log(LOG_WARNING, "Unable to lock pktccops\n");
1002                 return -1;
1003         }
1004         if (pktccops_thread == pthread_self()) {
1005                 ast_mutex_unlock(&pktccops_lock);
1006                 ast_log(LOG_WARNING, "Cannot kill myself\n");
1007                 return -1;
1008         }
1009         if (pktccops_thread != AST_PTHREADT_NULL) {
1010                 /* Wake up the thread */
1011                 pthread_kill(pktccops_thread, SIGURG);
1012         } else {
1013                 /* Start a new monitor */
1014                 if (ast_pthread_create_background(&pktccops_thread, NULL, do_pktccops, NULL) < 0) {
1015                         ast_mutex_unlock(&pktccops_lock);
1016                         ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
1017                         return -1;
1018                 }
1019         }
1020         ast_mutex_unlock(&pktccops_lock);
1021         return 0;
1022 }
1023
1024 static int load_pktccops_config(void)
1025 {
1026         static char *cfg = "res_pktccops.conf";
1027         struct ast_config *config;
1028         struct ast_variable *v;
1029         struct cops_cmts *cmts;
1030         struct cops_ippool *new_ippool;
1031         const char *host, *cat, *port;
1032         int update;
1033         int res = 0;
1034         uint16_t t1_temp, t7_temp, t8_temp;
1035         uint32_t keepalive_temp;
1036         unsigned int a,b,c,d,e,f,g,h;
1037         struct ast_flags config_flags = {0};
1038
1039         if (!(config = ast_config_load(cfg, config_flags))) {
1040                 ast_log(LOG_WARNING, "Unable to load config file res_pktccops.conf\n");
1041                 return -1;
1042         }
1043         for (cat = ast_category_browse(config, NULL); cat; cat = ast_category_browse(config, cat)) {
1044                 if (!strcmp(cat, "general")) {
1045                         for (v = ast_variable_browse(config, cat); v; v = v->next) {
1046                                 if (!strcasecmp(v->name, "t1")) {
1047                                         t1 = atoi(v->value);
1048                                 } else if (!strcasecmp(v->name, "t7")) {
1049                                         t7 = atoi(v->value);
1050                                 } else if (!strcasecmp(v->name, "t8")) {
1051                                         t8 = atoi(v->value);
1052                                 } else if (!strcasecmp(v->name, "keepalive")) {
1053                                         keepalive = atoi(v->value);
1054                                 } else if (!strcasecmp(v->name, "gateinfoperiod")) {
1055                                         gateinfoperiod = atoi(v->value);
1056                                 } else if (!strcasecmp(v->name, "gatetimeout")) {
1057                                         gatetimeout = atoi(v->value);
1058                                 } else {
1059                                         ast_log(LOG_WARNING, "Unkown option %s in general section of res_ptkccops.conf\n", v->name);
1060                                 }
1061                         }                       
1062                 } else {
1063                         /* Defaults */
1064                         host = NULL;
1065                         port = NULL;
1066                         t1_temp = t1;
1067                         t7_temp = t7;
1068                         t8_temp = t8;
1069                         keepalive_temp = keepalive;
1070
1071                         for (v = ast_variable_browse(config, cat); v; v = v->next) {
1072                                 if (!strcasecmp(v->name, "host")) {
1073                                         host = v->value;                                
1074                                 } else if (!strcasecmp(v->name, "port")) {
1075                                         port = v->value;
1076                                 } else if (!strcasecmp(v->name, "t1")) {
1077                                         t1_temp = atoi(v->value);
1078                                 } else if (!strcasecmp(v->name, "t7")) {
1079                                         t7_temp = atoi(v->value);
1080                                 } else if (!strcasecmp(v->name, "t8")) {
1081                                         t8_temp = atoi(v->value);
1082                                 } else if (!strcasecmp(v->name, "keepalive")) {
1083                                         keepalive_temp = atoi(v->value);
1084                                 } else if (!strcasecmp(v->name, "pool")) {
1085                                         /* we weill parse it in 2nd round */
1086                                 } else {
1087                                         ast_log(LOG_WARNING, "Unkown option %s in res_ptkccops.conf\n", v->name);
1088                                 }
1089                         }
1090
1091                         update = 0;
1092                         AST_LIST_TRAVERSE(&cmts_list, cmts, list) {
1093                                 if (!strcmp(cmts->name, cat)) {
1094                                         update = 1;
1095                                         break;
1096                                 }
1097
1098                         }
1099                         if (!update) {
1100                                 cmts = ast_calloc(1, sizeof(*cmts));
1101                                 if (!cmts) {
1102                                         res = -1;
1103                                         break;
1104                                 }
1105                                 AST_LIST_INSERT_HEAD(&cmts_list, cmts, list);
1106                         }
1107                         if (cat) {
1108                                 ast_copy_string(cmts->name, cat, sizeof(cmts->name));
1109                         }
1110                         if (host) {
1111                                 ast_copy_string(cmts->host, host, sizeof(cmts->host));
1112                         }
1113                         if (port) {
1114                                 ast_copy_string(cmts->port, port, sizeof(cmts->port));
1115                         } else {
1116                                 ast_copy_string(cmts->port, DEFAULT_COPS_PORT, sizeof(cmts->port));
1117                         }
1118
1119                         cmts->t1 = t1_temp;
1120                         cmts->t7 = t7_temp;
1121                         cmts->t8 = t8_temp;
1122                         cmts->keepalive = keepalive_temp;
1123                         if (!update) {
1124                                 cmts->state = 0;
1125                                 cmts->sfd = -1;
1126                         }
1127                         cmts->need_delete = 0;
1128                         for (v = ast_variable_browse(config, cat); v; v = v->next) {
1129                                 /* parse ipppol when we have cmts ptr */
1130                                 if (!strcasecmp(v->name, "pool")) {
1131                                         if (sscanf(v->value, "%3u.%3u.%3u.%3u %3u.%3u.%3u.%3u", &a, &b, &c, &d, &e, &f, &g, &h) == 8) {
1132                                                 new_ippool = ast_calloc(1, sizeof(*new_ippool));
1133                                                 if (!new_ippool) {
1134                                                         res = -1;
1135                                                         break;
1136                                                 }
1137                                                 new_ippool->start = a << 24 | b << 16 | c << 8 | d;
1138                                                 new_ippool->stop = e << 24 | f << 16 | g << 8 | h;
1139                                                 new_ippool->cmts = cmts;
1140                                                 pktccops_add_ippool(new_ippool);
1141                                         } else {
1142                                                 ast_log(LOG_WARNING, "Invalid ip pool format in res_pktccops.conf\n");
1143                                         }
1144                                 }
1145                         }
1146                 }
1147         }
1148         ast_config_destroy(config);
1149         return res;
1150 }
1151
1152 static char *pktccops_show_cmtses(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1153 {
1154         struct cops_cmts *cmts;
1155         char statedesc[16];
1156         int katimer;
1157         
1158         switch(cmd) {
1159         case CLI_INIT:
1160                 e->command = "pktccops show cmtses";
1161                 e->usage = 
1162                         "Usage: pktccops show cmtses\n"
1163                         "       List PacketCable COPS CMTSes.\n";
1164
1165                 return NULL;
1166         case CLI_GENERATE:
1167                 return NULL;
1168         }
1169
1170         ast_cli(a->fd, "%-16s %-24s %-12s %7s\n", "Name        ", "Host                ", "Status    ", "KA timer  ");
1171         ast_cli(a->fd, "%-16s %-24s %-12s %7s\n", "------------", "--------------------", "----------", "-----------");
1172         AST_LIST_LOCK(&cmts_list);
1173         AST_LIST_TRAVERSE(&cmts_list, cmts, list) {
1174                 katimer = -1;
1175                 if (cmts->state == 2) {
1176                         ast_copy_string(statedesc, "Connected", sizeof(statedesc));
1177                         katimer = (int) (time(NULL) - cmts->katimer);
1178                 } else if (cmts->state == 1) {
1179                         ast_copy_string(statedesc, "Connecting", sizeof(statedesc));
1180                 } else {
1181                         ast_copy_string(statedesc, "N/A", sizeof(statedesc));
1182                 }
1183                 ast_cli(a->fd, "%-16s %-15s:%-8s %-12s %-7d\n", cmts->name, cmts->host, cmts->port, statedesc, katimer);
1184         }
1185         AST_LIST_UNLOCK(&cmts_list);
1186         return CLI_SUCCESS;
1187 }
1188
1189 static char *pktccops_show_gates(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1190 {
1191         struct cops_gate *gate;
1192         char state_desc[16];
1193
1194         switch(cmd) {
1195         case CLI_INIT:
1196                 e->command = "pktccops show gates";
1197                 e->usage = 
1198                         "Usage: pktccops show gates\n"
1199                         "       List PacketCable COPS GATEs.\n";
1200
1201                 return NULL;
1202         case CLI_GENERATE:
1203                 return NULL;
1204         }
1205
1206         ast_cli(a->fd, "%-16s %-12s %-12s %-10s %-10s %-10s\n" ,"CMTS", "Gate-Id","MTA", "Status", "AllocTime", "CheckTime");
1207         ast_cli(a->fd, "%-16s %-12s %-12s %-10s %-10s %-10s\n" ,"--------------" ,"----------", "----------", "--------", "--------", "--------\n");
1208         AST_LIST_LOCK(&cmts_list);
1209         AST_LIST_LOCK(&gate_list);
1210         AST_LIST_TRAVERSE(&gate_list, gate, list) {
1211                 if (gate->state == GATE_ALLOC_FAILED) {
1212                         ast_copy_string(state_desc, "Failed", sizeof(state_desc));
1213                 } else if (gate->state == GATE_ALLOC_PROGRESS) {
1214                         ast_copy_string(state_desc, "In Progress", sizeof(state_desc));
1215                 } else if (gate->state == GATE_ALLOCATED) {
1216                         ast_copy_string(state_desc, "Allocated", sizeof(state_desc));
1217                 } else if (gate->state == GATE_CLOSED) {
1218                         ast_copy_string(state_desc, "Closed", sizeof(state_desc));
1219                 } else if (gate->state == GATE_CLOSED_ERR) {
1220                         ast_copy_string(state_desc, "ClosedErr", sizeof(state_desc));
1221                 } else if (gate->state == GATE_OPEN) {
1222                         ast_copy_string(state_desc, "Open", sizeof(state_desc));
1223                 } else if (gate->state == GATE_DELETED) {
1224                         ast_copy_string(state_desc, "Deleted", sizeof(state_desc));
1225                 } else {
1226                         ast_copy_string(state_desc, "N/A", sizeof(state_desc));
1227                 }
1228                 
1229                 ast_cli(a->fd, "%-16s 0x%.8x   0x%08x   %-10s %10i %10i %u\n", (gate->cmts) ? gate->cmts->name : "null" , gate->gateid, gate->mta, 
1230                         state_desc, (int) (time(NULL) - gate->allocated), (gate->checked) ? (int) (time(NULL) - gate->checked) : 0, (unsigned int) gate->in_transaction);
1231         }
1232         AST_LIST_UNLOCK(&cmts_list);
1233         AST_LIST_UNLOCK(&gate_list);
1234         return CLI_SUCCESS;
1235 }
1236
1237 static char *pktccops_show_pools(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1238 {
1239         struct cops_ippool *ippool;
1240         char start[32];
1241         char stop[32];
1242
1243         switch(cmd) {
1244         case CLI_INIT:
1245                 e->command = "pktccops show pools";
1246                 e->usage = 
1247                         "Usage: pktccops show pools\n"
1248                         "       List PacketCable COPS ip pools of MTAs.\n";
1249
1250                 return NULL;
1251         case CLI_GENERATE:
1252                 return NULL;
1253         }
1254
1255         ast_cli(a->fd, "%-16s %-18s %-7s\n", "Start     ", "Stop      ", "CMTS    ");
1256         ast_cli(a->fd, "%-16s %-18s %-7s\n", "----------", "----------", "--------");
1257         AST_LIST_LOCK(&ippool_list);
1258         AST_LIST_TRAVERSE(&ippool_list, ippool, list) {
1259                 snprintf(start, sizeof(start), "%3u.%3u.%3u.%3u", ippool->start >> 24, (ippool->start >> 16) & 0x000000ff, (ippool->start >> 8) & 0x000000ff, ippool->start & 0x000000ff);
1260
1261                 snprintf(stop, sizeof(stop), "%3u.%3u.%3u.%3u", ippool->stop >> 24, (ippool->stop >> 16) & 0x000000ff, (ippool->stop >> 8) & 0x000000ff, ippool->stop & 0x000000ff);
1262                 ast_cli(a->fd, "%-16s %-18s %-16s\n", start, stop, ippool->cmts->name);
1263         }
1264         AST_LIST_UNLOCK(&ippool_list);
1265         return CLI_SUCCESS;
1266 }
1267
1268 static char *pktccops_gatedel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1269 {
1270         int found = 0;
1271         int trid;
1272         uint32_t gateid;
1273         struct cops_gate *gate;
1274         struct cops_cmts *cmts;
1275
1276         switch (cmd) {
1277         case CLI_INIT:
1278                 e->command = "pktccops gatedel";
1279                 e->usage = 
1280                         "Usage: pktccops gatedel <cmts> <gateid>\n"
1281                         "       Send Gate-Del to cmts.\n";
1282                 return NULL;
1283         case CLI_GENERATE:
1284                 return NULL;
1285         }
1286
1287         if (a->argc < 4)
1288                 return CLI_SHOWUSAGE;
1289
1290         AST_LIST_LOCK(&cmts_list);
1291         AST_LIST_TRAVERSE(&cmts_list, cmts, list) {
1292                 if (!strcmp(cmts->name, a->argv[2])) {
1293                         ast_cli(a->fd, "Found cmts: %s\n", cmts->name);
1294                         found = 1;
1295                         break;
1296                 }
1297         }
1298         AST_LIST_UNLOCK(&cmts_list);
1299         
1300         if (!found)
1301                 return CLI_SHOWUSAGE;
1302
1303         trid = cops_trid++;
1304         if (!sscanf(a->argv[3], "%x", &gateid)) {
1305                 ast_cli(a->fd, "bad gate specification (%s)\n", a->argv[3]);    
1306                 return CLI_SHOWUSAGE;
1307         }
1308
1309         found = 0;
1310         AST_LIST_LOCK(&gate_list);
1311         AST_LIST_TRAVERSE(&gate_list, gate, list) {
1312                 if (gate->gateid == gateid && gate->cmts == cmts) {
1313                         found = 1;
1314                         break;
1315                 }
1316         }
1317                 
1318         if (!found) {
1319                 ast_cli(a->fd, "gate not found: %s\n", a->argv[3]);
1320                 return CLI_SHOWUSAGE;
1321         }
1322
1323         AST_LIST_UNLOCK(&gate_list);
1324         cops_gate_cmd(GATE_DEL, cmts, trid, 0, 0, 0, 0, 0, 0, gate);
1325         return CLI_SUCCESS;
1326 }
1327
1328 static char *pktccops_gateset(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1329 {
1330         int foundcmts = 0;
1331         int trid;
1332         unsigned int an,bn,cn,dn;
1333         uint32_t mta, ssip;
1334         struct cops_cmts *cmts;
1335
1336         switch (cmd) {
1337         case CLI_INIT:
1338                 e->command = "pktccops gateset";
1339                 e->usage = 
1340                         "Usage: pktccops gateset <cmts> <mta> <acctcount> <bitrate> <packet size> <switch ip> <switch port>\n"
1341                         "       Send Gate-Set to cmts.\n";
1342                 return NULL;
1343         case CLI_GENERATE:
1344                 return NULL;
1345         }
1346
1347         if (a->argc < 9)
1348                 return CLI_SHOWUSAGE;
1349
1350         if (!strcmp(a->argv[2], "null")) {
1351                 cmts = NULL;
1352         } else {
1353                 AST_LIST_LOCK(&cmts_list);
1354                 AST_LIST_TRAVERSE(&cmts_list, cmts, list) {
1355                         if (!strcmp(cmts->name, a->argv[2])) {
1356                                 ast_cli(a->fd, "Found cmts: %s\n", cmts->name);
1357                                 foundcmts = 1;
1358                                 break;
1359                         }
1360                 }
1361                 AST_LIST_UNLOCK(&cmts_list);
1362                 if (!foundcmts) {
1363                         ast_cli(a->fd, "CMTS not found: %s\n", a->argv[2]);
1364                         return CLI_SHOWUSAGE;
1365                 }
1366         }
1367
1368         trid = cops_trid++;
1369         if (sscanf(a->argv[3], "%3u.%3u.%3u.%3u", &an, &bn, &cn, &dn) != 4) {
1370                 ast_cli(a->fd, "MTA specification (%s) does not look like an ipaddr\n", a->argv[3]);
1371                 return CLI_SHOWUSAGE;
1372         }
1373         mta = an << 24 | bn << 16 | cn << 8 | dn;
1374
1375         if (sscanf(a->argv[7], "%3u.%3u.%3u.%3u", &an, &bn, &cn, &dn) != 4) {
1376                 ast_cli(a->fd, "SSIP specification (%s) does not look like an ipaddr\n", a->argv[7]);
1377                 return CLI_SHOWUSAGE;
1378         }
1379         ssip = an << 24 | bn << 16 | cn << 8 | dn;
1380
1381         cops_gate_cmd(GATE_SET, cmts, trid, mta, atoi(a->argv[4]), atof(a->argv[5]), atoi(a->argv[6]), ssip, atoi(a->argv[8]), NULL);
1382         return CLI_SUCCESS;
1383 }
1384
1385 static char *pktccops_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1386 {
1387         switch (cmd) {
1388         case CLI_INIT:
1389                 e->command = "pktccops set debug {on|off}";
1390                 e->usage = 
1391                         "Usage: pktccops set debug {on|off}\n"
1392                         "       Turn on/off debuging\n";
1393                 return NULL;
1394         case CLI_GENERATE:
1395                 return NULL;
1396         }
1397
1398         if (a->argc != e->args)
1399                 return CLI_SHOWUSAGE;
1400         if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
1401                 pktccopsdebug = 1;
1402                 ast_cli(a->fd, "PktcCOPS Debugging Enabled\n");
1403         } else if (!strncasecmp(a->argv[e->args - 1], "off", 2)) {
1404                 pktccopsdebug = 0;
1405                 ast_cli(a->fd, "PktcCOPS Debugging Disabled\n");
1406         } else {
1407                 return CLI_SHOWUSAGE;
1408         }
1409         return CLI_SUCCESS;
1410
1411 }
1412
1413 static struct ast_cli_entry cli_pktccops[] = {
1414         AST_CLI_DEFINE(pktccops_show_cmtses, "List PacketCable COPS CMTSes"),
1415         AST_CLI_DEFINE(pktccops_show_gates, "List PacketCable COPS GATEs"),
1416         AST_CLI_DEFINE(pktccops_show_pools, "List PacketCable MTA pools"),
1417         AST_CLI_DEFINE(pktccops_gateset, "Send Gate-Set to cmts"),
1418         AST_CLI_DEFINE(pktccops_gatedel, "Send Gate-Det to cmts"),
1419         AST_CLI_DEFINE(pktccops_debug, "Enable/Disable COPS debugging")
1420 };
1421
1422 static int pktccops_add_ippool(struct cops_ippool *ippool)
1423 {
1424         if (ippool) {
1425                 AST_LIST_LOCK(&ippool_list);
1426                 AST_LIST_INSERT_HEAD(&ippool_list, ippool, list);
1427                 AST_LIST_UNLOCK(&ippool_list);
1428                 return 0;
1429         } else {
1430                 ast_log(LOG_WARNING, "Attempted to register NULL ippool?\n");
1431                 return -1;
1432         }
1433 }
1434
1435 static void pktccops_unregister_cmtses(void)
1436 {
1437         struct cops_cmts *cmts;
1438         struct cops_gate *gate;
1439         AST_LIST_LOCK(&cmts_list);
1440         while ((cmts = AST_LIST_REMOVE_HEAD(&cmts_list, list))) {
1441                 if (cmts->sfd > 0) {
1442                         close(cmts->sfd);
1443                 }
1444                 free(cmts);
1445         }
1446         AST_LIST_UNLOCK(&cmts_list);
1447
1448         AST_LIST_LOCK(&gate_list);
1449         while ((gate = AST_LIST_REMOVE_HEAD(&gate_list, list))) {
1450                 free(gate);
1451         }
1452         AST_LIST_UNLOCK(&gate_list);
1453 }
1454
1455 static void pktccops_unregister_ippools(void)
1456 {
1457         struct cops_ippool *ippool;
1458         AST_LIST_LOCK(&ippool_list);
1459         while ((ippool = AST_LIST_REMOVE_HEAD(&ippool_list, list))) {
1460                 free(ippool);
1461         }
1462         AST_LIST_UNLOCK(&ippool_list);
1463 }
1464
1465 static int load_module(void)
1466 {
1467         int res;
1468         AST_LIST_LOCK(&cmts_list);
1469         res = load_pktccops_config();
1470         AST_LIST_UNLOCK(&cmts_list);
1471         if (res == -1) {
1472                 return AST_MODULE_LOAD_DECLINE;
1473         }
1474         ast_cli_register_multiple(cli_pktccops, sizeof(cli_pktccops) / sizeof(struct ast_cli_entry));
1475         restart_pktc_thread();
1476         return 0;
1477 }
1478
1479 static int unload_module(void)
1480 {
1481         if (!ast_mutex_lock(&pktccops_lock)) {
1482                 if ((pktccops_thread != AST_PTHREADT_NULL) && (pktccops_thread != AST_PTHREADT_STOP)) {
1483                         pthread_cancel(pktccops_thread);
1484                         pthread_kill(pktccops_thread, SIGURG);
1485                         pthread_join(pktccops_thread, NULL);
1486                 }
1487                 pktccops_thread = AST_PTHREADT_STOP;
1488                 ast_mutex_unlock(&pktccops_lock);
1489         } else {
1490                 ast_log(LOG_ERROR, "Unable to lock the pktccops_thread\n");
1491                 return -1;
1492         }
1493
1494         ast_cli_unregister_multiple(cli_pktccops, sizeof(cli_pktccops) / sizeof(struct ast_cli_entry));
1495         pktccops_unregister_cmtses();
1496         pktccops_unregister_ippools();
1497         pktccops_thread = AST_PTHREADT_NULL;
1498         return 0;
1499 }
1500
1501 static int reload_module(void)
1502 {
1503         /* Prohibit unloading */
1504         if (pktcreload) {
1505                 ast_log(LOG_NOTICE, "Previous reload in progress, please wait!\n");
1506                 return -1;
1507         }
1508         pktcreload = 1;
1509         return 0;
1510 }
1511
1512 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "PktcCOPS manager for MGCP",
1513                 .load = load_module,
1514                 .unload = unload_module,
1515                 .reload = reload_module,
1516                );
1517