]> git.ipfire.org Git - thirdparty/squid.git/blob - src/acl/Asn.cc
Merged from trunk
[thirdparty/squid.git] / src / acl / Asn.cc
1
2 /*
3 * DEBUG: section 53 AS Number handling
4 * AUTHOR: Duane Wessels, Kostas Anagnostakis
5 *
6 * SQUID Web Proxy Cache http://www.squid-cache.org/
7 * ----------------------------------------------------------
8 *
9 * Squid is the result of efforts by numerous individuals from
10 * the Internet community; see the CONTRIBUTORS file for full
11 * details. Many organizations have provided support for Squid's
12 * development; see the SPONSORS file for full details. Squid is
13 * Copyrighted (C) 2001 by the Regents of the University of
14 * California; see the COPYRIGHT file for full details. Squid
15 * incorporates software developed and/or copyrighted by other
16 * sources; see the CREDITS file for full details.
17 *
18 * This program is free software; you can redistribute it and/or modify
19 * it under the terms of the GNU General Public License as published by
20 * the Free Software Foundation; either version 2 of the License, or
21 * (at your option) any later version.
22 *
23 * This program is distributed in the hope that it will be useful,
24 * but WITHOUT ANY WARRANTY; without even the implied warranty of
25 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26 * GNU General Public License for more details.
27 *
28 * You should have received a copy of the GNU General Public License
29 * along with this program; if not, write to the Free Software
30 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111, USA.
31 *
32 */
33
34 #include "squid.h"
35 #include "mgr/Registration.h"
36 #include "radix.h"
37 #include "HttpRequest.h"
38 #include "StoreClient.h"
39 #include "Store.h"
40 #include "acl/Acl.h"
41 #include "acl/Asn.h"
42 #include "acl/Checklist.h"
43 #include "acl/SourceAsn.h"
44 #include "acl/DestinationAsn.h"
45 #include "acl/DestinationIp.h"
46 #include "cache_cf.h"
47 #include "HttpReply.h"
48 #include "ipcache.h"
49 #include "forward.h"
50 #include "StoreClient.h"
51 #include "wordlist.h"
52
53 #define WHOIS_PORT 43
54 #define AS_REQBUF_SZ 4096
55
56 /* BEGIN of definitions for radix tree entries */
57
58 /* 32/128 bits address in memory with length */
59 class m_ADDR
60 {
61 public:
62 uint8_t len;
63 Ip::Address addr;
64
65 m_ADDR() : len(sizeof(Ip::Address)) {};
66 };
67
68 /* END of definitions for radix tree entries */
69
70 /* Head for ip to asn radix tree */
71
72 struct squid_radix_node_head *AS_tree_head;
73
74 /* explicit instantiation required for some systems */
75
76 /// \cond AUTODOCS-IGNORE
77 template cbdata_type CbDataList<int>::CBDATA_CbDataList;
78 /// \endcond
79
80 /**
81 * Structure for as number information. it could be simply
82 * a list but it's coded as a structure for future
83 * enhancements (e.g. expires)
84 */
85 struct as_info {
86 CbDataList<int> *as_number;
87 time_t expires; /* NOTUSED */
88 };
89
90 struct ASState {
91 StoreEntry *entry;
92 store_client *sc;
93 HttpRequest *request;
94 int as_number;
95 int64_t offset;
96 int reqofs;
97 char reqbuf[AS_REQBUF_SZ];
98 bool dataRead;
99 };
100
101 /** entry into the radix tree */
102 struct rtentry_t {
103 struct squid_radix_node e_nodes[2];
104 as_info *e_info;
105 m_ADDR e_addr;
106 m_ADDR e_mask;
107 };
108
109 static int asnAddNet(char *, int);
110
111 static void asnCacheStart(int as);
112
113 static STCB asHandleReply;
114
115 #if defined(__cplusplus)
116 extern "C" {
117 #endif
118
119 static int destroyRadixNode(struct squid_radix_node *rn, void *w);
120 static int printRadixNode(struct squid_radix_node *rn, void *sentry);
121
122 #if defined(__cplusplus)
123 }
124 #endif
125
126 void asnAclInitialize(ACL * acls);
127
128 static void asStateFree(void *data);
129
130 static void destroyRadixNodeInfo(as_info *);
131
132 static OBJH asnStats;
133
134 /* PUBLIC */
135
136 int
137 asnMatchIp(CbDataList<int> *data, Ip::Address &addr)
138 {
139 struct squid_radix_node *rn;
140 as_info *e;
141 m_ADDR m_addr;
142 CbDataList<int> *a = NULL;
143 CbDataList<int> *b = NULL;
144
145 debugs(53, 3, "asnMatchIp: Called for " << addr );
146
147 if (AS_tree_head == NULL)
148 return 0;
149
150 if (addr.IsNoAddr())
151 return 0;
152
153 if (addr.IsAnyAddr())
154 return 0;
155
156 m_addr.addr = addr;
157
158 rn = squid_rn_match(&m_addr, AS_tree_head);
159
160 if (rn == NULL) {
161 debugs(53, 3, "asnMatchIp: Address not in as db.");
162 return 0;
163 }
164
165 debugs(53, 3, "asnMatchIp: Found in db!");
166 e = ((rtentry_t *) rn)->e_info;
167 assert(e);
168
169 for (a = data; a; a = a->next)
170 for (b = e->as_number; b; b = b->next)
171 if (a->element == b->element) {
172 debugs(53, 5, "asnMatchIp: Found a match!");
173 return 1;
174 }
175
176 debugs(53, 5, "asnMatchIp: AS not in as db.");
177 return 0;
178 }
179
180 void
181 ACLASN::prepareForUse()
182 {
183 for (CbDataList<int> *i = data; i; i = i->
184 next)
185 asnCacheStart(i->element);
186 }
187
188 static void
189 asnRegisterWithCacheManager(void)
190 {
191 Mgr::RegisterAction("asndb", "AS Number Database", asnStats, 0, 1);
192 }
193
194 /* initialize the radix tree structure */
195
196 SQUIDCEXTERN int squid_max_keylen; /* yuck.. this is in lib/radix.c */
197
198 CBDATA_TYPE(ASState);
199 void
200 asnInit(void)
201 {
202 static bool inited = false;
203 squid_max_keylen = 40;
204 CBDATA_INIT_TYPE(ASState);
205
206 if (!inited) {
207 inited = true;
208 squid_rn_init();
209 }
210
211 squid_rn_inithead(&AS_tree_head, 8);
212
213 asnRegisterWithCacheManager();
214 }
215
216 void
217 asnFreeMemory(void)
218 {
219 squid_rn_walktree(AS_tree_head, destroyRadixNode, AS_tree_head);
220
221 destroyRadixNode((struct squid_radix_node *) 0, (void *) AS_tree_head);
222 }
223
224 static void
225 asnStats(StoreEntry * sentry)
226 {
227 storeAppendPrintf(sentry, "Address \tAS Numbers\n");
228 squid_rn_walktree(AS_tree_head, printRadixNode, sentry);
229 }
230
231 /* PRIVATE */
232
233 static void
234 asnCacheStart(int as)
235 {
236 LOCAL_ARRAY(char, asres, 4096);
237 StoreEntry *e;
238 HttpRequest *req;
239 ASState *asState;
240 asState = cbdataAlloc(ASState);
241 asState->dataRead = 0;
242 debugs(53, 3, "asnCacheStart: AS " << as);
243 snprintf(asres, 4096, "whois://%s/!gAS%d", Config.as_whois_server, as);
244 asState->as_number = as;
245 req = HttpRequest::CreateFromUrl(asres);
246 assert(NULL != req);
247 asState->request = HTTPMSGLOCK(req);
248
249 if ((e = storeGetPublic(asres, METHOD_GET)) == NULL) {
250 e = storeCreateEntry(asres, asres, request_flags(), METHOD_GET);
251 asState->sc = storeClientListAdd(e, asState);
252 FwdState::fwdStart(Comm::ConnectionPointer(), e, asState->request);
253 } else {
254
255 e->lock();
256 asState->sc = storeClientListAdd(e, asState);
257 }
258
259 asState->entry = e;
260 asState->offset = 0;
261 asState->reqofs = 0;
262 StoreIOBuffer readBuffer (AS_REQBUF_SZ, asState->offset, asState->reqbuf);
263 storeClientCopy(asState->sc,
264 e,
265 readBuffer,
266 asHandleReply,
267 asState);
268 }
269
270 static void
271 asHandleReply(void *data, StoreIOBuffer result)
272 {
273 ASState *asState = (ASState *)data;
274 StoreEntry *e = asState->entry;
275 char *s;
276 char *t;
277 char *buf = asState->reqbuf;
278 int leftoversz = -1;
279
280 debugs(53, 3, "asHandleReply: Called with size=" << (unsigned int)result.length);
281 debugs(53, 3, "asHandleReply: buffer='" << buf << "'");
282
283 /* First figure out whether we should abort the request */
284
285 if (EBIT_TEST(e->flags, ENTRY_ABORTED)) {
286 asStateFree(asState);
287 return;
288 }
289
290 if (result.length == 0 && asState->dataRead) {
291 debugs(53, 3, "asHandleReply: Done: " << e->url() );
292 asStateFree(asState);
293 return;
294 } else if (result.flags.error) {
295 debugs(53, DBG_IMPORTANT, "asHandleReply: Called with Error set and size=" << (unsigned int) result.length);
296 asStateFree(asState);
297 return;
298 } else if (HTTP_OK != e->getReply()->sline.status) {
299 debugs(53, DBG_IMPORTANT, "WARNING: AS " << asState->as_number << " whois request failed");
300 asStateFree(asState);
301 return;
302 }
303
304 /*
305 * Next, attempt to parse our request
306 * Remembering that the actual buffer size is retsize + reqofs!
307 */
308 s = buf;
309
310 while ((size_t)(s - buf) < result.length + asState->reqofs && *s != '\0') {
311 while (*s && xisspace(*s))
312 ++s;
313
314 for (t = s; *t; ++t) {
315 if (xisspace(*t))
316 break;
317 }
318
319 if (*t == '\0') {
320 /* oof, word should continue on next block */
321 break;
322 }
323
324 *t = '\0';
325 debugs(53, 3, "asHandleReply: AS# " << s << " (" << asState->as_number << ")");
326 asnAddNet(s, asState->as_number);
327 s = t + 1;
328 asState->dataRead = 1;
329 }
330
331 /*
332 * Next, grab the end of the 'valid data' in the buffer, and figure
333 * out how much data is left in our buffer, which we need to keep
334 * around for the next request
335 */
336 leftoversz = (asState->reqofs + result.length) - (s - buf);
337
338 assert(leftoversz >= 0);
339
340 /*
341 * Next, copy the left over data, from s to s + leftoversz to the
342 * beginning of the buffer
343 */
344 memmove(buf, s, leftoversz);
345
346 /*
347 * Next, update our offset and reqofs, and kick off a copy if required
348 */
349 asState->offset += result.length;
350
351 asState->reqofs = leftoversz;
352
353 debugs(53, 3, "asState->offset = " << asState->offset);
354
355 if (e->store_status == STORE_PENDING) {
356 debugs(53, 3, "asHandleReply: store_status == STORE_PENDING: " << e->url() );
357 StoreIOBuffer tempBuffer (AS_REQBUF_SZ - asState->reqofs,
358 asState->offset,
359 asState->reqbuf + asState->reqofs);
360 storeClientCopy(asState->sc,
361 e,
362 tempBuffer,
363 asHandleReply,
364 asState);
365 } else {
366 StoreIOBuffer tempBuffer;
367 debugs(53, 3, "asHandleReply: store complete, but data received " << e->url() );
368 tempBuffer.offset = asState->offset;
369 tempBuffer.length = AS_REQBUF_SZ - asState->reqofs;
370 tempBuffer.data = asState->reqbuf + asState->reqofs;
371 storeClientCopy(asState->sc,
372 e,
373 tempBuffer,
374 asHandleReply,
375 asState);
376 }
377 }
378
379 static void
380 asStateFree(void *data)
381 {
382 ASState *asState = (ASState *)data;
383 debugs(53, 3, "asnStateFree: " << asState->entry->url() );
384 storeUnregister(asState->sc, asState->entry, asState);
385 asState->entry->unlock();
386 HTTPMSGUNLOCK(asState->request);
387 cbdataFree(asState);
388 }
389
390 /**
391 * add a network (addr, mask) to the radix tree, with matching AS number
392 */
393 static int
394 asnAddNet(char *as_string, int as_number)
395 {
396 rtentry_t *e;
397
398 struct squid_radix_node *rn;
399 CbDataList<int> **Tail = NULL;
400 CbDataList<int> *q = NULL;
401 as_info *asinfo = NULL;
402
403 Ip::Address mask;
404 Ip::Address addr;
405 char *t;
406 int bitl;
407
408 t = strchr(as_string, '/');
409
410 if (t == NULL) {
411 debugs(53, 3, "asnAddNet: failed, invalid response from whois server.");
412 return 0;
413 }
414
415 *t = '\0';
416 addr = as_string;
417 bitl = atoi(t + 1);
418
419 if (bitl < 0)
420 bitl = 0;
421
422 // INET6 TODO : find a better way of identifying the base IPA family for mask than this.
423 t = strchr(as_string, '.');
424
425 // generate Netbits Format Mask
426 mask.SetNoAddr();
427 mask.ApplyMask(bitl, (t!=NULL?AF_INET:AF_INET6) );
428
429 debugs(53, 3, "asnAddNet: called for " << addr << "/" << mask );
430
431 e = (rtentry_t *)xmalloc(sizeof(rtentry_t));
432
433 memset(e, '\0', sizeof(rtentry_t));
434
435 e->e_addr.addr = addr;
436
437 e->e_mask.addr = mask;
438
439 rn = squid_rn_lookup(&e->e_addr, &e->e_mask, AS_tree_head);
440
441 if (rn != NULL) {
442 asinfo = ((rtentry_t *) rn)->e_info;
443
444 if (asinfo->as_number->find(as_number)) {
445 debugs(53, 3, "asnAddNet: Ignoring repeated network '" << addr << "/" << bitl << "' for AS " << as_number);
446 } else {
447 debugs(53, 3, "asnAddNet: Warning: Found a network with multiple AS numbers!");
448
449 for (Tail = &asinfo->as_number; *Tail; Tail = &(*Tail)->next);
450 q = new CbDataList<int> (as_number);
451
452 *(Tail) = q;
453
454 e->e_info = asinfo;
455 }
456 } else {
457 q = new CbDataList<int> (as_number);
458 asinfo = (as_info *)xmalloc(sizeof(as_info));
459 asinfo->as_number = q;
460 rn = squid_rn_addroute(&e->e_addr, &e->e_mask, AS_tree_head, e->e_nodes);
461 rn = squid_rn_match(&e->e_addr, AS_tree_head);
462 assert(rn != NULL);
463 e->e_info = asinfo;
464 }
465
466 if (rn == 0) { /* assert might expand to nothing */
467 xfree(asinfo);
468 delete q;
469 xfree(e);
470 debugs(53, 3, "asnAddNet: Could not add entry.");
471 return 0;
472 }
473
474 e->e_info = asinfo;
475 return 1;
476 }
477
478 static int
479 destroyRadixNode(struct squid_radix_node *rn, void *w)
480 {
481
482 struct squid_radix_node_head *rnh = (struct squid_radix_node_head *) w;
483
484 if (rn && !(rn->rn_flags & RNF_ROOT)) {
485 rtentry_t *e = (rtentry_t *) rn;
486 rn = squid_rn_delete(rn->rn_key, rn->rn_mask, rnh);
487
488 if (rn == 0)
489 debugs(53, 3, "destroyRadixNode: internal screwup");
490
491 destroyRadixNodeInfo(e->e_info);
492
493 xfree(rn);
494 }
495
496 return 1;
497 }
498
499 static void
500 destroyRadixNodeInfo(as_info * e_info)
501 {
502 CbDataList<int> *prev = NULL;
503 CbDataList<int> *data = e_info->as_number;
504
505 while (data) {
506 prev = data;
507 data = data->next;
508 delete prev;
509 }
510
511 delete data;
512 }
513
514 static int
515 printRadixNode(struct squid_radix_node *rn, void *_sentry)
516 {
517 StoreEntry *sentry = (StoreEntry *)_sentry;
518 rtentry_t *e = (rtentry_t *) rn;
519 CbDataList<int> *q;
520 as_info *asinfo;
521 char buf[MAX_IPSTRLEN];
522 Ip::Address addr;
523 Ip::Address mask;
524
525 assert(e);
526 assert(e->e_info);
527 addr = e->e_addr.addr;
528 mask = e->e_mask.addr;
529 storeAppendPrintf(sentry, "%s/%d\t",
530 addr.NtoA(buf, MAX_IPSTRLEN),
531 mask.GetCIDR() );
532 asinfo = e->e_info;
533 assert(asinfo->as_number);
534
535 for (q = asinfo->as_number; q; q = q->next)
536 storeAppendPrintf(sentry, " %d", q->element);
537
538 storeAppendPrintf(sentry, "\n");
539
540 return 0;
541 }
542
543 ACLASN::~ACLASN()
544 {
545 if (data)
546 delete data;
547 }
548
549 bool
550
551 ACLASN::match(Ip::Address toMatch)
552 {
553 return asnMatchIp(data, toMatch);
554 }
555
556 wordlist *
557 ACLASN::dump()
558 {
559 wordlist *W = NULL;
560 char buf[32];
561 CbDataList<int> *ldata = data;
562
563 while (ldata != NULL) {
564 snprintf(buf, sizeof(buf), "%d", ldata->element);
565 wordlistAdd(&W, buf);
566 ldata = ldata->next;
567 }
568
569 return W;
570 }
571
572 bool
573 ACLASN::empty () const
574 {
575 return data == NULL;
576 }
577
578 void
579 ACLASN::parse()
580 {
581 CbDataList<int> **curlist = &data;
582 CbDataList<int> **Tail;
583 CbDataList<int> *q = NULL;
584 char *t = NULL;
585
586 for (Tail = curlist; *Tail; Tail = &((*Tail)->next));
587 while ((t = strtokFile())) {
588 q = new CbDataList<int> (atoi(t));
589 *(Tail) = q;
590 Tail = &q->next;
591 }
592 }
593
594 ACLData<Ip::Address> *
595 ACLASN::clone() const
596 {
597 if (data)
598 fatal ("cloning of ACLASN not implemented");
599
600 return new ACLASN(*this);
601 }
602
603 /* explicit template instantiation required for some systems */
604
605 template class ACLStrategised<Ip::Address>;
606
607 ACL::Prototype ACLASN::SourceRegistryProtoype(&ACLASN::SourceRegistryEntry_, "src_as");
608
609 ACLStrategised<Ip::Address> ACLASN::SourceRegistryEntry_(new ACLASN, ACLSourceASNStrategy::Instance(), "src_as");
610
611 ACL::Prototype ACLASN::DestinationRegistryProtoype(&ACLASN::DestinationRegistryEntry_, "dst_as");
612
613 ACLStrategised<Ip::Address> ACLASN::DestinationRegistryEntry_(new ACLASN, ACLDestinationASNStrategy::Instance(), "dst_as");
614
615 int
616 ACLSourceASNStrategy::match (ACLData<Ip::Address> * &data, ACLFilledChecklist *checklist)
617 {
618 return data->match(checklist->src_addr);
619 }
620
621 ACLSourceASNStrategy *
622 ACLSourceASNStrategy::Instance()
623 {
624 return &Instance_;
625 }
626
627 ACLSourceASNStrategy ACLSourceASNStrategy::Instance_;
628
629 int
630 ACLDestinationASNStrategy::match (ACLData<MatchType> * &data, ACLFilledChecklist *checklist)
631 {
632 const ipcache_addrs *ia = ipcache_gethostbyname(checklist->request->GetHost(), IP_LOOKUP_IF_MISS);
633
634 if (ia) {
635 for (int k = 0; k < (int) ia->count; ++k) {
636 if (data->match(ia->in_addrs[k]))
637 return 1;
638 }
639
640 return 0;
641
642 } else if (!checklist->request->flags.destinationIPLookedUp()) {
643 /* No entry in cache, lookup not attempted */
644 /* XXX FIXME: allow accessing the acl name here */
645 debugs(28, 3, "asnMatchAcl: Can't yet compare '" << "unknown" /*name*/ << "' ACL for '" << checklist->request->GetHost() << "'");
646 checklist->changeState (DestinationIPLookup::Instance());
647 } else {
648 Ip::Address noaddr;
649 noaddr.SetNoAddr();
650 return data->match(noaddr);
651 }
652
653 return 0;
654 }
655
656 ACLDestinationASNStrategy *
657 ACLDestinationASNStrategy::Instance()
658 {
659 return &Instance_;
660 }
661
662 ACLDestinationASNStrategy ACLDestinationASNStrategy::Instance_;