Allow Asterisk to compile under GCC 4.10
[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: %u\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: %u 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 %u < %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 (%us) 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=%u\n",
803                                                         cmts->name, (unsigned)recmsg->verflag,
804                                                         recmsg->opcode, (unsigned)recmsg->clienttype, recmsg->length);
805                                                 if (recmsg->object != NULL) {
806                                                         pobject = recmsg->object;
807                                                         while (pobject != NULL) {
808                                                                 ast_debug(3, " OBJECT: length=%i cnum=%i ctype=%i\n", pobject->length, pobject->cnum, pobject->ctype);
809                                                                 if (recmsg->opcode == 1 && pobject->cnum == 1 && pobject->ctype == 1 ) {
810                                                                         cmts->handle = ntohl(*((uint32_t *) pobject->contents));
811                                                                         ast_debug(3, "    REQ client handle: %u\n", cmts->handle);
812                                                                         cmts->state = 2;
813                                                                         cmts->katimer = time(NULL);
814                                                                 } else if (pobject->cnum == 9 && pobject->ctype == 1) {
815                                                                         sobjp = pobject->contents;
816                                                                         subscrid = 0;
817                                                                         recvtrid = 0;
818                                                                         scommand = 0;
819                                                                         pktcerror = 0;
820                                                                         actcount = 0;
821                                                                         gateid = 0;
822                                                                         reason = 0;
823                                                                         subreason = 0;
824                                                                         while (sobjp < (pobject->contents + pobject->length - 4)) {
825                                                                                 sobjlen = ntohs(*((uint16_t *) sobjp));
826                                                                                 snst = ntohs(*((uint16_t *) (sobjp + 2)));
827                                                                                 ast_debug(3, "   S-Num S-type: 0x%.4x len: %i\n", (unsigned)snst, sobjlen);
828                                                                                 if (snst == 0x0101 ) {
829                                                                                         recvtrid = ntohs(*((uint16_t *) (sobjp + 4)));
830                                                                                         scommand = ntohs(*((uint16_t *) (sobjp + 6)));                                  
831                                                                                         ast_debug(3, "     Transaction Identifier command: %i trid %i\n", scommand, recvtrid);
832                                                                                 } else if (snst == 0x0201) {
833                                                                                         subscrid = ntohl(*((uint32_t *) (sobjp + 4)));
834                                                                                         ast_debug(3, "     Subscriber ID: 0x%.8x\n", subscrid);
835                                                                                 } else if (snst == 0x0301) {
836                                                                                         gateid = ntohl(*((uint32_t *) (sobjp + 4)));
837                                                                                         ast_debug(3, "      Gate ID: 0x%x 0x%.8x\n", gateid, gateid);
838                                                                                 } else if (snst == 0x0401) {
839                                                                                         actcount = ntohs(*((uint16_t *) (sobjp + 6)));
840                                                                                         ast_debug(3, "      Activity Count: %i\n", actcount);
841                                                                                 } else if (snst == 0x0901) {
842                                                                                         pktcerror = ntohl(*((uint32_t *) (sobjp + 4)));
843                                                                                         ast_debug(3, "      PKTC Error: 0x%.8x\n", pktcerror);
844                                                                                 } else if (snst == 0x0d01) {
845                                                                                         reason = ntohs(*((uint16_t *) (sobjp + 4)));
846                                                                                         subreason = ntohs(*((uint16_t *) (sobjp + 6)));
847                                                                                         ast_debug(3, "      Reason: %d Subreason: %d\n", reason, subreason);
848                                                                                 }
849                                                                                 sobjp += sobjlen;
850                                                                                 if (!sobjlen)
851                                                                                         break;
852                                                                         }
853                                                                         if (scommand == PKTCCOPS_SCOMMAND_GATE_CLOSE || scommand == PKTCCOPS_SCOMMAND_GATE_OPEN) {
854                                                                                 AST_LIST_LOCK(&gate_list);
855                                                                                 AST_LIST_TRAVERSE_SAFE_BEGIN(&gate_list, gate, list) {
856                                                                                         if (gate->cmts == cmts && gate->gateid == gateid) {
857                                                                                                 if (scommand == PKTCCOPS_SCOMMAND_GATE_CLOSE && gate->state != GATE_CLOSED && gate->state != GATE_CLOSED_ERR ) {
858                                                                                                         ast_debug(3, "COPS Gate Close Gate ID: 0x%x TrId: %i CMTS: %s\n", gateid, recvtrid, cmts->name);
859                                                                                                         if (subreason) {
860                                                                                                                 gate->state = GATE_CLOSED_ERR;
861                                                                                                                 PKTCCOPS_DESTROY_CURRENT_GATE;
862                                                                                                         } else {
863                                                                                                                 gate->state = GATE_CLOSED;
864                                                                                                                 PKTCCOPS_DESTROY_CURRENT_GATE;
865                                                                                                         }
866                                                                                                         break;
867                                                                                                 } else if (scommand == PKTCCOPS_SCOMMAND_GATE_OPEN && gate->state == GATE_ALLOCATED) {
868                                                                                                         ast_debug(3, "COPS Gate Open Gate ID: 0x%x TrId: %i CMTS: %s\n", gateid, recvtrid, cmts->name);
869                                                                                                         gate->state = GATE_OPEN;
870                                                                                                         if (gate->gate_open) {
871                                                                                                                 ast_debug(3, "Calling GATE-OPEN callback function\n");
872                                                                                                                 gate->gate_open(gate);
873                                                                                                                 gate->gate_open = NULL;
874                                                                                                         }
875                                                                                                         break;
876                                                                                                 } 
877                                                                                         }
878                                                                                 }
879                                                                                 AST_LIST_TRAVERSE_SAFE_END;
880                                                                                 AST_LIST_UNLOCK(&gate_list);
881                                                                         } 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) {
882                                                                                 AST_LIST_LOCK(&gate_list);
883                                                                                 AST_LIST_TRAVERSE_SAFE_BEGIN(&gate_list, gate, list) {
884                                                                                         if (gate->cmts == cmts && gate->trid == recvtrid) {
885                                                                                                 gate->gateid = gateid;
886                                                                                                 gate->checked = time(NULL);
887                                                                                                 if (scommand == PKTCCOPS_SCOMMAND_GATE_SET_ACK) {
888                                                                                                         ast_debug(3, "COPS Gate Set Ack Gate ID: 0x%x TrId: %i CMTS: %s\n", gateid, recvtrid, cmts->name);
889                                                                                                         gate->state = GATE_ALLOCATED;
890                                                                                                         if (gate->got_dq_gi) {
891                                                                                                                 gate->got_dq_gi(gate);
892                                                                                                                 gate->got_dq_gi = NULL;
893                                                                                                         }
894                                                                                                 } else if (scommand == PKTCCOPS_SCOMMAND_GATE_SET_ERR) {
895                                                                                                         ast_debug(3, "COPS Gate Set Error TrId: %i ErrorCode: 0x%.8x CMTS: %s\n ", recvtrid, pktcerror, cmts->name);
896                                                                                                         gate->state = GATE_ALLOC_FAILED;
897                                                                                                         if (gate->got_dq_gi) {
898                                                                                                                 gate->got_dq_gi(gate);
899                                                                                                                 gate->got_dq_gi = NULL;
900                                                                                                         }
901                                                                                                         PKTCCOPS_DESTROY_CURRENT_GATE;
902                                                                                                 } else if (scommand == PKTCCOPS_SCOMMAND_GATE_INFO_ACK) {
903                                                                                                         ast_debug(3, "COPS Gate Info Ack Gate ID: 0x%x TrId: %i CMTS: %s\n", gateid, recvtrid, cmts->name);
904                                                                                                 } else if (scommand == PKTCCOPS_SCOMMAND_GATE_INFO_ERR) {
905                                                                                                         ast_debug(3, "COPS Gate Info Error Gate ID: 0x%x TrId: %i CMTS: %s\n", gateid, recvtrid, cmts->name);
906                                                                                                         gate->state = GATE_ALLOC_FAILED;
907                                                                                                         PKTCCOPS_DESTROY_CURRENT_GATE;
908                                                                                                 } else if (scommand == PKTCCOPS_SCOMMAND_GATE_DELETE_ACK) {
909                                                                                                         ast_debug(3, "COPS Gate Deleted Gate ID: 0x%x TrId: %i CMTS: %s\n", gateid, recvtrid, cmts->name);
910                                                                                                         gate->state = GATE_DELETED;
911                                                                                                         PKTCCOPS_DESTROY_CURRENT_GATE;
912                                                                                                 }
913                                                                                                 gate->in_transaction = 0;
914                                                                                                 break;
915                                                                                         }
916                                                                                 }
917                                                                                 AST_LIST_TRAVERSE_SAFE_END;
918                                                                                 AST_LIST_UNLOCK(&gate_list);
919                                                                         }
920                                                                 }
921                                                                 pobject = pobject->next;
922                                                         }
923                                                 }
924
925                                                 if (recmsg->opcode == 6 && recmsg->object && recmsg->object->cnum == 11 && recmsg->object->ctype == 1) {
926                                                         ast_debug(3, "COPS: Client open %s\n", cmts->name);
927                                                         sendmsg->msg = NULL;
928                                                         sendmsg->verflag = 0x10;
929                                                         sendmsg->opcode = 7; /* Client Accept */
930                                                         sendmsg->clienttype = 0x8008; /* =PacketCable */
931                                                         sendmsg->length = COPS_HEADER_SIZE + COPS_OBJECT_HEADER_SIZE + 4;
932                                                         sendmsg->object = malloc(sizeof(struct pktcobj));
933                                                         sendmsg->object->length = 4 + COPS_OBJECT_HEADER_SIZE;
934                                                         sendmsg->object->cnum = 10; /* keppalive timer*/
935                                                         sendmsg->object->ctype = 1;
936                                                         sendmsg->object->contents = malloc(sizeof(uint32_t));
937                                                         *((uint32_t *) sendmsg->object->contents) = htonl(cmts->keepalive & 0x0000ffff);
938                                                         sendmsg->object->next = NULL;
939                                                         cops_sendmsg(cmts->sfd, sendmsg);
940                                                         cops_freemsg(sendmsg);
941                                                 } else if (recmsg->opcode == 9) {
942                                                         ast_debug(3, "COPS: Keepalive Request got echoing back %s\n", cmts->name);
943                                                         cops_sendmsg(cmts->sfd, recmsg);
944                                                         cmts->state = 2;
945                                                         cmts->katimer = time(NULL);
946                                                 }
947                                         } 
948                                         if (len <= 0) {
949                                                 ast_debug(3, "COPS: lost connection to %s\n", cmts->name);
950                                                 close(cmts->sfd);
951                                                 cmts->sfd = -1;
952                                                 cmts->state = 0;
953                                         }
954                                         cops_freemsg(recmsg);
955                                 }
956                         }
957                         AST_LIST_UNLOCK(&cmts_list);                    
958                 }
959                 if (pktcreload) {
960                         ast_debug(3, "Reloading pktccops...\n");
961                         AST_LIST_LOCK(&gate_list);
962                         AST_LIST_LOCK(&cmts_list);
963                         pktccops_unregister_ippools();
964                         AST_LIST_TRAVERSE(&cmts_list, cmts, list) {
965                                 cmts->need_delete = 1;
966                         }
967                         load_pktccops_config();
968                         AST_LIST_TRAVERSE_SAFE_BEGIN(&cmts_list, cmts, list) {
969                                 if (cmts && cmts->need_delete) {
970                                         AST_LIST_TRAVERSE(&gate_list, gate, list) {
971                                                 if (gate->cmts == cmts) {
972                                                         ast_debug(3, "Null gate %s\n", gate->cmts->name);
973                                                         gate->cmts = NULL;
974                                                 }
975                                                 gate->in_transaction = 0;
976                                         }
977                                         AST_LIST_UNLOCK(&gate_list);
978                                         ast_debug(3, "removing cmts: %s\n", cmts->name);
979                                         if (cmts->sfd > 0) {
980                                                 close(cmts->sfd);
981                                         }
982                                         AST_LIST_REMOVE_CURRENT(list);
983                                         free(cmts);
984                                 }
985                         }
986                         AST_LIST_TRAVERSE_SAFE_END;
987                         AST_LIST_UNLOCK(&cmts_list);
988                         AST_LIST_UNLOCK(&gate_list);
989                         pktcreload = 2;
990                 }
991                 pthread_testcancel();
992         }
993         return NULL;
994 }
995
996 static int restart_pktc_thread(void)
997 {
998         if (pktccops_thread == AST_PTHREADT_STOP) {
999                 return 0;
1000         }
1001         if (ast_mutex_lock(&pktccops_lock)) {
1002                 ast_log(LOG_WARNING, "Unable to lock pktccops\n");
1003                 return -1;
1004         }
1005         if (pktccops_thread == pthread_self()) {
1006                 ast_mutex_unlock(&pktccops_lock);
1007                 ast_log(LOG_WARNING, "Cannot kill myself\n");
1008                 return -1;
1009         }
1010         if (pktccops_thread != AST_PTHREADT_NULL) {
1011                 /* Wake up the thread */
1012                 pthread_kill(pktccops_thread, SIGURG);
1013         } else {
1014                 /* Start a new monitor */
1015                 if (ast_pthread_create_background(&pktccops_thread, NULL, do_pktccops, NULL) < 0) {
1016                         ast_mutex_unlock(&pktccops_lock);
1017                         ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
1018                         return -1;
1019                 }
1020         }
1021         ast_mutex_unlock(&pktccops_lock);
1022         return 0;
1023 }
1024
1025 static int load_pktccops_config(void)
1026 {
1027         static char *cfg = "res_pktccops.conf";
1028         struct ast_config *config;
1029         struct ast_variable *v;
1030         struct cops_cmts *cmts;
1031         struct cops_ippool *new_ippool;
1032         const char *host, *cat, *port;
1033         int update;
1034         int res = 0;
1035         uint16_t t1_temp, t7_temp, t8_temp;
1036         uint32_t keepalive_temp;
1037         unsigned int a,b,c,d,e,f,g,h;
1038         struct ast_flags config_flags = {0};
1039
1040         if (!(config = ast_config_load(cfg, config_flags))) {
1041                 ast_log(LOG_WARNING, "Unable to load config file res_pktccops.conf\n");
1042                 return -1;
1043         }
1044         for (cat = ast_category_browse(config, NULL); cat; cat = ast_category_browse(config, cat)) {
1045                 if (!strcmp(cat, "general")) {
1046                         for (v = ast_variable_browse(config, cat); v; v = v->next) {
1047                                 if (!strcasecmp(v->name, "t1")) {
1048                                         t1 = atoi(v->value);
1049                                 } else if (!strcasecmp(v->name, "t7")) {
1050                                         t7 = atoi(v->value);
1051                                 } else if (!strcasecmp(v->name, "t8")) {
1052                                         t8 = atoi(v->value);
1053                                 } else if (!strcasecmp(v->name, "keepalive")) {
1054                                         keepalive = atoi(v->value);
1055                                 } else if (!strcasecmp(v->name, "gateinfoperiod")) {
1056                                         gateinfoperiod = atoi(v->value);
1057                                 } else if (!strcasecmp(v->name, "gatetimeout")) {
1058                                         gatetimeout = atoi(v->value);
1059                                 } else {
1060                                         ast_log(LOG_WARNING, "Unkown option %s in general section of res_ptkccops.conf\n", v->name);
1061                                 }
1062                         }                       
1063                 } else {
1064                         /* Defaults */
1065                         host = NULL;
1066                         port = NULL;
1067                         t1_temp = t1;
1068                         t7_temp = t7;
1069                         t8_temp = t8;
1070                         keepalive_temp = keepalive;
1071
1072                         for (v = ast_variable_browse(config, cat); v; v = v->next) {
1073                                 if (!strcasecmp(v->name, "host")) {
1074                                         host = v->value;                                
1075                                 } else if (!strcasecmp(v->name, "port")) {
1076                                         port = v->value;
1077                                 } else if (!strcasecmp(v->name, "t1")) {
1078                                         t1_temp = atoi(v->value);
1079                                 } else if (!strcasecmp(v->name, "t7")) {
1080                                         t7_temp = atoi(v->value);
1081                                 } else if (!strcasecmp(v->name, "t8")) {
1082                                         t8_temp = atoi(v->value);
1083                                 } else if (!strcasecmp(v->name, "keepalive")) {
1084                                         keepalive_temp = atoi(v->value);
1085                                 } else if (!strcasecmp(v->name, "pool")) {
1086                                         /* we weill parse it in 2nd round */
1087                                 } else {
1088                                         ast_log(LOG_WARNING, "Unkown option %s in res_ptkccops.conf\n", v->name);
1089                                 }
1090                         }
1091
1092                         update = 0;
1093                         AST_LIST_TRAVERSE(&cmts_list, cmts, list) {
1094                                 if (!strcmp(cmts->name, cat)) {
1095                                         update = 1;
1096                                         break;
1097                                 }
1098
1099                         }
1100                         if (!update) {
1101                                 cmts = ast_calloc(1, sizeof(*cmts));
1102                                 if (!cmts) {
1103                                         res = -1;
1104                                         break;
1105                                 }
1106                                 AST_LIST_INSERT_HEAD(&cmts_list, cmts, list);
1107                         }
1108                         if (cat) {
1109                                 ast_copy_string(cmts->name, cat, sizeof(cmts->name));
1110                         }
1111                         if (host) {
1112                                 ast_copy_string(cmts->host, host, sizeof(cmts->host));
1113                         }
1114                         if (port) {
1115                                 ast_copy_string(cmts->port, port, sizeof(cmts->port));
1116                         } else {
1117                                 ast_copy_string(cmts->port, DEFAULT_COPS_PORT, sizeof(cmts->port));
1118                         }
1119
1120                         cmts->t1 = t1_temp;
1121                         cmts->t7 = t7_temp;
1122                         cmts->t8 = t8_temp;
1123                         cmts->keepalive = keepalive_temp;
1124                         if (!update) {
1125                                 cmts->state = 0;
1126                                 cmts->sfd = -1;
1127                         }
1128                         cmts->need_delete = 0;
1129                         for (v = ast_variable_browse(config, cat); v; v = v->next) {
1130                                 /* parse ipppol when we have cmts ptr */
1131                                 if (!strcasecmp(v->name, "pool")) {
1132                                         if (sscanf(v->value, "%3u.%3u.%3u.%3u %3u.%3u.%3u.%3u", &a, &b, &c, &d, &e, &f, &g, &h) == 8) {
1133                                                 new_ippool = ast_calloc(1, sizeof(*new_ippool));
1134                                                 if (!new_ippool) {
1135                                                         res = -1;
1136                                                         break;
1137                                                 }
1138                                                 new_ippool->start = a << 24 | b << 16 | c << 8 | d;
1139                                                 new_ippool->stop = e << 24 | f << 16 | g << 8 | h;
1140                                                 new_ippool->cmts = cmts;
1141                                                 pktccops_add_ippool(new_ippool);
1142                                         } else {
1143                                                 ast_log(LOG_WARNING, "Invalid ip pool format in res_pktccops.conf\n");
1144                                         }
1145                                 }
1146                         }
1147                 }
1148         }
1149         ast_config_destroy(config);
1150         return res;
1151 }
1152
1153 static char *pktccops_show_cmtses(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1154 {
1155         struct cops_cmts *cmts;
1156         char statedesc[16];
1157         int katimer;
1158         
1159         switch(cmd) {
1160         case CLI_INIT:
1161                 e->command = "pktccops show cmtses";
1162                 e->usage = 
1163                         "Usage: pktccops show cmtses\n"
1164                         "       List PacketCable COPS CMTSes.\n";
1165
1166                 return NULL;
1167         case CLI_GENERATE:
1168                 return NULL;
1169         }
1170
1171         ast_cli(a->fd, "%-16s %-24s %-12s %7s\n", "Name        ", "Host                ", "Status    ", "KA timer  ");
1172         ast_cli(a->fd, "%-16s %-24s %-12s %7s\n", "------------", "--------------------", "----------", "-----------");
1173         AST_LIST_LOCK(&cmts_list);
1174         AST_LIST_TRAVERSE(&cmts_list, cmts, list) {
1175                 katimer = -1;
1176                 if (cmts->state == 2) {
1177                         ast_copy_string(statedesc, "Connected", sizeof(statedesc));
1178                         katimer = (int) (time(NULL) - cmts->katimer);
1179                 } else if (cmts->state == 1) {
1180                         ast_copy_string(statedesc, "Connecting", sizeof(statedesc));
1181                 } else {
1182                         ast_copy_string(statedesc, "N/A", sizeof(statedesc));
1183                 }
1184                 ast_cli(a->fd, "%-16s %-15s:%-8s %-12s %-7d\n", cmts->name, cmts->host, cmts->port, statedesc, katimer);
1185         }
1186         AST_LIST_UNLOCK(&cmts_list);
1187         return CLI_SUCCESS;
1188 }
1189
1190 static char *pktccops_show_gates(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1191 {
1192         struct cops_gate *gate;
1193         char state_desc[16];
1194
1195         switch(cmd) {
1196         case CLI_INIT:
1197                 e->command = "pktccops show gates";
1198                 e->usage = 
1199                         "Usage: pktccops show gates\n"
1200                         "       List PacketCable COPS GATEs.\n";
1201
1202                 return NULL;
1203         case CLI_GENERATE:
1204                 return NULL;
1205         }
1206
1207         ast_cli(a->fd, "%-16s %-12s %-12s %-10s %-10s %-10s\n" ,"CMTS", "Gate-Id","MTA", "Status", "AllocTime", "CheckTime");
1208         ast_cli(a->fd, "%-16s %-12s %-12s %-10s %-10s %-10s\n" ,"--------------" ,"----------", "----------", "--------", "--------", "--------\n");
1209         AST_LIST_LOCK(&cmts_list);
1210         AST_LIST_LOCK(&gate_list);
1211         AST_LIST_TRAVERSE(&gate_list, gate, list) {
1212                 if (gate->state == GATE_ALLOC_FAILED) {
1213                         ast_copy_string(state_desc, "Failed", sizeof(state_desc));
1214                 } else if (gate->state == GATE_ALLOC_PROGRESS) {
1215                         ast_copy_string(state_desc, "In Progress", sizeof(state_desc));
1216                 } else if (gate->state == GATE_ALLOCATED) {
1217                         ast_copy_string(state_desc, "Allocated", sizeof(state_desc));
1218                 } else if (gate->state == GATE_CLOSED) {
1219                         ast_copy_string(state_desc, "Closed", sizeof(state_desc));
1220                 } else if (gate->state == GATE_CLOSED_ERR) {
1221                         ast_copy_string(state_desc, "ClosedErr", sizeof(state_desc));
1222                 } else if (gate->state == GATE_OPEN) {
1223                         ast_copy_string(state_desc, "Open", sizeof(state_desc));
1224                 } else if (gate->state == GATE_DELETED) {
1225                         ast_copy_string(state_desc, "Deleted", sizeof(state_desc));
1226                 } else {
1227                         ast_copy_string(state_desc, "N/A", sizeof(state_desc));
1228                 }
1229                 
1230                 ast_cli(a->fd, "%-16s 0x%.8x   0x%08x   %-10s %10i %10i %u\n", (gate->cmts) ? gate->cmts->name : "null" , gate->gateid, gate->mta, 
1231                         state_desc, (int) (time(NULL) - gate->allocated), (gate->checked) ? (int) (time(NULL) - gate->checked) : 0, (unsigned int) gate->in_transaction);
1232         }
1233         AST_LIST_UNLOCK(&cmts_list);
1234         AST_LIST_UNLOCK(&gate_list);
1235         return CLI_SUCCESS;
1236 }
1237
1238 static char *pktccops_show_pools(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1239 {
1240         struct cops_ippool *ippool;
1241         char start[32];
1242         char stop[32];
1243
1244         switch(cmd) {
1245         case CLI_INIT:
1246                 e->command = "pktccops show pools";
1247                 e->usage = 
1248                         "Usage: pktccops show pools\n"
1249                         "       List PacketCable COPS ip pools of MTAs.\n";
1250
1251                 return NULL;
1252         case CLI_GENERATE:
1253                 return NULL;
1254         }
1255
1256         ast_cli(a->fd, "%-16s %-18s %-7s\n", "Start     ", "Stop      ", "CMTS    ");
1257         ast_cli(a->fd, "%-16s %-18s %-7s\n", "----------", "----------", "--------");
1258         AST_LIST_LOCK(&ippool_list);
1259         AST_LIST_TRAVERSE(&ippool_list, ippool, list) {
1260                 snprintf(start, sizeof(start), "%3u.%3u.%3u.%3u", ippool->start >> 24, (ippool->start >> 16) & 0x000000ff, (ippool->start >> 8) & 0x000000ff, ippool->start & 0x000000ff);
1261
1262                 snprintf(stop, sizeof(stop), "%3u.%3u.%3u.%3u", ippool->stop >> 24, (ippool->stop >> 16) & 0x000000ff, (ippool->stop >> 8) & 0x000000ff, ippool->stop & 0x000000ff);
1263                 ast_cli(a->fd, "%-16s %-18s %-16s\n", start, stop, ippool->cmts->name);
1264         }
1265         AST_LIST_UNLOCK(&ippool_list);
1266         return CLI_SUCCESS;
1267 }
1268
1269 static char *pktccops_gatedel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1270 {
1271         int found = 0;
1272         int trid;
1273         uint32_t gateid;
1274         struct cops_gate *gate;
1275         struct cops_cmts *cmts;
1276
1277         switch (cmd) {
1278         case CLI_INIT:
1279                 e->command = "pktccops gatedel";
1280                 e->usage = 
1281                         "Usage: pktccops gatedel <cmts> <gateid>\n"
1282                         "       Send Gate-Del to cmts.\n";
1283                 return NULL;
1284         case CLI_GENERATE:
1285                 return NULL;
1286         }
1287
1288         if (a->argc < 4)
1289                 return CLI_SHOWUSAGE;
1290
1291         AST_LIST_LOCK(&cmts_list);
1292         AST_LIST_TRAVERSE(&cmts_list, cmts, list) {
1293                 if (!strcmp(cmts->name, a->argv[2])) {
1294                         ast_cli(a->fd, "Found cmts: %s\n", cmts->name);
1295                         found = 1;
1296                         break;
1297                 }
1298         }
1299         AST_LIST_UNLOCK(&cmts_list);
1300         
1301         if (!found)
1302                 return CLI_SHOWUSAGE;
1303
1304         trid = cops_trid++;
1305         if (!sscanf(a->argv[3], "%x", &gateid)) {
1306                 ast_cli(a->fd, "bad gate specification (%s)\n", a->argv[3]);    
1307                 return CLI_SHOWUSAGE;
1308         }
1309
1310         found = 0;
1311         AST_LIST_LOCK(&gate_list);
1312         AST_LIST_TRAVERSE(&gate_list, gate, list) {
1313                 if (gate->gateid == gateid && gate->cmts == cmts) {
1314                         found = 1;
1315                         break;
1316                 }
1317         }
1318                 
1319         if (!found) {
1320                 ast_cli(a->fd, "gate not found: %s\n", a->argv[3]);
1321                 return CLI_SHOWUSAGE;
1322         }
1323
1324         AST_LIST_UNLOCK(&gate_list);
1325         cops_gate_cmd(GATE_DEL, cmts, trid, 0, 0, 0, 0, 0, 0, gate);
1326         return CLI_SUCCESS;
1327 }
1328
1329 static char *pktccops_gateset(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1330 {
1331         int foundcmts = 0;
1332         int trid;
1333         unsigned int an,bn,cn,dn;
1334         uint32_t mta, ssip;
1335         struct cops_cmts *cmts;
1336
1337         switch (cmd) {
1338         case CLI_INIT:
1339                 e->command = "pktccops gateset";
1340                 e->usage = 
1341                         "Usage: pktccops gateset <cmts> <mta> <acctcount> <bitrate> <packet size> <switch ip> <switch port>\n"
1342                         "       Send Gate-Set to cmts.\n";
1343                 return NULL;
1344         case CLI_GENERATE:
1345                 return NULL;
1346         }
1347
1348         if (a->argc < 9)
1349                 return CLI_SHOWUSAGE;
1350
1351         if (!strcmp(a->argv[2], "null")) {
1352                 cmts = NULL;
1353         } else {
1354                 AST_LIST_LOCK(&cmts_list);
1355                 AST_LIST_TRAVERSE(&cmts_list, cmts, list) {
1356                         if (!strcmp(cmts->name, a->argv[2])) {
1357                                 ast_cli(a->fd, "Found cmts: %s\n", cmts->name);
1358                                 foundcmts = 1;
1359                                 break;
1360                         }
1361                 }
1362                 AST_LIST_UNLOCK(&cmts_list);
1363                 if (!foundcmts) {
1364                         ast_cli(a->fd, "CMTS not found: %s\n", a->argv[2]);
1365                         return CLI_SHOWUSAGE;
1366                 }
1367         }
1368
1369         trid = cops_trid++;
1370         if (sscanf(a->argv[3], "%3u.%3u.%3u.%3u", &an, &bn, &cn, &dn) != 4) {
1371                 ast_cli(a->fd, "MTA specification (%s) does not look like an ipaddr\n", a->argv[3]);
1372                 return CLI_SHOWUSAGE;
1373         }
1374         mta = an << 24 | bn << 16 | cn << 8 | dn;
1375
1376         if (sscanf(a->argv[7], "%3u.%3u.%3u.%3u", &an, &bn, &cn, &dn) != 4) {
1377                 ast_cli(a->fd, "SSIP specification (%s) does not look like an ipaddr\n", a->argv[7]);
1378                 return CLI_SHOWUSAGE;
1379         }
1380         ssip = an << 24 | bn << 16 | cn << 8 | dn;
1381
1382         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);
1383         return CLI_SUCCESS;
1384 }
1385
1386 static char *pktccops_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1387 {
1388         switch (cmd) {
1389         case CLI_INIT:
1390                 e->command = "pktccops set debug {on|off}";
1391                 e->usage = 
1392                         "Usage: pktccops set debug {on|off}\n"
1393                         "       Turn on/off debuging\n";
1394                 return NULL;
1395         case CLI_GENERATE:
1396                 return NULL;
1397         }
1398
1399         if (a->argc != e->args)
1400                 return CLI_SHOWUSAGE;
1401         if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
1402                 pktccopsdebug = 1;
1403                 ast_cli(a->fd, "PktcCOPS Debugging Enabled\n");
1404         } else if (!strncasecmp(a->argv[e->args - 1], "off", 2)) {
1405                 pktccopsdebug = 0;
1406                 ast_cli(a->fd, "PktcCOPS Debugging Disabled\n");
1407         } else {
1408                 return CLI_SHOWUSAGE;
1409         }
1410         return CLI_SUCCESS;
1411
1412 }
1413
1414 static struct ast_cli_entry cli_pktccops[] = {
1415         AST_CLI_DEFINE(pktccops_show_cmtses, "List PacketCable COPS CMTSes"),
1416         AST_CLI_DEFINE(pktccops_show_gates, "List PacketCable COPS GATEs"),
1417         AST_CLI_DEFINE(pktccops_show_pools, "List PacketCable MTA pools"),
1418         AST_CLI_DEFINE(pktccops_gateset, "Send Gate-Set to cmts"),
1419         AST_CLI_DEFINE(pktccops_gatedel, "Send Gate-Det to cmts"),
1420         AST_CLI_DEFINE(pktccops_debug, "Enable/Disable COPS debugging")
1421 };
1422
1423 static int pktccops_add_ippool(struct cops_ippool *ippool)
1424 {
1425         if (ippool) {
1426                 AST_LIST_LOCK(&ippool_list);
1427                 AST_LIST_INSERT_HEAD(&ippool_list, ippool, list);
1428                 AST_LIST_UNLOCK(&ippool_list);
1429                 return 0;
1430         } else {
1431                 ast_log(LOG_WARNING, "Attempted to register NULL ippool?\n");
1432                 return -1;
1433         }
1434 }
1435
1436 static void pktccops_unregister_cmtses(void)
1437 {
1438         struct cops_cmts *cmts;
1439         struct cops_gate *gate;
1440         AST_LIST_LOCK(&cmts_list);
1441         while ((cmts = AST_LIST_REMOVE_HEAD(&cmts_list, list))) {
1442                 if (cmts->sfd > 0) {
1443                         close(cmts->sfd);
1444                 }
1445                 free(cmts);
1446         }
1447         AST_LIST_UNLOCK(&cmts_list);
1448
1449         AST_LIST_LOCK(&gate_list);
1450         while ((gate = AST_LIST_REMOVE_HEAD(&gate_list, list))) {
1451                 free(gate);
1452         }
1453         AST_LIST_UNLOCK(&gate_list);
1454 }
1455
1456 static void pktccops_unregister_ippools(void)
1457 {
1458         struct cops_ippool *ippool;
1459         AST_LIST_LOCK(&ippool_list);
1460         while ((ippool = AST_LIST_REMOVE_HEAD(&ippool_list, list))) {
1461                 free(ippool);
1462         }
1463         AST_LIST_UNLOCK(&ippool_list);
1464 }
1465
1466 static int load_module(void)
1467 {
1468         int res;
1469         AST_LIST_LOCK(&cmts_list);
1470         res = load_pktccops_config();
1471         AST_LIST_UNLOCK(&cmts_list);
1472         if (res == -1) {
1473                 return AST_MODULE_LOAD_DECLINE;
1474         }
1475         ast_cli_register_multiple(cli_pktccops, sizeof(cli_pktccops) / sizeof(struct ast_cli_entry));
1476         restart_pktc_thread();
1477         return 0;
1478 }
1479
1480 static int unload_module(void)
1481 {
1482         if (!ast_mutex_lock(&pktccops_lock)) {
1483                 if ((pktccops_thread != AST_PTHREADT_NULL) && (pktccops_thread != AST_PTHREADT_STOP)) {
1484                         pthread_cancel(pktccops_thread);
1485                         pthread_kill(pktccops_thread, SIGURG);
1486                         pthread_join(pktccops_thread, NULL);
1487                 }
1488                 pktccops_thread = AST_PTHREADT_STOP;
1489                 ast_mutex_unlock(&pktccops_lock);
1490         } else {
1491                 ast_log(LOG_ERROR, "Unable to lock the pktccops_thread\n");
1492                 return -1;
1493         }
1494
1495         ast_cli_unregister_multiple(cli_pktccops, sizeof(cli_pktccops) / sizeof(struct ast_cli_entry));
1496         pktccops_unregister_cmtses();
1497         pktccops_unregister_ippools();
1498         pktccops_thread = AST_PTHREADT_NULL;
1499         return 0;
1500 }
1501
1502 static int reload_module(void)
1503 {
1504         /* Prohibit unloading */
1505         if (pktcreload) {
1506                 ast_log(LOG_NOTICE, "Previous reload in progress, please wait!\n");
1507                 return -1;
1508         }
1509         pktcreload = 1;
1510         return 0;
1511 }
1512
1513 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_GLOBAL_SYMBOLS, "PktcCOPS manager for MGCP",
1514                 .load = load_module,
1515                 .unload = unload_module,
1516                 .reload = reload_module,
1517                );
1518