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