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