]> git.ipfire.org Git - thirdparty/squid.git/blob - src/icmp/net_db.cc
transaction_initiator ACL for detecting various unusual transactions
[thirdparty/squid.git] / src / icmp / net_db.cc
1 /*
2 * Copyright (C) 1996-2017 The Squid Software Foundation and contributors
3 *
4 * Squid software is distributed under GPLv2+ license and includes
5 * contributions from numerous individuals and organizations.
6 * Please see the COPYING and CONTRIBUTORS files for details.
7 */
8
9 /* DEBUG: section 38 Network Measurement Database */
10
11 /*
12 * XXX XXX XXX
13 *
14 * This code may be slightly broken now. If you're getting consistent
15 * (sometimes working) corrupt data exchanges, please contact adrian
16 * (adrian@squid-cache.org) to sort them out.
17 */
18
19 #include "squid.h"
20 #include "CachePeer.h"
21 #include "cbdata.h"
22 #include "event.h"
23 #include "fde.h"
24 #include "fs_io.h"
25 #include "FwdState.h"
26 #include "HttpReply.h"
27 #include "icmp/net_db.h"
28 #include "internal.h"
29 #include "ip/Address.h"
30 #include "log/File.h"
31 #include "MemObject.h"
32 #include "mgr/Registration.h"
33 #include "mime_header.h"
34 #include "neighbors.h"
35 #include "SquidConfig.h"
36 #include "SquidTime.h"
37 #include "Store.h"
38 #include "StoreClient.h"
39 #include "tools.h"
40 #include "wordlist.h"
41
42 #if HAVE_SYS_STAT_H
43 #include <sys/stat.h>
44 #endif
45
46 #if USE_ICMP
47 #include "icmp/IcmpSquid.h"
48 #include "ipcache.h"
49 #include "StoreClient.h"
50
51 #define NETDB_REQBUF_SZ 4096
52
53 typedef enum {
54 STATE_NONE,
55 STATE_HEADER,
56 STATE_BODY
57 } netdb_conn_state_t;
58
59 class netdbExchangeState
60 {
61 CBDATA_CLASS(netdbExchangeState);
62
63 public:
64 netdbExchangeState(CachePeer *aPeer, const HttpRequestPointer &theReq) :
65 p(aPeer),
66 r(theReq)
67 {
68 *buf = 0;
69 assert(r);
70 // TODO: check if we actually need to do this. should be implicit
71 r->http_ver = Http::ProtocolVersion();
72 }
73
74 ~netdbExchangeState() {
75 debugs(38, 3, e->url());
76 storeUnregister(sc, e, this);
77 e->unlock("netdbExchangeDone");
78 }
79
80 CbcPointer<CachePeer> p;
81 StoreEntry *e = nullptr;
82 store_client *sc = nullptr;
83 HttpRequestPointer r;
84 int64_t used = 0;
85 size_t buf_sz = NETDB_REQBUF_SZ;
86 char buf[NETDB_REQBUF_SZ];
87 int buf_ofs = 0;
88 netdb_conn_state_t connstate = STATE_HEADER;
89 };
90
91 CBDATA_CLASS_INIT(netdbExchangeState);
92
93 static hash_table *addr_table = NULL;
94 static hash_table *host_table = NULL;
95
96 Ip::Address networkFromInaddr(const Ip::Address &a);
97 static void netdbRelease(netdbEntry * n);
98
99 static void netdbHashInsert(netdbEntry * n, Ip::Address &addr);
100 static void netdbHashDelete(const char *key);
101 static void netdbHostInsert(netdbEntry * n, const char *hostname);
102 static void netdbHostDelete(const net_db_name * x);
103 static void netdbPurgeLRU(void);
104 static netdbEntry *netdbLookupHost(const char *key);
105 static net_db_peer *netdbPeerByName(const netdbEntry * n, const char *);
106 static net_db_peer *netdbPeerAdd(netdbEntry * n, CachePeer * e);
107 static const char *netdbPeerName(const char *name);
108 static IPH netdbSendPing;
109 static FREE netdbFreeNameEntry;
110 static FREE netdbFreeNetdbEntry;
111 static STCB netdbExchangeHandleReply;
112
113 /* We have to keep a local list of CachePeer names. The Peers structure
114 * gets freed during a reconfigure. We want this database to
115 * remain persisitent, so _net_db_peer->peername points into this
116 * linked list */
117 static wordlist *peer_names = NULL;
118
119 static void
120 netdbHashInsert(netdbEntry * n, Ip::Address &addr)
121 {
122 networkFromInaddr(addr).toStr(n->network, MAX_IPSTRLEN);
123 n->hash.key = n->network;
124 assert(hash_lookup(addr_table, n->network) == NULL);
125 hash_join(addr_table, &n->hash);
126 }
127
128 static void
129 netdbHashDelete(const char *key)
130 {
131 hash_link *hptr = (hash_link *)hash_lookup(addr_table, key);
132
133 if (hptr == NULL) {
134 debug_trap("netdbHashDelete: key not found");
135 return;
136 }
137
138 hash_remove_link(addr_table, hptr);
139 }
140
141 net_db_name::net_db_name(const char *hostname, netdbEntry *e) :
142 next(e ? e->hosts : nullptr),
143 net_db_entry(e)
144 {
145 hash.key = xstrdup(hostname);
146 if (e) {
147 e->hosts = this;
148 ++ e->link_count;
149 }
150 }
151
152 static void
153 netdbHostInsert(netdbEntry * n, const char *hostname)
154 {
155 net_db_name *x = new net_db_name(hostname, n);
156 assert(hash_lookup(host_table, hostname) == NULL);
157 hash_join(host_table, &x->hash);
158 }
159
160 static void
161 netdbHostDelete(const net_db_name * x)
162 {
163 assert(x != NULL);
164 assert(x->net_db_entry != NULL);
165
166 netdbEntry *n = x->net_db_entry;
167 -- n->link_count;
168
169 for (auto **X = &n->hosts; *X; X = &(*X)->next) {
170 if (*X == x) {
171 *X = x->next;
172 break;
173 }
174 }
175
176 hash_remove_link(host_table, (hash_link *) x);
177 delete x;
178 }
179
180 static netdbEntry *
181 netdbLookupHost(const char *key)
182 {
183 net_db_name *x = (net_db_name *) hash_lookup(host_table, key);
184 return x ? x->net_db_entry : NULL;
185 }
186
187 static void
188 netdbRelease(netdbEntry * n)
189 {
190 net_db_name *x;
191 net_db_name *next;
192
193 for (x = n->hosts; x; x = next) {
194 next = x->next;
195 netdbHostDelete(x);
196 }
197
198 n->hosts = NULL;
199 safe_free(n->peers);
200 n->peers = NULL;
201 n->n_peers = 0;
202 n->n_peers_alloc = 0;
203
204 if (n->link_count == 0) {
205 netdbHashDelete(n->network);
206 delete n;
207 }
208 }
209
210 static int
211 netdbLRU(const void *A, const void *B)
212 {
213 const netdbEntry *const *n1 = (const netdbEntry *const *)A;
214 const netdbEntry *const *n2 = (const netdbEntry *const *)B;
215
216 if ((*n1)->last_use_time > (*n2)->last_use_time)
217 return (1);
218
219 if ((*n1)->last_use_time < (*n2)->last_use_time)
220 return (-1);
221
222 return (0);
223 }
224
225 static void
226 netdbPurgeLRU(void)
227 {
228 netdbEntry *n;
229 netdbEntry **list;
230 int k = 0;
231 int list_count = 0;
232 int removed = 0;
233 list = (netdbEntry **)xcalloc(netdbEntry::UseCount(), sizeof(netdbEntry *));
234 hash_first(addr_table);
235
236 while ((n = (netdbEntry *) hash_next(addr_table))) {
237 assert(list_count < netdbEntry::UseCount());
238 *(list + list_count) = n;
239 ++list_count;
240 }
241
242 qsort((char *) list,
243 list_count,
244 sizeof(netdbEntry *),
245 netdbLRU);
246
247 for (k = 0; k < list_count; ++k) {
248 if (netdbEntry::UseCount() < Config.Netdb.low)
249 break;
250
251 netdbRelease(*(list + k));
252
253 ++removed;
254 }
255
256 xfree(list);
257 }
258
259 static netdbEntry *
260 netdbLookupAddr(const Ip::Address &addr)
261 {
262 netdbEntry *n;
263 char *key = new char[MAX_IPSTRLEN];
264 networkFromInaddr(addr).toStr(key,MAX_IPSTRLEN);
265 n = (netdbEntry *) hash_lookup(addr_table, key);
266 delete[] key;
267 return n;
268 }
269
270 static netdbEntry *
271 netdbAdd(Ip::Address &addr)
272 {
273 netdbEntry *n;
274
275 if (netdbEntry::UseCount() > Config.Netdb.high)
276 netdbPurgeLRU();
277
278 if ((n = netdbLookupAddr(addr)) == NULL) {
279 n = new netdbEntry;
280 netdbHashInsert(n, addr);
281 }
282
283 return n;
284 }
285
286 static void
287 netdbSendPing(const ipcache_addrs *ia, const Dns::LookupDetails &, void *data)
288 {
289 Ip::Address addr;
290 char *hostname = NULL;
291 static_cast<generic_cbdata *>(data)->unwrap(&hostname);
292 netdbEntry *n;
293 netdbEntry *na;
294 net_db_name *x;
295 net_db_name **X;
296
297 if (ia == NULL) {
298 xfree(hostname);
299 return;
300 }
301
302 addr = ia->in_addrs[ia->cur];
303
304 if ((n = netdbLookupHost(hostname)) == NULL) {
305 n = netdbAdd(addr);
306 netdbHostInsert(n, hostname);
307 } else if ((na = netdbLookupAddr(addr)) != n) {
308 /*
309 *hostname moved from 'network n' to 'network na'!
310 */
311
312 if (na == NULL)
313 na = netdbAdd(addr);
314
315 debugs(38, 3, "netdbSendPing: " << hostname << " moved from " << n->network << " to " << na->network);
316
317 x = (net_db_name *) hash_lookup(host_table, hostname);
318
319 if (x == NULL) {
320 debugs(38, DBG_IMPORTANT, "netdbSendPing: net_db_name list bug: " << hostname << " not found");
321 xfree(hostname);
322 return;
323 }
324
325 /* remove net_db_name from 'network n' linked list */
326 for (X = &n->hosts; *X; X = &(*X)->next) {
327 if (*X == x) {
328 *X = x->next;
329 break;
330 }
331 }
332
333 -- n->link_count;
334 /* point to 'network na' from host entry */
335 x->net_db_entry = na;
336 /* link net_db_name to 'network na' */
337 x->next = na->hosts;
338 na->hosts = x;
339 ++ na->link_count;
340 n = na;
341 }
342
343 if (n->next_ping_time <= squid_curtime) {
344 debugs(38, 3, "netdbSendPing: pinging " << hostname);
345 icmpEngine.DomainPing(addr, hostname);
346 ++ n->pings_sent;
347 n->next_ping_time = squid_curtime + Config.Netdb.period;
348 n->last_use_time = squid_curtime;
349 }
350
351 xfree(hostname);
352 }
353
354 Ip::Address
355 networkFromInaddr(const Ip::Address &in)
356 {
357 Ip::Address out;
358
359 out = in;
360
361 /* in IPv6 the 'network' should be the routing section. */
362 if ( in.isIPv6() ) {
363 out.applyMask(64, AF_INET6);
364 debugs(14, 5, "networkFromInaddr : Masked IPv6 Address to " << in << "/64 routing part.");
365 return out;
366 }
367
368 #if USE_CLASSFUL
369 struct in_addr b;
370
371 in.getInAddr(b);
372
373 if (IN_CLASSC(b.s_addr))
374 b.s_addr &= IN_CLASSC_NET;
375 else if (IN_CLASSB(b.s_addr))
376 b.s_addr &= IN_CLASSB_NET;
377 else if (IN_CLASSA(b.s_addr))
378 b.s_addr &= IN_CLASSA_NET;
379
380 out = b;
381
382 #endif
383
384 debugs(14, 5, "networkFromInaddr : Masked IPv4 Address to " << out << "/24.");
385
386 /* use /24 for everything under IPv4 */
387 out.applyMask(24, AF_INET);
388 debugs(14, 5, "networkFromInaddr : Masked IPv4 Address to " << in << "/24.");
389
390 return out;
391 }
392
393 static int
394 sortByRtt(const void *A, const void *B)
395 {
396 const netdbEntry *const *n1 = (const netdbEntry *const *)A;
397 const netdbEntry *const *n2 = (const netdbEntry *const *)B;
398
399 if ((*n1)->rtt > (*n2)->rtt)
400 return 1;
401 else if ((*n1)->rtt < (*n2)->rtt)
402 return -1;
403 else
404 return 0;
405 }
406
407 static net_db_peer *
408 netdbPeerByName(const netdbEntry * n, const char *peername)
409 {
410 int i;
411 net_db_peer *p = n->peers;
412
413 for (i = 0; i < n->n_peers; ++i, ++p) {
414 if (!strcmp(p->peername, peername))
415 return p;
416 }
417
418 return NULL;
419 }
420
421 static net_db_peer *
422 netdbPeerAdd(netdbEntry * n, CachePeer * e)
423 {
424 net_db_peer *p;
425 net_db_peer *o;
426 int osize;
427 int i;
428
429 if (n->n_peers == n->n_peers_alloc) {
430 o = n->peers;
431 osize = n->n_peers_alloc;
432
433 if (n->n_peers_alloc == 0)
434 n->n_peers_alloc = 2;
435 else
436 n->n_peers_alloc <<= 1;
437
438 debugs(38, 3, "netdbPeerAdd: Growing peer list for '" << n->network << "' to " << n->n_peers_alloc);
439
440 n->peers = (net_db_peer *)xcalloc(n->n_peers_alloc, sizeof(net_db_peer));
441
442 for (i = 0; i < osize; ++i)
443 *(n->peers + i) = *(o + i);
444
445 if (osize) {
446 safe_free(o);
447 }
448 }
449
450 p = n->peers + n->n_peers;
451 p->peername = netdbPeerName(e->host);
452 ++ n->n_peers;
453 return p;
454 }
455
456 static int
457 sortPeerByRtt(const void *A, const void *B)
458 {
459 const net_db_peer *p1 = (net_db_peer *)A;
460 const net_db_peer *p2 = (net_db_peer *)B;
461
462 if (p1->rtt > p2->rtt)
463 return 1;
464 else if (p1->rtt < p2->rtt)
465 return -1;
466 else
467 return 0;
468 }
469
470 static void
471 netdbSaveState(void *foo)
472 {
473 if (strcmp(Config.netdbFilename, "none") == 0)
474 return;
475
476 Logfile *lf;
477 netdbEntry *n;
478 net_db_name *x;
479
480 struct timeval start = current_time;
481 int count = 0;
482 /*
483 * This was nicer when we were using stdio, but thanks to
484 * Solaris bugs, its a bad idea. fopen can fail if more than
485 * 256 FDs are open.
486 */
487 /*
488 * unlink() is here because there is currently no way to make
489 * logfileOpen() use O_TRUNC.
490 */
491 unlink(Config.netdbFilename);
492 lf = logfileOpen(Config.netdbFilename, 4096, 0);
493
494 if (lf) {
495 int xerrno = errno;
496 debugs(50, DBG_IMPORTANT, MYNAME << Config.netdbFilename << ": " << xstrerr(xerrno));
497 return;
498 }
499
500 hash_first(addr_table);
501
502 while ((n = (netdbEntry *) hash_next(addr_table))) {
503 if (n->pings_recv == 0)
504 continue;
505
506 logfilePrintf(lf, "%s %d %d %10.5f %10.5f %d %d",
507 n->network,
508 n->pings_sent,
509 n->pings_recv,
510 n->hops,
511 n->rtt,
512 (int) n->next_ping_time,
513 (int) n->last_use_time);
514
515 for (x = n->hosts; x; x = x->next)
516 logfilePrintf(lf, " %s", hashKeyStr(&x->hash));
517
518 logfilePrintf(lf, "\n");
519
520 ++count;
521
522 #undef RBUF_SZ
523
524 }
525
526 logfileClose(lf);
527 getCurrentTime();
528 debugs(38, DBG_IMPORTANT, "NETDB state saved; " <<
529 count << " entries, " <<
530 tvSubMsec(start, current_time) << " msec" );
531 eventAddIsh("netdbSaveState", netdbSaveState, NULL, 3600.0, 1);
532 }
533
534 static void
535 netdbReloadState(void)
536 {
537 if (strcmp(Config.netdbFilename, "none") == 0)
538 return;
539
540 char *s;
541 int fd;
542 int l;
543
544 struct stat sb;
545 netdbEntry *n;
546 netdbEntry N;
547
548 Ip::Address addr;
549 int count = 0;
550
551 struct timeval start = current_time;
552 /*
553 * This was nicer when we were using stdio, but thanks to
554 * Solaris bugs, its a bad idea. fopen can fail if more than
555 * 256 FDs are open.
556 */
557 fd = file_open(Config.netdbFilename, O_RDONLY | O_BINARY);
558
559 if (fd < 0)
560 return;
561
562 if (fstat(fd, &sb) < 0) {
563 file_close(fd);
564 return;
565 }
566
567 char *t;
568 char *buf = (char *)xcalloc(1, sb.st_size + 1);
569 t = buf;
570 l = FD_READ_METHOD(fd, buf, sb.st_size);
571 file_close(fd);
572
573 if (l <= 0) {
574 safe_free (buf);
575 return;
576 };
577
578 while ((s = strchr(t, '\n'))) {
579 char *q;
580 assert(s - buf < l);
581 *s = '\0';
582 memset(&N, '\0', sizeof(netdbEntry));
583 q = strtok(t, w_space);
584 t = s + 1;
585
586 if (NULL == q)
587 continue;
588
589 if (! (addr = q) )
590 continue;
591
592 if (netdbLookupAddr(addr) != NULL) /* no dups! */
593 continue;
594
595 if ((q = strtok(NULL, w_space)) == NULL)
596 continue;
597
598 N.pings_sent = atoi(q);
599
600 if ((q = strtok(NULL, w_space)) == NULL)
601 continue;
602
603 N.pings_recv = atoi(q);
604
605 if (N.pings_recv == 0)
606 continue;
607
608 /* give this measurement low weight */
609 N.pings_sent = 1;
610
611 N.pings_recv = 1;
612
613 if ((q = strtok(NULL, w_space)) == NULL)
614 continue;
615
616 N.hops = atof(q);
617
618 if ((q = strtok(NULL, w_space)) == NULL)
619 continue;
620
621 N.rtt = atof(q);
622
623 if ((q = strtok(NULL, w_space)) == NULL)
624 continue;
625
626 N.next_ping_time = (time_t) atoi(q);
627
628 if ((q = strtok(NULL, w_space)) == NULL)
629 continue;
630
631 N.last_use_time = (time_t) atoi(q);
632
633 n = new netdbEntry;
634
635 memcpy(n, &N, sizeof(netdbEntry));
636
637 netdbHashInsert(n, addr);
638
639 while ((q = strtok(NULL, w_space)) != NULL) {
640 if (netdbLookupHost(q) != NULL) /* no dups! */
641 continue;
642
643 netdbHostInsert(n, q);
644 }
645
646 ++count;
647 }
648
649 xfree(buf);
650 getCurrentTime();
651 debugs(38, DBG_IMPORTANT, "NETDB state reloaded; " <<
652 count << " entries, " <<
653 tvSubMsec(start, current_time) << " msec" );
654 }
655
656 static const char *
657 netdbPeerName(const char *name)
658 {
659 const wordlist *w;
660
661 for (w = peer_names; w; w = w->next) {
662 if (!strcmp(w->key, name))
663 return w->key;
664 }
665
666 return wordlistAdd(&peer_names, name);
667 }
668
669 static void
670 netdbFreeNetdbEntry(void *data)
671 {
672 netdbEntry *n = (netdbEntry *)data;
673 safe_free(n->peers);
674 delete n;
675 }
676
677 static void
678 netdbFreeNameEntry(void *data)
679 {
680 net_db_name *x = (net_db_name *)data;
681 delete x;
682 }
683
684 static void
685 netdbExchangeHandleReply(void *data, StoreIOBuffer receivedData)
686 {
687 Ip::Address addr;
688
689 netdbExchangeState *ex = (netdbExchangeState *)data;
690 int rec_sz = 0;
691 int o;
692
693 struct in_addr line_addr;
694 double rtt;
695 double hops;
696 char *p;
697 int j;
698 HttpReply const *rep;
699 size_t hdr_sz;
700 int nused = 0;
701 int size;
702 int oldbufofs = ex->buf_ofs;
703
704 rec_sz = 0;
705 rec_sz += 1 + sizeof(struct in_addr);
706 rec_sz += 1 + sizeof(int);
707 rec_sz += 1 + sizeof(int);
708 debugs(38, 3, "netdbExchangeHandleReply: " << receivedData.length << " read bytes");
709
710 if (!ex->p.valid()) {
711 debugs(38, 3, "netdbExchangeHandleReply: Peer became invalid");
712 delete ex;
713 return;
714 }
715
716 debugs(38, 3, "netdbExchangeHandleReply: for '" << ex->p->host << ":" << ex->p->http_port << "'");
717
718 if (receivedData.length == 0 && !receivedData.flags.error) {
719 debugs(38, 3, "netdbExchangeHandleReply: Done");
720 delete ex;
721 return;
722 }
723
724 p = ex->buf;
725
726 /* Get the size of the buffer now */
727 size = ex->buf_ofs + receivedData.length;
728 debugs(38, 3, "netdbExchangeHandleReply: " << size << " bytes buf");
729
730 /* Check if we're still doing headers */
731
732 if (ex->connstate == STATE_HEADER) {
733
734 ex->buf_ofs += receivedData.length;
735
736 /* skip reply headers */
737
738 if ((hdr_sz = headersEnd(p, ex->buf_ofs))) {
739 debugs(38, 5, "netdbExchangeHandleReply: hdr_sz = " << hdr_sz);
740 rep = ex->e->getReply();
741 assert(rep->sline.status() != Http::scNone);
742 debugs(38, 3, "netdbExchangeHandleReply: reply status " << rep->sline.status());
743
744 if (rep->sline.status() != Http::scOkay) {
745 delete ex;
746 return;
747 }
748
749 assert((size_t)ex->buf_ofs >= hdr_sz);
750
751 /*
752 * Now, point p to the part of the buffer where the data
753 * starts, and update the size accordingly
754 */
755 assert(ex->used == 0);
756 ex->used = hdr_sz;
757 size = ex->buf_ofs - hdr_sz;
758 p += hdr_sz;
759
760 /* Finally, set the conn state mode to STATE_BODY */
761 ex->connstate = STATE_BODY;
762 } else {
763 StoreIOBuffer tempBuffer;
764 tempBuffer.offset = ex->buf_ofs;
765 tempBuffer.length = ex->buf_sz - ex->buf_ofs;
766 tempBuffer.data = ex->buf + ex->buf_ofs;
767 /* Have more headers .. */
768 storeClientCopy(ex->sc, ex->e, tempBuffer,
769 netdbExchangeHandleReply, ex);
770 return;
771 }
772 }
773
774 assert(ex->connstate == STATE_BODY);
775
776 /* If we get here, we have some body to parse .. */
777 debugs(38, 5, "netdbExchangeHandleReply: start parsing loop, size = " << size);
778
779 while (size >= rec_sz) {
780 debugs(38, 5, "netdbExchangeHandleReply: in parsing loop, size = " << size);
781 addr.setAnyAddr();
782 hops = rtt = 0.0;
783
784 for (o = 0; o < rec_sz;) {
785 switch ((int) *(p + o)) {
786
787 case NETDB_EX_NETWORK:
788 ++o;
789 /* FIXME INET6 : NetDB can still ony send IPv4 */
790 memcpy(&line_addr, p + o, sizeof(struct in_addr));
791 addr = line_addr;
792 o += sizeof(struct in_addr);
793 break;
794
795 case NETDB_EX_RTT:
796 ++o;
797 memcpy(&j, p + o, sizeof(int));
798 o += sizeof(int);
799 rtt = (double) ntohl(j) / 1000.0;
800 break;
801
802 case NETDB_EX_HOPS:
803 ++o;
804 memcpy(&j, p + o, sizeof(int));
805 o += sizeof(int);
806 hops = (double) ntohl(j) / 1000.0;
807 break;
808
809 default:
810 debugs(38, DBG_IMPORTANT, "netdbExchangeHandleReply: corrupt data, aborting");
811 delete ex;
812 return;
813 }
814 }
815
816 if (!addr.isAnyAddr() && rtt > 0)
817 netdbExchangeUpdatePeer(addr, ex->p.get(), rtt, hops);
818
819 assert(o == rec_sz);
820
821 ex->used += rec_sz;
822
823 size -= rec_sz;
824
825 p += rec_sz;
826
827 ++nused;
828 }
829
830 /*
831 * Copy anything that is left over to the beginning of the buffer,
832 * and adjust buf_ofs accordingly
833 */
834
835 /*
836 * Evilly, size refers to the buf size left now,
837 * ex->buf_ofs is the original buffer size, so just copy that
838 * much data over
839 */
840 memmove(ex->buf, ex->buf + (ex->buf_ofs - size), size);
841
842 ex->buf_ofs = size;
843
844 /*
845 * And don't re-copy the remaining data ..
846 */
847 ex->used += size;
848
849 /*
850 * Now the tricky bit - size _included_ the leftover bit from the _last_
851 * storeClientCopy. We don't want to include that, or our offset will be wrong.
852 * So, don't count the size of the leftover buffer we began with.
853 * This can _disappear_ when we're not tracking offsets ..
854 */
855 ex->used -= oldbufofs;
856
857 debugs(38, 3, "netdbExchangeHandleReply: size left over in this buffer: " << size << " bytes");
858
859 debugs(38, 3, "netdbExchangeHandleReply: used " << nused <<
860 " entries, (x " << rec_sz << " bytes) == " << nused * rec_sz <<
861 " bytes total");
862
863 debugs(38, 3, "netdbExchangeHandleReply: used " << ex->used);
864
865 if (EBIT_TEST(ex->e->flags, ENTRY_ABORTED)) {
866 debugs(38, 3, "netdbExchangeHandleReply: ENTRY_ABORTED");
867 delete ex;
868 } else if (ex->e->store_status == STORE_PENDING) {
869 StoreIOBuffer tempBuffer;
870 tempBuffer.offset = ex->used;
871 tempBuffer.length = ex->buf_sz - ex->buf_ofs;
872 tempBuffer.data = ex->buf + ex->buf_ofs;
873 debugs(38, 3, "netdbExchangeHandleReply: EOF not received");
874 storeClientCopy(ex->sc, ex->e, tempBuffer,
875 netdbExchangeHandleReply, ex);
876 }
877 }
878
879 #endif /* USE_ICMP */
880
881 /* PUBLIC FUNCTIONS */
882
883 void
884 netdbInit(void)
885 {
886 #if USE_ICMP
887 Mgr::RegisterAction("netdb", "Network Measurement Database", netdbDump, 0, 1);
888
889 if (addr_table)
890 return;
891
892 int n = hashPrime(Config.Netdb.high / 4);
893
894 addr_table = hash_create((HASHCMP *) strcmp, n, hash_string);
895
896 n = hashPrime(3 * Config.Netdb.high / 4);
897
898 host_table = hash_create((HASHCMP *) strcmp, n, hash_string);
899
900 eventAddIsh("netdbSaveState", netdbSaveState, NULL, 3600.0, 1);
901
902 netdbReloadState();
903
904 #endif
905 }
906
907 void
908 netdbPingSite(const char *hostname)
909 {
910 #if USE_ICMP
911 netdbEntry *n;
912
913 if ((n = netdbLookupHost(hostname)) != NULL)
914 if (n->next_ping_time > squid_curtime)
915 return;
916
917 ipcache_nbgethostbyname(hostname, netdbSendPing,
918 new generic_cbdata(xstrdup(hostname)));
919
920 #endif
921 }
922
923 void
924 netdbHandlePingReply(const Ip::Address &from, int hops, int rtt)
925 {
926 #if USE_ICMP
927 netdbEntry *n;
928 int N;
929 debugs(38, 3, "netdbHandlePingReply: from " << from);
930
931 if ((n = netdbLookupAddr(from)) == NULL)
932 return;
933
934 N = ++n->pings_recv;
935
936 if (N > 5)
937 N = 5;
938
939 if (rtt < 1)
940 rtt = 1;
941
942 n->hops = ((n->hops * (N - 1)) + hops) / N;
943
944 n->rtt = ((n->rtt * (N - 1)) + rtt) / N;
945
946 debugs(38, 3, "netdbHandlePingReply: " << n->network << "; rtt="<<
947 std::setw(5)<< std::setprecision(2) << n->rtt << " hops="<<
948 std::setw(4) << n->hops);
949
950 #endif
951 }
952
953 void
954 netdbFreeMemory(void)
955 {
956 #if USE_ICMP
957 hashFreeItems(addr_table, netdbFreeNetdbEntry);
958 hashFreeMemory(addr_table);
959 addr_table = NULL;
960 hashFreeItems(host_table, netdbFreeNameEntry);
961 hashFreeMemory(host_table);
962 host_table = NULL;
963 wordlistDestroy(&peer_names);
964 peer_names = NULL;
965 #endif
966 }
967
968 void
969 netdbDump(StoreEntry * sentry)
970 {
971 #if USE_ICMP
972 netdbEntry *n;
973 netdbEntry **list;
974 net_db_name *x;
975 int k;
976 int i;
977 int j;
978 net_db_peer *p;
979 storeAppendPrintf(sentry, "Network DB Statistics:\n");
980 storeAppendPrintf(sentry, "%-46.46s %9s %7s %5s %s\n", /* Max between 16 (IPv4) or 46 (IPv6) */
981 "Network",
982 "recv/sent",
983 "RTT",
984 "Hops",
985 "Hostnames");
986 list = (netdbEntry **)xcalloc(netdbEntry::UseCount(), sizeof(netdbEntry *));
987 i = 0;
988 hash_first(addr_table);
989
990 while ((n = (netdbEntry *) hash_next(addr_table))) {
991 *(list + i) = n;
992 ++i;
993 }
994
995 if (i != netdbEntry::UseCount())
996 debugs(38, DBG_CRITICAL, "WARNING: netdb_addrs count off, found " << i <<
997 ", expected " << netdbEntry::UseCount());
998
999 qsort((char *) list,
1000 i,
1001 sizeof(netdbEntry *),
1002 sortByRtt);
1003
1004 for (k = 0; k < i; ++k) {
1005 n = *(list + k);
1006 storeAppendPrintf(sentry, "%-46.46s %4d/%4d %7.1f %5.1f", /* Max between 16 (IPv4) or 46 (IPv6) */
1007 n->network,
1008 n->pings_recv,
1009 n->pings_sent,
1010 n->rtt,
1011 n->hops);
1012
1013 for (x = n->hosts; x; x = x->next)
1014 storeAppendPrintf(sentry, " %s", hashKeyStr(&x->hash));
1015
1016 storeAppendPrintf(sentry, "\n");
1017
1018 p = n->peers;
1019
1020 for (j = 0; j < n->n_peers; ++j, ++p) {
1021 storeAppendPrintf(sentry, " %-22.22s %7.1f %5.1f\n",
1022 p->peername,
1023 p->rtt,
1024 p->hops);
1025 }
1026 }
1027
1028 xfree(list);
1029 #else
1030
1031 storeAppendPrintf(sentry,"NETDB support not compiled into this Squid cache.\n");
1032 #endif
1033 }
1034
1035 int
1036 netdbHostHops(const char *host)
1037 {
1038 #if USE_ICMP
1039 netdbEntry *n = netdbLookupHost(host);
1040
1041 if (n) {
1042 n->last_use_time = squid_curtime;
1043 return (int) (n->hops + 0.5);
1044 }
1045
1046 #endif
1047 return 0;
1048 }
1049
1050 int
1051 netdbHostRtt(const char *host)
1052 {
1053 #if USE_ICMP
1054 netdbEntry *n = netdbLookupHost(host);
1055
1056 if (n) {
1057 n->last_use_time = squid_curtime;
1058 return (int) (n->rtt + 0.5);
1059 }
1060
1061 #endif
1062 return 0;
1063 }
1064
1065 void
1066 netdbHostData(const char *host, int *samp, int *rtt, int *hops)
1067 {
1068 #if USE_ICMP
1069 netdbEntry *n = netdbLookupHost(host);
1070
1071 if (n == NULL)
1072 return;
1073
1074 *samp = n->pings_recv;
1075
1076 *rtt = (int) (n->rtt + 0.5);
1077
1078 *hops = (int) (n->hops + 0.5);
1079
1080 n->last_use_time = squid_curtime;
1081
1082 #endif
1083 }
1084
1085 void
1086 netdbUpdatePeer(const URL &url, CachePeer * e, int irtt, int ihops)
1087 {
1088 #if USE_ICMP
1089 netdbEntry *n;
1090 double rtt = (double) irtt;
1091 double hops = (double) ihops;
1092 net_db_peer *p;
1093 debugs(38, 3, url.host() << ", " << ihops << " hops, " << irtt << " rtt");
1094 n = netdbLookupHost(url.host());
1095
1096 if (n == NULL) {
1097 debugs(38, 3, "host " << url.host() << " not found");
1098 return;
1099 }
1100
1101 if ((p = netdbPeerByName(n, e->host)) == NULL)
1102 p = netdbPeerAdd(n, e);
1103
1104 p->rtt = rtt;
1105
1106 p->hops = hops;
1107
1108 p->expires = squid_curtime + 3600;
1109
1110 if (n->n_peers < 2)
1111 return;
1112
1113 qsort((char *) n->peers,
1114 n->n_peers,
1115 sizeof(net_db_peer),
1116 sortPeerByRtt);
1117
1118 #endif
1119 }
1120
1121 void
1122 netdbExchangeUpdatePeer(Ip::Address &addr, CachePeer * e, double rtt, double hops)
1123 {
1124 #if USE_ICMP
1125 netdbEntry *n;
1126 net_db_peer *p;
1127 debugs(38, 5, "netdbExchangeUpdatePeer: '" << addr << "', "<<
1128 std::setfill('0')<< std::setprecision(2) << hops << " hops, " <<
1129 rtt << " rtt");
1130
1131 if ( !addr.isIPv4() ) {
1132 debugs(38, 5, "netdbExchangeUpdatePeer: Aborting peer update for '" << addr << "', NetDB cannot handle IPv6.");
1133 return;
1134 }
1135
1136 n = netdbLookupAddr(addr);
1137
1138 if (n == NULL)
1139 n = netdbAdd(addr);
1140
1141 assert(NULL != n);
1142
1143 if ((p = netdbPeerByName(n, e->host)) == NULL)
1144 p = netdbPeerAdd(n, e);
1145
1146 p->rtt = rtt;
1147
1148 p->hops = hops;
1149
1150 p->expires = squid_curtime + 3600; /* XXX ? */
1151
1152 if (n->n_peers < 2)
1153 return;
1154
1155 qsort((char *) n->peers,
1156 n->n_peers,
1157 sizeof(net_db_peer),
1158 sortPeerByRtt);
1159
1160 #endif
1161 }
1162
1163 void
1164 netdbDeleteAddrNetwork(Ip::Address &addr)
1165 {
1166 #if USE_ICMP
1167 netdbEntry *n = netdbLookupAddr(addr);
1168
1169 if (n == NULL)
1170 return;
1171
1172 debugs(38, 3, "netdbDeleteAddrNetwork: " << n->network);
1173
1174 netdbRelease(n);
1175 #endif
1176 }
1177
1178 void
1179 netdbBinaryExchange(StoreEntry * s)
1180 {
1181 HttpReply *reply = new HttpReply;
1182 #if USE_ICMP
1183
1184 Ip::Address addr;
1185
1186 netdbEntry *n;
1187 int i;
1188 int j;
1189 int rec_sz;
1190 char *buf;
1191
1192 struct in_addr line_addr;
1193 s->buffer();
1194 reply->setHeaders(Http::scOkay, "OK", NULL, -1, squid_curtime, -2);
1195 s->replaceHttpReply(reply);
1196 rec_sz = 0;
1197 rec_sz += 1 + sizeof(struct in_addr);
1198 rec_sz += 1 + sizeof(int);
1199 rec_sz += 1 + sizeof(int);
1200 buf = (char *)memAllocate(MEM_4K_BUF);
1201 i = 0;
1202 hash_first(addr_table);
1203
1204 while ((n = (netdbEntry *) hash_next(addr_table))) {
1205 if (0.0 == n->rtt)
1206 continue;
1207
1208 if (n->rtt > 60000) /* RTT > 1 MIN probably bogus */
1209 continue;
1210
1211 if (! (addr = n->network) )
1212 continue;
1213
1214 /* FIXME INET6 : NetDB cannot yet handle IPv6 addresses. Ensure only IPv4 get sent. */
1215 if ( !addr.isIPv4() )
1216 continue;
1217
1218 buf[i] = (char) NETDB_EX_NETWORK;
1219 ++i;
1220
1221 addr.getInAddr(line_addr);
1222 memcpy(&buf[i], &line_addr, sizeof(struct in_addr));
1223
1224 i += sizeof(struct in_addr);
1225
1226 buf[i] = (char) NETDB_EX_RTT;
1227 ++i;
1228
1229 j = htonl((int) (n->rtt * 1000));
1230
1231 memcpy(&buf[i], &j, sizeof(int));
1232
1233 i += sizeof(int);
1234
1235 buf[i] = (char) NETDB_EX_HOPS;
1236 ++i;
1237
1238 j = htonl((int) (n->hops * 1000));
1239
1240 memcpy(&buf[i], &j, sizeof(int));
1241
1242 i += sizeof(int);
1243
1244 if (i + rec_sz > 4096) {
1245 s->append(buf, i);
1246 i = 0;
1247 }
1248 }
1249
1250 if (i > 0) {
1251 s->append(buf, i);
1252 i = 0;
1253 }
1254
1255 assert(0 == i);
1256 s->flush();
1257 memFree(buf, MEM_4K_BUF);
1258 #else
1259
1260 reply->setHeaders(Http::scBadRequest, "Bad Request", NULL, -1, squid_curtime, -2);
1261 s->replaceHttpReply(reply);
1262 storeAppendPrintf(s, "NETDB support not compiled into this Squid cache.\n");
1263 #endif
1264
1265 s->complete();
1266 }
1267
1268 void
1269 netdbExchangeStart(void *data)
1270 {
1271 #if USE_ICMP
1272 CachePeer *p = (CachePeer *)data;
1273 static const SBuf netDB("netdb");
1274 char *uri = internalRemoteUri(p->host, p->http_port, "/squid-internal-dynamic/", netDB);
1275 debugs(38, 3, "netdbExchangeStart: Requesting '" << uri << "'");
1276 assert(NULL != uri);
1277 const MasterXaction::Pointer mx = new MasterXaction(XactionInitiator::initIcmp);
1278 HttpRequestPointer req(HttpRequest::FromUrl(uri, mx));
1279
1280 if (!req) {
1281 debugs(38, DBG_IMPORTANT, "netdbExchangeStart: Bad URI " << uri);
1282 return;
1283 }
1284
1285 netdbExchangeState *ex = new netdbExchangeState(p, req);
1286 ex->e = storeCreateEntry(uri, uri, RequestFlags(), Http::METHOD_GET);
1287 assert(NULL != ex->e);
1288
1289 StoreIOBuffer tempBuffer;
1290 tempBuffer.length = ex->buf_sz;
1291 tempBuffer.data = ex->buf;
1292
1293 ex->sc = storeClientListAdd(ex->e, ex);
1294
1295 storeClientCopy(ex->sc, ex->e, tempBuffer,
1296 netdbExchangeHandleReply, ex);
1297 ex->r->flags.loopDetected = true; /* cheat! -- force direct */
1298
1299 // XXX: send as Proxy-Authenticate instead
1300 if (p->login)
1301 ex->r->url.userInfo(SBuf(p->login));
1302
1303 FwdState::fwdStart(Comm::ConnectionPointer(), ex->e, ex->r.getRaw());
1304 #endif
1305 }
1306
1307 CachePeer *
1308 netdbClosestParent(HttpRequest * request)
1309 {
1310 #if USE_ICMP
1311 CachePeer *p = NULL;
1312 netdbEntry *n;
1313 const ipcache_addrs *ia;
1314 net_db_peer *h;
1315 int i;
1316 n = netdbLookupHost(request->url.host());
1317
1318 if (NULL == n) {
1319 /* try IP addr */
1320 ia = ipcache_gethostbyname(request->url.host(), 0);
1321
1322 if (NULL != ia)
1323 n = netdbLookupAddr(ia->in_addrs[ia->cur]);
1324 }
1325
1326 if (NULL == n)
1327 return NULL;
1328
1329 if (0 == n->n_peers)
1330 return NULL;
1331
1332 n->last_use_time = squid_curtime;
1333
1334 /*
1335 * Find the parent with the least RTT to the origin server.
1336 * Make sure we don't return a parent who is farther away than
1337 * we are. Note, the n->peers list is pre-sorted by RTT.
1338 */
1339 for (i = 0; i < n->n_peers; ++i) {
1340 h = &n->peers[i];
1341
1342 if (n->rtt > 0)
1343 if (n->rtt < h->rtt)
1344 break;
1345
1346 p = peerFindByName(h->peername);
1347
1348 if (NULL == p) /* not found */
1349 continue;
1350
1351 if (neighborType(p, request->url) != PEER_PARENT)
1352 continue;
1353
1354 if (!peerHTTPOkay(p, request)) /* not allowed */
1355 continue;
1356
1357 return p;
1358 }
1359
1360 #endif
1361 return NULL;
1362 }
1363