Merged revisions 284597 via svnmerge from
[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, SOL_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         struct pollfd *pfds = NULL, *tmp;
707         struct pktcobj *pobject;
708         struct cops_cmts *cmts;
709         struct cops_gate *gate;
710         char *sobjp;
711         uint16_t snst, sobjlen, scommand, recvtrid, actcount, reason, subreason;
712         uint32_t gateid, subscrid, pktcerror;
713         time_t last_exec = 0;
714
715         recmsg = &recmsgb;
716         sendmsg = &sendmsgb;
717
718         ast_debug(3, "COPS: thread started\n");
719
720         for (;;) {
721                 ast_free(pfds);
722                 pfds = NULL;
723                 nfds = 0;
724                 AST_LIST_LOCK(&cmts_list);
725                 AST_LIST_TRAVERSE(&cmts_list, cmts, list) {
726                         if (last_exec != time(NULL)) {
727                                 if (cmts->state == 2 && cmts->katimer + cmts->keepalive < time(NULL)) {
728                                         ast_log(LOG_WARNING, "KA timer (%is) expired cmts: %s\n",  cmts->keepalive, cmts->name);
729                                         cmts->state = 0;
730                                         cmts->katimer = -1;
731                                         close(cmts->sfd);
732                                         cmts->sfd = -1;
733                                 }
734                         }
735                         if (cmts->sfd > 0) {
736                                 if (!(tmp = ast_realloc(pfds, (nfds + 1) * sizeof(*pfds)))) {
737                                         continue;
738                                 }
739                                 pfds = tmp;
740                                 pfds[nfds].fd = cmts->sfd;
741                                 pfds[nfds].events = POLLIN;
742                                 pfds[nfds].revents = 0;
743                                 nfds++;
744                         } else {
745                                 cmts->sfd = cops_connect(cmts->host, cmts->port);
746                                 if (cmts->sfd > 0) {
747                                         cmts->state = 1;
748                                         if (cmts->sfd > 0) {
749                                                 if (!(tmp = ast_realloc(pfds, (nfds + 1) * sizeof(*pfds)))) {
750                                                         continue;
751                                                 }
752                                                 pfds = tmp;
753                                                 pfds[nfds].fd = cmts->sfd;
754                                                 pfds[nfds].events = POLLIN;
755                                                 pfds[nfds].revents = 0;
756                                                 nfds++;
757                                         }
758                                 }
759                         }
760                 }
761                 AST_LIST_UNLOCK(&cmts_list);
762
763                 if (last_exec != time(NULL)) {
764                         last_exec = time(NULL);
765                         AST_LIST_LOCK(&gate_list);
766                         AST_LIST_TRAVERSE_SAFE_BEGIN(&gate_list, gate, list) {
767                                 if (gate) {
768                                         if (gate->deltimer && gate->deltimer < time(NULL)) {
769                                                 gate->deltimer = time(NULL) + 5;
770                                                 gate->trid = cops_trid++;
771                                                 cops_gate_cmd(GATE_DEL, gate->cmts, gate->trid, 0, 0, 0, 0, 0, 0, gate);
772                                                 ast_debug(3, "COPS: requested Gate-Del: CMTS: %s gateid: 0x%x\n", (gate->cmts) ? gate->cmts->name : "null", gate->gateid);
773                                         }
774                                         if (time(NULL) - gate->checked > gatetimeout) {
775                                                 ast_debug(3, "COPS: remove from list GATE, CMTS: %s gateid: 0x%x\n", (gate->cmts) ? gate->cmts->name : "null", gate->gateid);
776                                                 gate->state = GATE_TIMEOUT;
777                                                 PKTCCOPS_DESTROY_CURRENT_GATE;
778                                         } else if (time(NULL) - gate->checked > gateinfoperiod && (gate->state == GATE_ALLOCATED || gate->state == GATE_OPEN)) {
779                                                 if (gate->cmts && (!gate->in_transaction || ( gate->in_transaction + 5 ) < time(NULL))) {
780                                                         gate->trid = cops_trid++;
781                                                         ast_debug(3, "COPS: Gate-Info send to CMTS: %s gateid: 0x%x\n", gate->cmts->name, gate->gateid);
782                                                         cops_gate_cmd(GATE_INFO, gate->cmts, gate->trid, gate->mta, 0, 0, 0, 0, 0, gate);
783                                                 }
784                                         }
785                                 }
786                         }
787                         AST_LIST_TRAVERSE_SAFE_END;
788                         AST_LIST_UNLOCK(&gate_list);
789                 }
790
791                 if (pktcreload == 2) {
792                         pktcreload = 0;
793                 }
794                 if ((res = ast_poll(pfds, nfds, 1000))) {
795                         AST_LIST_LOCK(&cmts_list);
796                         AST_LIST_TRAVERSE(&cmts_list, cmts, list) {
797                                 int idx;
798                                 if ((idx = ast_poll_fd_index(pfds, nfds, cmts->sfd)) > -1 && (pfds[idx].revents & POLLIN)) {
799                                         len = cops_getmsg(cmts->sfd, recmsg);
800                                         if (len > 0) {
801                                                 ast_debug(3, "COPS: got from %s:\n Header: versflag=0x%.2x opcode=%i clienttype=0x%.4x msglength=%i\n",
802                                                         cmts->name, recmsg->verflag, recmsg->opcode, recmsg->clienttype, recmsg->length);
803                                                 if (recmsg->object != NULL) {
804                                                         pobject = recmsg->object;
805                                                         while (pobject != NULL) {
806                                                                 ast_debug(3, " OBJECT: length=%i cnum=%i ctype=%i\n", pobject->length, pobject->cnum, pobject->ctype);
807                                                                 if (recmsg->opcode == 1 && pobject->cnum == 1 && pobject->ctype == 1 ) {
808                                                                         cmts->handle = ntohl(*((uint32_t *) pobject->contents));
809                                                                         ast_debug(3, "    REQ client handle: %i\n", cmts->handle);
810                                                                         cmts->state = 2;
811                                                                         cmts->katimer = time(NULL);
812                                                                 } else if (pobject->cnum == 9 && pobject->ctype == 1) {
813                                                                         sobjp = pobject->contents;
814                                                                         subscrid = 0;
815                                                                         recvtrid = 0;
816                                                                         scommand = 0;
817                                                                         pktcerror = 0;
818                                                                         actcount = 0;
819                                                                         gateid = 0;
820                                                                         reason = 0;
821                                                                         subreason = 0;
822                                                                         while (sobjp < (pobject->contents + pobject->length - 4)) {
823                                                                                 sobjlen = ntohs(*((uint16_t *) sobjp));
824                                                                                 snst = ntohs(*((uint16_t *) (sobjp + 2)));
825                                                                                 ast_debug(3, "   S-Num S-type: 0x%.4x len: %i\n", snst, sobjlen);
826                                                                                 if (snst == 0x0101 ) {
827                                                                                         recvtrid = ntohs(*((uint16_t *) (sobjp + 4)));
828                                                                                         scommand = ntohs(*((uint16_t *) (sobjp + 6)));                                  
829                                                                                         ast_debug(3, "     Transaction Identifier command: %i trid %i\n", scommand, recvtrid);
830                                                                                 } else if (snst == 0x0201) {
831                                                                                         subscrid = ntohl(*((uint32_t *) (sobjp + 4)));
832                                                                                         ast_debug(3, "     Subscriber ID: 0x%.8x\n", subscrid);
833                                                                                 } else if (snst == 0x0301) {
834                                                                                         gateid = ntohl(*((uint32_t *) (sobjp + 4)));
835                                                                                         ast_debug(3, "      Gate ID: 0x%x 0x%.8x\n", gateid, gateid);
836                                                                                 } else if (snst == 0x0401) {
837                                                                                         actcount = ntohs(*((uint16_t *) (sobjp + 6)));
838                                                                                         ast_debug(3, "      Activity Count: %i\n", actcount);
839                                                                                 } else if (snst == 0x0901) {
840                                                                                         pktcerror = ntohl(*((uint32_t *) (sobjp + 4)));
841                                                                                         ast_debug(3, "      PKTC Error: 0x%.8x\n", pktcerror);
842                                                                                 } else if (snst == 0x0d01) {
843                                                                                         reason = ntohs(*((uint16_t *) (sobjp + 4)));
844                                                                                         subreason = ntohs(*((uint16_t *) (sobjp + 6)));
845                                                                                         ast_debug(3, "      Reason: %u Subreason: %u\n", reason, subreason);
846                                                                                 }
847                                                                                 sobjp += sobjlen;
848                                                                                 if (!sobjlen)
849                                                                                         break;
850                                                                         }
851                                                                         if (scommand == PKTCCOPS_SCOMMAND_GATE_CLOSE || scommand == PKTCCOPS_SCOMMAND_GATE_OPEN) {
852                                                                                 AST_LIST_LOCK(&gate_list);
853                                                                                 AST_LIST_TRAVERSE_SAFE_BEGIN(&gate_list, gate, list) {
854                                                                                         if (gate->cmts == cmts && gate->gateid == gateid) {
855                                                                                                 if (scommand == PKTCCOPS_SCOMMAND_GATE_CLOSE && gate->state != GATE_CLOSED && gate->state != GATE_CLOSED_ERR ) {
856                                                                                                         ast_debug(3, "COPS Gate Close Gate ID: 0x%x TrId: %i CMTS: %s\n", gateid, recvtrid, cmts->name);
857                                                                                                         if (subreason) {
858                                                                                                                 gate->state = GATE_CLOSED_ERR;
859                                                                                                                 PKTCCOPS_DESTROY_CURRENT_GATE;
860                                                                                                         } else {
861                                                                                                                 gate->state = GATE_CLOSED;
862                                                                                                                 PKTCCOPS_DESTROY_CURRENT_GATE;
863                                                                                                         }
864                                                                                                         break;
865                                                                                                 } else if (scommand == PKTCCOPS_SCOMMAND_GATE_OPEN && gate->state == GATE_ALLOCATED) {
866                                                                                                         ast_debug(3, "COPS Gate Open Gate ID: 0x%x TrId: %i CMTS: %s\n", gateid, recvtrid, cmts->name);
867                                                                                                         gate->state = GATE_OPEN;
868                                                                                                         if (gate->gate_open) {
869                                                                                                                 ast_debug(3, "Calling GATE-OPEN callback function\n");
870                                                                                                                 gate->gate_open(gate);
871                                                                                                                 gate->gate_open = NULL;
872                                                                                                         }
873                                                                                                         break;
874                                                                                                 } 
875                                                                                         }
876                                                                                 }
877                                                                                 AST_LIST_TRAVERSE_SAFE_END;
878                                                                                 AST_LIST_UNLOCK(&gate_list);
879                                                                         } 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) {
880                                                                                 AST_LIST_LOCK(&gate_list);
881                                                                                 AST_LIST_TRAVERSE_SAFE_BEGIN(&gate_list, gate, list) {
882                                                                                         if (gate->cmts == cmts && gate->trid == recvtrid) {
883                                                                                                 gate->gateid = gateid;
884                                                                                                 gate->checked = time(NULL);
885                                                                                                 if (scommand == PKTCCOPS_SCOMMAND_GATE_SET_ACK) {
886                                                                                                         ast_debug(3, "COPS Gate Set Ack Gate ID: 0x%x TrId: %i CMTS: %s\n", gateid, recvtrid, cmts->name);
887                                                                                                         gate->state = GATE_ALLOCATED;
888                                                                                                         if (gate->got_dq_gi) {
889                                                                                                                 gate->got_dq_gi(gate);
890                                                                                                                 gate->got_dq_gi = NULL;
891                                                                                                         }
892                                                                                                 } else if (scommand == PKTCCOPS_SCOMMAND_GATE_SET_ERR) {
893                                                                                                         ast_debug(3, "COPS Gate Set Error TrId: %i ErrorCode: 0x%.8x CMTS: %s\n ", recvtrid, pktcerror, cmts->name);
894                                                                                                         gate->state = GATE_ALLOC_FAILED;
895                                                                                                         if (gate->got_dq_gi) {
896                                                                                                                 gate->got_dq_gi(gate);
897                                                                                                                 gate->got_dq_gi = NULL;
898                                                                                                         }
899                                                                                                         PKTCCOPS_DESTROY_CURRENT_GATE;
900                                                                                                 } else if (scommand == PKTCCOPS_SCOMMAND_GATE_INFO_ACK) {
901                                                                                                         ast_debug(3, "COPS Gate Info Ack Gate ID: 0x%x TrId: %i CMTS: %s\n", gateid, recvtrid, cmts->name);
902                                                                                                 } else if (scommand == PKTCCOPS_SCOMMAND_GATE_INFO_ERR) {
903                                                                                                         ast_debug(3, "COPS Gate Info Error Gate ID: 0x%x TrId: %i CMTS: %s\n", gateid, recvtrid, cmts->name);
904                                                                                                         gate->state = GATE_ALLOC_FAILED;
905                                                                                                         PKTCCOPS_DESTROY_CURRENT_GATE;
906                                                                                                 } else if (scommand == PKTCCOPS_SCOMMAND_GATE_DELETE_ACK) {
907                                                                                                         ast_debug(3, "COPS Gate Deleted Gate ID: 0x%x TrId: %i CMTS: %s\n", gateid, recvtrid, cmts->name);
908                                                                                                         gate->state = GATE_DELETED;
909                                                                                                         PKTCCOPS_DESTROY_CURRENT_GATE;
910                                                                                                 }
911                                                                                                 gate->in_transaction = 0;
912                                                                                                 break;
913                                                                                         }
914                                                                                 }
915                                                                                 AST_LIST_TRAVERSE_SAFE_END;
916                                                                                 AST_LIST_UNLOCK(&gate_list);
917                                                                         }
918                                                                 }
919                                                                 pobject = pobject->next;
920                                                         }
921                                                 }
922
923                                                 if (recmsg->opcode == 6 && recmsg->object && recmsg->object->cnum == 11 && recmsg->object->ctype == 1) {
924                                                         ast_debug(3, "COPS: Client open %s\n", cmts->name);
925                                                         sendmsg->msg = NULL;
926                                                         sendmsg->verflag = 0x10;
927                                                         sendmsg->opcode = 7; /* Client Accept */
928                                                         sendmsg->clienttype = 0x8008; /* =PacketCable */
929                                                         sendmsg->length = COPS_HEADER_SIZE + COPS_OBJECT_HEADER_SIZE + 4;
930                                                         sendmsg->object = malloc(sizeof(struct pktcobj));
931                                                         sendmsg->object->length = 4 + COPS_OBJECT_HEADER_SIZE;
932                                                         sendmsg->object->cnum = 10; /* keppalive timer*/
933                                                         sendmsg->object->ctype = 1;
934                                                         sendmsg->object->contents = malloc(sizeof(uint32_t));
935                                                         *((uint32_t *) sendmsg->object->contents) = htonl(cmts->keepalive & 0x0000ffff);
936                                                         sendmsg->object->next = NULL;
937                                                         cops_sendmsg(cmts->sfd, sendmsg);
938                                                         cops_freemsg(sendmsg);
939                                                 } else if (recmsg->opcode == 9) {
940                                                         ast_debug(3, "COPS: Keepalive Request got echoing back %s\n", cmts->name);
941                                                         cops_sendmsg(cmts->sfd, recmsg);
942                                                         cmts->state = 2;
943                                                         cmts->katimer = time(NULL);
944                                                 }
945                                         } 
946                                         if (len <= 0) {
947                                                 ast_debug(3, "COPS: lost connection to %s\n", cmts->name);
948                                                 close(cmts->sfd);
949                                                 cmts->sfd = -1;
950                                                 cmts->state = 0;
951                                         }
952                                         cops_freemsg(recmsg);
953                                 }
954                         }
955                         AST_LIST_UNLOCK(&cmts_list);                    
956                 }
957                 if (pktcreload) {
958                         ast_debug(3, "Reloading pktccops...\n");
959                         AST_LIST_LOCK(&gate_list);
960                         AST_LIST_LOCK(&cmts_list);
961                         pktccops_unregister_ippools();
962                         AST_LIST_TRAVERSE(&cmts_list, cmts, list) {
963                                 cmts->need_delete = 1;
964                         }
965                         load_pktccops_config();
966                         AST_LIST_TRAVERSE_SAFE_BEGIN(&cmts_list, cmts, list) {
967                                 if (cmts && cmts->need_delete) {
968                                         AST_LIST_TRAVERSE(&gate_list, gate, list) {
969                                                 if (gate->cmts == cmts) {
970                                                         ast_debug(3, "Null gate %s\n", gate->cmts->name);
971                                                         gate->cmts = NULL;
972                                                 }
973                                                 gate->in_transaction = 0;
974                                         }
975                                         AST_LIST_UNLOCK(&gate_list);
976                                         ast_debug(3, "removing cmts: %s\n", cmts->name);
977                                         if (cmts->sfd > 0) {
978                                                 close(cmts->sfd);
979                                         }
980                                         AST_LIST_REMOVE_CURRENT(list);
981                                         free(cmts);
982                                 }
983                         }
984                         AST_LIST_TRAVERSE_SAFE_END;
985                         AST_LIST_UNLOCK(&cmts_list);
986                         AST_LIST_UNLOCK(&gate_list);
987                         pktcreload = 2;
988                 }
989                 pthread_testcancel();
990         }
991         return NULL;
992 }
993
994 static int restart_pktc_thread(void)
995 {
996         if (pktccops_thread == AST_PTHREADT_STOP) {
997                 return 0;
998         }
999         if (ast_mutex_lock(&pktccops_lock)) {
1000                 ast_log(LOG_WARNING, "Unable to lock pktccops\n");
1001                 return -1;
1002         }
1003         if (pktccops_thread == pthread_self()) {
1004                 ast_mutex_unlock(&pktccops_lock);
1005                 ast_log(LOG_WARNING, "Cannot kill myself\n");
1006                 return -1;
1007         }
1008         if (pktccops_thread != AST_PTHREADT_NULL) {
1009                 /* Wake up the thread */
1010                 pthread_kill(pktccops_thread, SIGURG);
1011         } else {
1012                 /* Start a new monitor */
1013                 if (ast_pthread_create_background(&pktccops_thread, NULL, do_pktccops, NULL) < 0) {
1014                         ast_mutex_unlock(&pktccops_lock);
1015                         ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
1016                         return -1;
1017                 }
1018         }
1019         ast_mutex_unlock(&pktccops_lock);
1020         return 0;
1021 }
1022
1023 static int load_pktccops_config(void)
1024 {
1025         static char *cfg = "res_pktccops.conf";
1026         struct ast_config *config;
1027         struct ast_variable *v;
1028         struct cops_cmts *cmts;
1029         struct cops_ippool *new_ippool;
1030         const char *host, *cat, *port;
1031         int sfd, update;
1032         int res = 0;
1033         uint16_t t1_temp, t7_temp, t8_temp;
1034         uint32_t keepalive_temp;
1035         unsigned int a,b,c,d,e,f,g,h;
1036         struct ast_flags config_flags = {0};
1037
1038         if (!(config = ast_config_load(cfg, config_flags))) {
1039                 ast_log(LOG_WARNING, "Unable to load config file res_pktccops.conf\n");
1040                 return -1;
1041         }
1042         for (cat = ast_category_browse(config, NULL); cat; cat = ast_category_browse(config, cat)) {
1043                 if (!strcmp(cat, "general")) {
1044                         for (v = ast_variable_browse(config, cat); v; v = v->next) {
1045                                 if (!strcasecmp(v->name, "t1")) {
1046                                         t1 = atoi(v->value);
1047                                 } else if (!strcasecmp(v->name, "t7")) {
1048                                         t7 = atoi(v->value);
1049                                 } else if (!strcasecmp(v->name, "t8")) {
1050                                         t8 = atoi(v->value);
1051                                 } else if (!strcasecmp(v->name, "keepalive")) {
1052                                         keepalive = atoi(v->value);
1053                                 } else if (!strcasecmp(v->name, "gateinfoperiod")) {
1054                                         gateinfoperiod = atoi(v->value);
1055                                 } else if (!strcasecmp(v->name, "gatetimeout")) {
1056                                         gatetimeout = atoi(v->value);
1057                                 } else {
1058                                         ast_log(LOG_WARNING, "Unkown option %s in general section of res_ptkccops.conf\n", v->name);
1059                                 }
1060                         }                       
1061                 } else {
1062                         /* Defaults */
1063                         host = NULL;
1064                         port = NULL;
1065                         sfd = 0;
1066                         t1_temp = t1;
1067                         t7_temp = t7;
1068                         t8_temp = t8;
1069                         keepalive_temp = keepalive;
1070
1071                         for (v = ast_variable_browse(config, cat); v; v = v->next) {
1072                                 if (!strcasecmp(v->name, "host")) {
1073                                         host = v->value;                                
1074                                 } else if (!strcasecmp(v->name, "port")) {
1075                                         port = v->value;
1076                                 } else if (!strcasecmp(v->name, "t1")) {
1077                                         t1_temp = atoi(v->value);
1078                                 } else if (!strcasecmp(v->name, "t7")) {
1079                                         t7_temp = atoi(v->value);
1080                                 } else if (!strcasecmp(v->name, "t8")) {
1081                                         t8_temp = atoi(v->value);
1082                                 } else if (!strcasecmp(v->name, "keepalive")) {
1083                                         keepalive_temp = atoi(v->value);
1084                                 } else if (!strcasecmp(v->name, "pool")) {
1085                                         /* we weill parse it in 2nd round */
1086                                 } else {
1087                                         ast_log(LOG_WARNING, "Unkown option %s in res_ptkccops.conf\n", v->name);
1088                                 }
1089                         }
1090
1091                         update = 0;
1092                         AST_LIST_TRAVERSE(&cmts_list, cmts, list) {
1093                                 if (!strcmp(cmts->name, cat)) {
1094                                         update = 1;
1095                                         break;
1096                                 }
1097
1098                         }
1099                         if (!update) {
1100                                 cmts = ast_calloc(1, sizeof(*cmts));
1101                                 if (!cmts) {
1102                                         res = -1;
1103                                         break;
1104                                 }
1105                                 AST_LIST_INSERT_HEAD(&cmts_list, cmts, list);
1106                         }
1107                         if (cat) {
1108                                 ast_copy_string(cmts->name, cat, sizeof(cmts->name));
1109                         }
1110                         if (host) {
1111                                 ast_copy_string(cmts->host, host, sizeof(cmts->host));
1112                         }
1113                         if (port) {
1114                                 ast_copy_string(cmts->port, port, sizeof(cmts->port));
1115                         } else {
1116                                 ast_copy_string(cmts->port, DEFAULT_COPS_PORT, sizeof(cmts->port));
1117                         }
1118
1119                         cmts->t1 = t1_temp;
1120                         cmts->t7 = t7_temp;
1121                         cmts->t8 = t8_temp;
1122                         cmts->keepalive = keepalive_temp;
1123                         if (!update) {
1124                                 cmts->state = 0;
1125                                 cmts->sfd = -1;
1126                         }
1127                         cmts->need_delete = 0;
1128                         for (v = ast_variable_browse(config, cat); v; v = v->next) {
1129                                 /* parse ipppol when we have cmts ptr */
1130                                 if (!strcasecmp(v->name, "pool")) {
1131                                         if (sscanf(v->value, "%3u.%3u.%3u.%3u %3u.%3u.%3u.%3u", &a, &b, &c, &d, &e, &f, &g, &h) == 8) {
1132                                                 new_ippool = ast_calloc(1, sizeof(*new_ippool));
1133                                                 if (!new_ippool) {
1134                                                         res = -1;
1135                                                         break;
1136                                                 }
1137                                                 new_ippool->start = a << 24 | b << 16 | c << 8 | d;
1138                                                 new_ippool->stop = e << 24 | f << 16 | g << 8 | h;
1139                                                 new_ippool->cmts = cmts;
1140                                                 pktccops_add_ippool(new_ippool);
1141                                         } else {
1142                                                 ast_log(LOG_WARNING, "Invalid ip pool format in res_pktccops.conf\n");
1143                                         }
1144                                 }
1145                         }
1146                 }
1147         }
1148         ast_config_destroy(config);
1149         return res;
1150 }
1151
1152 static char *pktccops_show_cmtses(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1153 {
1154         struct cops_cmts *cmts;
1155         char statedesc[16];
1156         int katimer;
1157         
1158         switch(cmd) {
1159         case CLI_INIT:
1160                 e->command = "pktccops show cmtses";
1161                 e->usage = 
1162                         "Usage: pktccops show cmtses\n"
1163                         "       List PacketCable COPS CMTSes.\n";
1164
1165                 return NULL;
1166         case CLI_GENERATE:
1167                 return NULL;
1168         }
1169
1170         ast_cli(a->fd, "%-16s %-24s %-12s %7s\n", "Name        ", "Host                ", "Status    ", "KA timer  ");
1171         ast_cli(a->fd, "%-16s %-24s %-12s %7s\n", "------------", "--------------------", "----------", "-----------");
1172         AST_LIST_LOCK(&cmts_list);
1173         AST_LIST_TRAVERSE(&cmts_list, cmts, list) {
1174                 katimer = -1;
1175                 if (cmts->state == 2) {
1176                         ast_copy_string(statedesc, "Connected", sizeof(statedesc));
1177                         katimer = (int) (time(NULL) - cmts->katimer);
1178                 } else if (cmts->state == 1) {
1179                         ast_copy_string(statedesc, "Connecting", sizeof(statedesc));
1180                 } else {
1181                         ast_copy_string(statedesc, "N/A", sizeof(statedesc));
1182                 }
1183                 ast_cli(a->fd, "%-16s %-15s:%-8s %-12s %-7d\n", cmts->name, cmts->host, cmts->port, statedesc, katimer);
1184         }
1185         AST_LIST_UNLOCK(&cmts_list);
1186         return CLI_SUCCESS;
1187 }
1188
1189 static char *pktccops_show_gates(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1190 {
1191         struct cops_gate *gate;
1192         char state_desc[16];
1193
1194         switch(cmd) {
1195         case CLI_INIT:
1196                 e->command = "pktccops show gates";
1197                 e->usage = 
1198                         "Usage: pktccops show gates\n"
1199                         "       List PacketCable COPS GATEs.\n";
1200
1201                 return NULL;
1202         case CLI_GENERATE:
1203                 return NULL;
1204         }
1205
1206         ast_cli(a->fd, "%-16s %-12s %-12s %-10s %-10s %-10s\n" ,"CMTS", "Gate-Id","MTA", "Status", "AllocTime", "CheckTime");
1207         ast_cli(a->fd, "%-16s %-12s %-12s %-10s %-10s %-10s\n" ,"--------------" ,"----------", "----------", "--------", "--------", "--------\n");
1208         AST_LIST_LOCK(&cmts_list);
1209         AST_LIST_LOCK(&gate_list);
1210         AST_LIST_TRAVERSE(&gate_list, gate, list) {
1211                 if (gate->state == GATE_ALLOC_FAILED) {
1212                         ast_copy_string(state_desc, "Failed", sizeof(state_desc));
1213                 } else if (gate->state == GATE_ALLOC_PROGRESS) {
1214                         ast_copy_string(state_desc, "In Progress", sizeof(state_desc));
1215                 } else if (gate->state == GATE_ALLOCATED) {
1216                         ast_copy_string(state_desc, "Allocated", sizeof(state_desc));
1217                 } else if (gate->state == GATE_CLOSED) {
1218                         ast_copy_string(state_desc, "Closed", sizeof(state_desc));
1219                 } else if (gate->state == GATE_CLOSED_ERR) {
1220                         ast_copy_string(state_desc, "ClosedErr", sizeof(state_desc));
1221                 } else if (gate->state == GATE_OPEN) {
1222                         ast_copy_string(state_desc, "Open", sizeof(state_desc));
1223                 } else if (gate->state == GATE_DELETED) {
1224                         ast_copy_string(state_desc, "Deleted", sizeof(state_desc));
1225                 } else {
1226                         ast_copy_string(state_desc, "N/A", sizeof(state_desc));
1227                 }
1228                 
1229                 ast_cli(a->fd, "%-16s 0x%.8x   0x%08x   %-10s %10i %10i %u\n", (gate->cmts) ? gate->cmts->name : "null" , gate->gateid, gate->mta, 
1230                         state_desc, (int) (time(NULL) - gate->allocated), (gate->checked) ? (int) (time(NULL) - gate->checked) : 0, (unsigned int) gate->in_transaction);
1231         }
1232         AST_LIST_UNLOCK(&cmts_list);
1233         AST_LIST_UNLOCK(&gate_list);
1234         return CLI_SUCCESS;
1235 }
1236
1237 static char *pktccops_show_pools(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1238 {
1239         struct cops_ippool *ippool;
1240         char start[32];
1241         char stop[32];
1242
1243         switch(cmd) {
1244         case CLI_INIT:
1245                 e->command = "pktccops show pools";
1246                 e->usage = 
1247                         "Usage: pktccops show pools\n"
1248                         "       List PacketCable COPS ip pools of MTAs.\n";
1249
1250                 return NULL;
1251         case CLI_GENERATE:
1252                 return NULL;
1253         }
1254
1255         ast_cli(a->fd, "%-16s %-18s %-7s\n", "Start     ", "Stop      ", "CMTS    ");
1256         ast_cli(a->fd, "%-16s %-18s %-7s\n", "----------", "----------", "--------");
1257         AST_LIST_LOCK(&ippool_list);
1258         AST_LIST_TRAVERSE(&ippool_list, ippool, list) {
1259                 snprintf(start, sizeof(start), "%3u.%3u.%3u.%3u", ippool->start >> 24, (ippool->start >> 16) & 0x000000ff, (ippool->start >> 8) & 0x000000ff, ippool->start & 0x000000ff);
1260
1261                 snprintf(stop, sizeof(stop), "%3u.%3u.%3u.%3u", ippool->stop >> 24, (ippool->stop >> 16) & 0x000000ff, (ippool->stop >> 8) & 0x000000ff, ippool->stop & 0x000000ff);
1262                 ast_cli(a->fd, "%-16s %-18s %-16s\n", start, stop, ippool->cmts->name);
1263         }
1264         AST_LIST_UNLOCK(&ippool_list);
1265         return CLI_SUCCESS;
1266 }
1267
1268 static char *pktccops_gatedel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1269 {
1270         int found = 0;
1271         int trid;
1272         uint32_t gateid;
1273         struct cops_gate *gate;
1274         struct cops_cmts *cmts;
1275
1276         switch (cmd) {
1277         case CLI_INIT:
1278                 e->command = "pktccops gatedel";
1279                 e->usage = 
1280                         "Usage: pktccops gatedel <cmts> <gateid>\n"
1281                         "       Send Gate-Del to cmts.\n";
1282                 return NULL;
1283         case CLI_GENERATE:
1284                 return NULL;
1285         }
1286
1287         if (a->argc < 4)
1288                 return CLI_SHOWUSAGE;
1289
1290         AST_LIST_LOCK(&cmts_list);
1291         AST_LIST_TRAVERSE(&cmts_list, cmts, list) {
1292                 if (!strcmp(cmts->name, a->argv[2])) {
1293                         ast_cli(a->fd, "Found cmts: %s\n", cmts->name);
1294                         found = 1;
1295                         break;
1296                 }
1297         }
1298         AST_LIST_UNLOCK(&cmts_list);
1299         
1300         if (!found)
1301                 return CLI_SHOWUSAGE;
1302
1303         trid = cops_trid++;
1304         if (!sscanf(a->argv[3], "%x", &gateid)) {
1305                 ast_cli(a->fd, "bad gate specification (%s)\n", a->argv[3]);    
1306                 return CLI_SHOWUSAGE;
1307         }
1308
1309         found = 0;
1310         AST_LIST_LOCK(&gate_list);
1311         AST_LIST_TRAVERSE(&gate_list, gate, list) {
1312                 if (gate->gateid == gateid && gate->cmts == cmts) {
1313                         found = 1;
1314                         break;
1315                 }
1316         }
1317                 
1318         if (!found) {
1319                 ast_cli(a->fd, "gate not found: %s\n", a->argv[3]);
1320                 return CLI_SHOWUSAGE;
1321         }
1322
1323         AST_LIST_UNLOCK(&gate_list);
1324         cops_gate_cmd(GATE_DEL, cmts, trid, 0, 0, 0, 0, 0, 0, gate);
1325         return CLI_SUCCESS;
1326 }
1327
1328 static char *pktccops_gateset(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1329 {
1330         int foundcmts = 0;
1331         int trid;
1332         unsigned int an,bn,cn,dn;
1333         uint32_t mta, ssip;
1334         struct cops_cmts *cmts;
1335         struct cops_gate *gate;
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 (!strncmp(a->argv[2], "null", sizeof(a->argv[2]))) {
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         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);
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