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