Merge "ari: Implement 'debug all' and request/response logging"
[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, flags;
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                 flags = fcntl(sfd, F_GETFL);
678                 fcntl(sfd, F_SETFL, flags | O_NONBLOCK);
679 #ifdef HAVE_SO_NOSIGPIPE
680                 setsockopt(sfd, SOL_SOCKET, SO_NOSIGPIPE, &trueval, sizeof(trueval));
681 #endif
682                 connect(sfd, rp->ai_addr, rp->ai_addrlen);
683                 if (sfd == -1) {
684                         ast_log(LOG_WARNING, "Failed connect\n");
685                 }
686         }
687         freeaddrinfo(result);
688
689         ast_debug(3, "Connecting to cmts:  %s:%s\n", host, port);
690         return(sfd);
691 }
692
693 #define PKTCCOPS_DESTROY_CURRENT_GATE   \
694                 AST_LIST_REMOVE_CURRENT(list);  \
695                 if (gate->gate_remove) {        \
696                         gate->gate_remove(gate);    \
697                 }                               \
698                 ast_free(gate);
699
700 static void *do_pktccops(void *data)
701 {
702         int res, nfds, len;
703         struct copsmsg *recmsg, *sendmsg;
704         struct copsmsg recmsgb, sendmsgb;
705         struct pollfd *pfds = NULL, *tmp;
706         struct pktcobj *pobject;
707         struct cops_cmts *cmts;
708         struct cops_gate *gate;
709         char *sobjp;
710         uint16_t snst, sobjlen, scommand, recvtrid, actcount, reason, subreason;
711         uint32_t gateid, subscrid, pktcerror;
712         time_t last_exec = 0;
713
714         recmsg = &recmsgb;
715         sendmsg = &sendmsgb;
716
717         ast_debug(3, "COPS: thread started\n");
718
719         for (;;) {
720                 ast_free(pfds);
721                 pfds = NULL;
722                 nfds = 0;
723                 AST_LIST_LOCK(&cmts_list);
724                 AST_LIST_TRAVERSE(&cmts_list, cmts, list) {
725                         if (last_exec != time(NULL)) {
726                                 if (cmts->state == 2 && cmts->katimer + cmts->keepalive < time(NULL)) {
727                                         ast_log(LOG_WARNING, "KA timer (%us) expired cmts: %s\n",  cmts->keepalive, cmts->name);
728                                         cmts->state = 0;
729                                         cmts->katimer = -1;
730                                         close(cmts->sfd);
731                                         cmts->sfd = -1;
732                                 }
733                         }
734                         if (cmts->sfd > 0) {
735                                 if (!(tmp = ast_realloc(pfds, (nfds + 1) * sizeof(*pfds)))) {
736                                         continue;
737                                 }
738                                 pfds = tmp;
739                                 pfds[nfds].fd = cmts->sfd;
740                                 pfds[nfds].events = POLLIN;
741                                 pfds[nfds].revents = 0;
742                                 nfds++;
743                         } else {
744                                 cmts->sfd = cops_connect(cmts->host, cmts->port);
745                                 if (cmts->sfd > 0) {
746                                         cmts->state = 1;
747                                         if (cmts->sfd > 0) {
748                                                 if (!(tmp = ast_realloc(pfds, (nfds + 1) * sizeof(*pfds)))) {
749                                                         continue;
750                                                 }
751                                                 pfds = tmp;
752                                                 pfds[nfds].fd = cmts->sfd;
753                                                 pfds[nfds].events = POLLIN;
754                                                 pfds[nfds].revents = 0;
755                                                 nfds++;
756                                         }
757                                 }
758                         }
759                 }
760                 AST_LIST_UNLOCK(&cmts_list);
761
762                 if (last_exec != time(NULL)) {
763                         last_exec = time(NULL);
764                         AST_LIST_LOCK(&gate_list);
765                         AST_LIST_TRAVERSE_SAFE_BEGIN(&gate_list, gate, list) {
766                                 if (gate) {
767                                         if (gate->deltimer && gate->deltimer < time(NULL)) {
768                                                 gate->deltimer = time(NULL) + 5;
769                                                 gate->trid = cops_trid++;
770                                                 cops_gate_cmd(GATE_DEL, gate->cmts, gate->trid, 0, 0, 0, 0, 0, 0, gate);
771                                                 ast_debug(3, "COPS: requested Gate-Del: CMTS: %s gateid: 0x%x\n", (gate->cmts) ? gate->cmts->name : "null", gate->gateid);
772                                         }
773                                         if (time(NULL) - gate->checked > gatetimeout) {
774                                                 ast_debug(3, "COPS: remove from list GATE, CMTS: %s gateid: 0x%x\n", (gate->cmts) ? gate->cmts->name : "null", gate->gateid);
775                                                 gate->state = GATE_TIMEOUT;
776                                                 PKTCCOPS_DESTROY_CURRENT_GATE;
777                                         } else if (time(NULL) - gate->checked > gateinfoperiod && (gate->state == GATE_ALLOCATED || gate->state == GATE_OPEN)) {
778                                                 if (gate->cmts && (!gate->in_transaction || ( gate->in_transaction + 5 ) < time(NULL))) {
779                                                         gate->trid = cops_trid++;
780                                                         ast_debug(3, "COPS: Gate-Info send to CMTS: %s gateid: 0x%x\n", gate->cmts->name, gate->gateid);
781                                                         cops_gate_cmd(GATE_INFO, gate->cmts, gate->trid, gate->mta, 0, 0, 0, 0, 0, gate);
782                                                 }
783                                         }
784                                 }
785                         }
786                         AST_LIST_TRAVERSE_SAFE_END;
787                         AST_LIST_UNLOCK(&gate_list);
788                 }
789
790                 if (pktcreload == 2) {
791                         pktcreload = 0;
792                 }
793                 if ((res = ast_poll(pfds, nfds, 1000))) {
794                         AST_LIST_LOCK(&cmts_list);
795                         AST_LIST_TRAVERSE(&cmts_list, cmts, list) {
796                                 int idx;
797                                 if ((idx = ast_poll_fd_index(pfds, nfds, cmts->sfd)) > -1 && (pfds[idx].revents & POLLIN)) {
798                                         len = cops_getmsg(cmts->sfd, recmsg);
799                                         if (len > 0) {
800                                                 ast_debug(3, "COPS: got from %s:\n Header: versflag=0x%02hhx opcode=%i clienttype=0x%04hx msglength=%u\n",
801                                                         cmts->name, recmsg->verflag,
802                                                         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: %u\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", (unsigned)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: %d Subreason: %d\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 = ast_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 = ast_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                                         ast_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 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                         t1_temp = t1;
1066                         t7_temp = t7;
1067                         t8_temp = t8;
1068                         keepalive_temp = keepalive;
1069
1070                         for (v = ast_variable_browse(config, cat); v; v = v->next) {
1071                                 if (!strcasecmp(v->name, "host")) {
1072                                         host = v->value;                                
1073                                 } else if (!strcasecmp(v->name, "port")) {
1074                                         port = v->value;
1075                                 } else if (!strcasecmp(v->name, "t1")) {
1076                                         t1_temp = atoi(v->value);
1077                                 } else if (!strcasecmp(v->name, "t7")) {
1078                                         t7_temp = atoi(v->value);
1079                                 } else if (!strcasecmp(v->name, "t8")) {
1080                                         t8_temp = atoi(v->value);
1081                                 } else if (!strcasecmp(v->name, "keepalive")) {
1082                                         keepalive_temp = atoi(v->value);
1083                                 } else if (!strcasecmp(v->name, "pool")) {
1084                                         /* we weill parse it in 2nd round */
1085                                 } else {
1086                                         ast_log(LOG_WARNING, "Unkown option %s in res_ptkccops.conf\n", v->name);
1087                                 }
1088                         }
1089
1090                         update = 0;
1091                         AST_LIST_TRAVERSE(&cmts_list, cmts, list) {
1092                                 if (!strcmp(cmts->name, cat)) {
1093                                         update = 1;
1094                                         break;
1095                                 }
1096
1097                         }
1098                         if (!update) {
1099                                 cmts = ast_calloc(1, sizeof(*cmts));
1100                                 if (!cmts) {
1101                                         res = -1;
1102                                         break;
1103                                 }
1104                                 AST_LIST_INSERT_HEAD(&cmts_list, cmts, list);
1105                         }
1106                         if (cat) {
1107                                 ast_copy_string(cmts->name, cat, sizeof(cmts->name));
1108                         }
1109                         if (host) {
1110                                 ast_copy_string(cmts->host, host, sizeof(cmts->host));
1111                         }
1112                         if (port) {
1113                                 ast_copy_string(cmts->port, port, sizeof(cmts->port));
1114                         } else {
1115                                 ast_copy_string(cmts->port, DEFAULT_COPS_PORT, sizeof(cmts->port));
1116                         }
1117
1118                         cmts->t1 = t1_temp;
1119                         cmts->t7 = t7_temp;
1120                         cmts->t8 = t8_temp;
1121                         cmts->keepalive = keepalive_temp;
1122                         if (!update) {
1123                                 cmts->state = 0;
1124                                 cmts->sfd = -1;
1125                         }
1126                         cmts->need_delete = 0;
1127                         for (v = ast_variable_browse(config, cat); v; v = v->next) {
1128                                 /* parse ipppol when we have cmts ptr */
1129                                 if (!strcasecmp(v->name, "pool")) {
1130                                         if (sscanf(v->value, "%3u.%3u.%3u.%3u %3u.%3u.%3u.%3u", &a, &b, &c, &d, &e, &f, &g, &h) == 8) {
1131                                                 new_ippool = ast_calloc(1, sizeof(*new_ippool));
1132                                                 if (!new_ippool) {
1133                                                         res = -1;
1134                                                         break;
1135                                                 }
1136                                                 new_ippool->start = a << 24 | b << 16 | c << 8 | d;
1137                                                 new_ippool->stop = e << 24 | f << 16 | g << 8 | h;
1138                                                 new_ippool->cmts = cmts;
1139                                                 pktccops_add_ippool(new_ippool);
1140                                         } else {
1141                                                 ast_log(LOG_WARNING, "Invalid ip pool format in res_pktccops.conf\n");
1142                                         }
1143                                 }
1144                         }
1145                 }
1146         }
1147         ast_config_destroy(config);
1148         return res;
1149 }
1150
1151 static char *pktccops_show_cmtses(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1152 {
1153         struct cops_cmts *cmts;
1154         char statedesc[16];
1155         int katimer;
1156         
1157         switch(cmd) {
1158         case CLI_INIT:
1159                 e->command = "pktccops show cmtses";
1160                 e->usage = 
1161                         "Usage: pktccops show cmtses\n"
1162                         "       List PacketCable COPS CMTSes.\n";
1163
1164                 return NULL;
1165         case CLI_GENERATE:
1166                 return NULL;
1167         }
1168
1169         ast_cli(a->fd, "%-16s %-24s %-12s %7s\n", "Name        ", "Host                ", "Status    ", "KA timer  ");
1170         ast_cli(a->fd, "%-16s %-24s %-12s %7s\n", "------------", "--------------------", "----------", "-----------");
1171         AST_LIST_LOCK(&cmts_list);
1172         AST_LIST_TRAVERSE(&cmts_list, cmts, list) {
1173                 katimer = -1;
1174                 if (cmts->state == 2) {
1175                         ast_copy_string(statedesc, "Connected", sizeof(statedesc));
1176                         katimer = (int) (time(NULL) - cmts->katimer);
1177                 } else if (cmts->state == 1) {
1178                         ast_copy_string(statedesc, "Connecting", sizeof(statedesc));
1179                 } else {
1180                         ast_copy_string(statedesc, "N/A", sizeof(statedesc));
1181                 }
1182                 ast_cli(a->fd, "%-16s %-15s:%-8s %-12s %-7d\n", cmts->name, cmts->host, cmts->port, statedesc, katimer);
1183         }
1184         AST_LIST_UNLOCK(&cmts_list);
1185         return CLI_SUCCESS;
1186 }
1187
1188 static char *pktccops_show_gates(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1189 {
1190         struct cops_gate *gate;
1191         char state_desc[16];
1192
1193         switch(cmd) {
1194         case CLI_INIT:
1195                 e->command = "pktccops show gates";
1196                 e->usage = 
1197                         "Usage: pktccops show gates\n"
1198                         "       List PacketCable COPS GATEs.\n";
1199
1200                 return NULL;
1201         case CLI_GENERATE:
1202                 return NULL;
1203         }
1204
1205         ast_cli(a->fd, "%-16s %-12s %-12s %-10s %-10s %-10s\n" ,"CMTS", "Gate-Id","MTA", "Status", "AllocTime", "CheckTime");
1206         ast_cli(a->fd, "%-16s %-12s %-12s %-10s %-10s %-10s\n" ,"--------------" ,"----------", "----------", "--------", "--------", "--------\n");
1207         AST_LIST_LOCK(&cmts_list);
1208         AST_LIST_LOCK(&gate_list);
1209         AST_LIST_TRAVERSE(&gate_list, gate, list) {
1210                 if (gate->state == GATE_ALLOC_FAILED) {
1211                         ast_copy_string(state_desc, "Failed", sizeof(state_desc));
1212                 } else if (gate->state == GATE_ALLOC_PROGRESS) {
1213                         ast_copy_string(state_desc, "In Progress", sizeof(state_desc));
1214                 } else if (gate->state == GATE_ALLOCATED) {
1215                         ast_copy_string(state_desc, "Allocated", sizeof(state_desc));
1216                 } else if (gate->state == GATE_CLOSED) {
1217                         ast_copy_string(state_desc, "Closed", sizeof(state_desc));
1218                 } else if (gate->state == GATE_CLOSED_ERR) {
1219                         ast_copy_string(state_desc, "ClosedErr", sizeof(state_desc));
1220                 } else if (gate->state == GATE_OPEN) {
1221                         ast_copy_string(state_desc, "Open", sizeof(state_desc));
1222                 } else if (gate->state == GATE_DELETED) {
1223                         ast_copy_string(state_desc, "Deleted", sizeof(state_desc));
1224                 } else {
1225                         ast_copy_string(state_desc, "N/A", sizeof(state_desc));
1226                 }
1227                 
1228                 ast_cli(a->fd, "%-16s 0x%.8x   0x%08x   %-10s %10i %10i %u\n", (gate->cmts) ? gate->cmts->name : "null" , gate->gateid, gate->mta, 
1229                         state_desc, (int) (time(NULL) - gate->allocated), (gate->checked) ? (int) (time(NULL) - gate->checked) : 0, (unsigned int) gate->in_transaction);
1230         }
1231         AST_LIST_UNLOCK(&cmts_list);
1232         AST_LIST_UNLOCK(&gate_list);
1233         return CLI_SUCCESS;
1234 }
1235
1236 static char *pktccops_show_pools(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1237 {
1238         struct cops_ippool *ippool;
1239         char start[32];
1240         char stop[32];
1241
1242         switch(cmd) {
1243         case CLI_INIT:
1244                 e->command = "pktccops show pools";
1245                 e->usage = 
1246                         "Usage: pktccops show pools\n"
1247                         "       List PacketCable COPS ip pools of MTAs.\n";
1248
1249                 return NULL;
1250         case CLI_GENERATE:
1251                 return NULL;
1252         }
1253
1254         ast_cli(a->fd, "%-16s %-18s %-7s\n", "Start     ", "Stop      ", "CMTS    ");
1255         ast_cli(a->fd, "%-16s %-18s %-7s\n", "----------", "----------", "--------");
1256         AST_LIST_LOCK(&ippool_list);
1257         AST_LIST_TRAVERSE(&ippool_list, ippool, list) {
1258                 snprintf(start, sizeof(start), "%3u.%3u.%3u.%3u", ippool->start >> 24, (ippool->start >> 16) & 0x000000ff, (ippool->start >> 8) & 0x000000ff, ippool->start & 0x000000ff);
1259
1260                 snprintf(stop, sizeof(stop), "%3u.%3u.%3u.%3u", ippool->stop >> 24, (ippool->stop >> 16) & 0x000000ff, (ippool->stop >> 8) & 0x000000ff, ippool->stop & 0x000000ff);
1261                 ast_cli(a->fd, "%-16s %-18s %-16s\n", start, stop, ippool->cmts->name);
1262         }
1263         AST_LIST_UNLOCK(&ippool_list);
1264         return CLI_SUCCESS;
1265 }
1266
1267 static char *pktccops_gatedel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1268 {
1269         int found = 0;
1270         int trid;
1271         uint32_t gateid;
1272         struct cops_gate *gate;
1273         struct cops_cmts *cmts;
1274
1275         switch (cmd) {
1276         case CLI_INIT:
1277                 e->command = "pktccops gatedel";
1278                 e->usage = 
1279                         "Usage: pktccops gatedel <cmts> <gateid>\n"
1280                         "       Send Gate-Del to cmts.\n";
1281                 return NULL;
1282         case CLI_GENERATE:
1283                 return NULL;
1284         }
1285
1286         if (a->argc < 4)
1287                 return CLI_SHOWUSAGE;
1288
1289         AST_LIST_LOCK(&cmts_list);
1290         AST_LIST_TRAVERSE(&cmts_list, cmts, list) {
1291                 if (!strcmp(cmts->name, a->argv[2])) {
1292                         ast_cli(a->fd, "Found cmts: %s\n", cmts->name);
1293                         found = 1;
1294                         break;
1295                 }
1296         }
1297         AST_LIST_UNLOCK(&cmts_list);
1298         
1299         if (!found)
1300                 return CLI_SHOWUSAGE;
1301
1302         trid = cops_trid++;
1303         if (!sscanf(a->argv[3], "%x", &gateid)) {
1304                 ast_cli(a->fd, "bad gate specification (%s)\n", a->argv[3]);    
1305                 return CLI_SHOWUSAGE;
1306         }
1307
1308         found = 0;
1309         AST_LIST_LOCK(&gate_list);
1310         AST_LIST_TRAVERSE(&gate_list, gate, list) {
1311                 if (gate->gateid == gateid && gate->cmts == cmts) {
1312                         found = 1;
1313                         break;
1314                 }
1315         }
1316                 
1317         if (!found) {
1318                 ast_cli(a->fd, "gate not found: %s\n", a->argv[3]);
1319                 return CLI_SHOWUSAGE;
1320         }
1321
1322         AST_LIST_UNLOCK(&gate_list);
1323         cops_gate_cmd(GATE_DEL, cmts, trid, 0, 0, 0, 0, 0, 0, gate);
1324         return CLI_SUCCESS;
1325 }
1326
1327 static char *pktccops_gateset(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1328 {
1329         int foundcmts = 0;
1330         int trid;
1331         unsigned int an,bn,cn,dn;
1332         uint32_t mta, ssip;
1333         struct cops_cmts *cmts;
1334
1335         switch (cmd) {
1336         case CLI_INIT:
1337                 e->command = "pktccops gateset";
1338                 e->usage = 
1339                         "Usage: pktccops gateset <cmts> <mta> <acctcount> <bitrate> <packet size> <switch ip> <switch port>\n"
1340                         "       Send Gate-Set to cmts.\n";
1341                 return NULL;
1342         case CLI_GENERATE:
1343                 return NULL;
1344         }
1345
1346         if (a->argc < 9)
1347                 return CLI_SHOWUSAGE;
1348
1349         if (!strcmp(a->argv[2], "null")) {
1350                 cmts = NULL;
1351         } else {
1352                 AST_LIST_LOCK(&cmts_list);
1353                 AST_LIST_TRAVERSE(&cmts_list, cmts, list) {
1354                         if (!strcmp(cmts->name, a->argv[2])) {
1355                                 ast_cli(a->fd, "Found cmts: %s\n", cmts->name);
1356                                 foundcmts = 1;
1357                                 break;
1358                         }
1359                 }
1360                 AST_LIST_UNLOCK(&cmts_list);
1361                 if (!foundcmts) {
1362                         ast_cli(a->fd, "CMTS not found: %s\n", a->argv[2]);
1363                         return CLI_SHOWUSAGE;
1364                 }
1365         }
1366
1367         trid = cops_trid++;
1368         if (sscanf(a->argv[3], "%3u.%3u.%3u.%3u", &an, &bn, &cn, &dn) != 4) {
1369                 ast_cli(a->fd, "MTA specification (%s) does not look like an ipaddr\n", a->argv[3]);
1370                 return CLI_SHOWUSAGE;
1371         }
1372         mta = an << 24 | bn << 16 | cn << 8 | dn;
1373
1374         if (sscanf(a->argv[7], "%3u.%3u.%3u.%3u", &an, &bn, &cn, &dn) != 4) {
1375                 ast_cli(a->fd, "SSIP specification (%s) does not look like an ipaddr\n", a->argv[7]);
1376                 return CLI_SHOWUSAGE;
1377         }
1378         ssip = an << 24 | bn << 16 | cn << 8 | dn;
1379
1380         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);
1381         return CLI_SUCCESS;
1382 }
1383
1384 static char *pktccops_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
1385 {
1386         switch (cmd) {
1387         case CLI_INIT:
1388                 e->command = "pktccops set debug {on|off}";
1389                 e->usage = 
1390                         "Usage: pktccops set debug {on|off}\n"
1391                         "       Turn on/off debuging\n";
1392                 return NULL;
1393         case CLI_GENERATE:
1394                 return NULL;
1395         }
1396
1397         if (a->argc != e->args)
1398                 return CLI_SHOWUSAGE;
1399         if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
1400                 pktccopsdebug = 1;
1401                 ast_cli(a->fd, "PktcCOPS Debugging Enabled\n");
1402         } else if (!strncasecmp(a->argv[e->args - 1], "off", 2)) {
1403                 pktccopsdebug = 0;
1404                 ast_cli(a->fd, "PktcCOPS Debugging Disabled\n");
1405         } else {
1406                 return CLI_SHOWUSAGE;
1407         }
1408         return CLI_SUCCESS;
1409
1410 }
1411
1412 static struct ast_cli_entry cli_pktccops[] = {
1413         AST_CLI_DEFINE(pktccops_show_cmtses, "List PacketCable COPS CMTSes"),
1414         AST_CLI_DEFINE(pktccops_show_gates, "List PacketCable COPS GATEs"),
1415         AST_CLI_DEFINE(pktccops_show_pools, "List PacketCable MTA pools"),
1416         AST_CLI_DEFINE(pktccops_gateset, "Send Gate-Set to cmts"),
1417         AST_CLI_DEFINE(pktccops_gatedel, "Send Gate-Det to cmts"),
1418         AST_CLI_DEFINE(pktccops_debug, "Enable/Disable COPS debugging")
1419 };
1420
1421 static int pktccops_add_ippool(struct cops_ippool *ippool)
1422 {
1423         if (ippool) {
1424                 AST_LIST_LOCK(&ippool_list);
1425                 AST_LIST_INSERT_HEAD(&ippool_list, ippool, list);
1426                 AST_LIST_UNLOCK(&ippool_list);
1427                 return 0;
1428         } else {
1429                 ast_log(LOG_WARNING, "Attempted to register NULL ippool?\n");
1430                 return -1;
1431         }
1432 }
1433
1434 static void pktccops_unregister_cmtses(void)
1435 {
1436         struct cops_cmts *cmts;
1437         struct cops_gate *gate;
1438         AST_LIST_LOCK(&cmts_list);
1439         while ((cmts = AST_LIST_REMOVE_HEAD(&cmts_list, list))) {
1440                 if (cmts->sfd > 0) {
1441                         close(cmts->sfd);
1442                 }
1443                 ast_free(cmts);
1444         }
1445         AST_LIST_UNLOCK(&cmts_list);
1446
1447         AST_LIST_LOCK(&gate_list);
1448         while ((gate = AST_LIST_REMOVE_HEAD(&gate_list, list))) {
1449                 ast_free(gate);
1450         }
1451         AST_LIST_UNLOCK(&gate_list);
1452 }
1453
1454 static void pktccops_unregister_ippools(void)
1455 {
1456         struct cops_ippool *ippool;
1457         AST_LIST_LOCK(&ippool_list);
1458         while ((ippool = AST_LIST_REMOVE_HEAD(&ippool_list, list))) {
1459                 ast_free(ippool);
1460         }
1461         AST_LIST_UNLOCK(&ippool_list);
1462 }
1463
1464 static int load_module(void)
1465 {
1466         int res;
1467         AST_LIST_LOCK(&cmts_list);
1468         res = load_pktccops_config();
1469         AST_LIST_UNLOCK(&cmts_list);
1470         if (res == -1) {
1471                 return AST_MODULE_LOAD_DECLINE;
1472         }
1473         ast_cli_register_multiple(cli_pktccops, sizeof(cli_pktccops) / sizeof(struct ast_cli_entry));
1474         restart_pktc_thread();
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 );
1517