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