Revamped debug/verbosity control to use flags for functions of interest

instead of general verbosity ramp.
This commit is contained in:
gardners 2012-01-10 15:56:40 +10:30
parent 26a2c62555
commit 800f8d41eb
17 changed files with 297 additions and 251 deletions

View File

@ -47,25 +47,25 @@ int readRoutingTable(struct in_addr peers[],int *peer_count,int peer_max){
unsigned long d, g, m; unsigned long d, g, m;
int flgs, ref, use, metric, mtu, win, ir; int flgs, ref, use, metric, mtu, win, ir;
if (debug) fprintf(stderr,"Reading routing table\n"); if (debug&DEBUG_PEERS) fprintf(stderr,"Reading routing table\n");
FILE *fp = fopen("/proc/net/route","r"); FILE *fp = fopen("/proc/net/route","r");
if (!fp) return -1; if (!fp) return -1;
if (debug>1) fprintf(stderr,"Skipping line\n"); if (debug&DEBUG_PEERS) fprintf(stderr,"Skipping line\n");
if (fscanf(fp, "%*[^\n]\n") < 0) if (fscanf(fp, "%*[^\n]\n") < 0)
goto ERROR; goto ERROR;
while(1){ while(1){
int r; int r;
if (debug>1) fprintf(stderr,"Reading next route\n"); if (debug&DEBUG_PEERS) fprintf(stderr,"Reading next route\n");
r = fscanf(fp, "%63s%lx%lx%X%d%d%d%lx%d%d%d\n", r = fscanf(fp, "%63s%lx%lx%X%d%d%d%lx%d%d%d\n",
devname, &d, &g, &flgs, &ref, &use, &metric, &m, devname, &d, &g, &flgs, &ref, &use, &metric, &m,
&mtu, &win, &ir); &mtu, &win, &ir);
if (r != 11) { if (r != 11) {
if ((r < 0) && feof(fp)) { /* EOF with no (nonspace) chars read. */ if ((r < 0) && feof(fp)) { /* EOF with no (nonspace) chars read. */
if (debug>1) fprintf(stderr,"eof\n"); if (debug&DEBUG_PEERS) fprintf(stderr,"eof\n");
break; break;
} }
ERROR: ERROR:
@ -74,18 +74,18 @@ int readRoutingTable(struct in_addr peers[],int *peer_count,int peer_max){
} }
if (!(flgs & RTF_UP)) { /* Skip interfaces that are down. */ if (!(flgs & RTF_UP)) { /* Skip interfaces that are down. */
if (debug>1) fprintf(stderr,"Skipping down interface %s\n",devname); if (debug&DEBUG_PEERS) fprintf(stderr,"Skipping down interface %s\n",devname);
continue; continue;
} }
if (m!=0xFFFFFFFF){ if (m!=0xFFFFFFFF){
/* Netmask indicates a network, so calculate broadcast address */ /* Netmask indicates a network, so calculate broadcast address */
d=(d&m)|(0xffffffff^m); d=(d&m)|(0xffffffff^m);
if (debug) fprintf(stderr,"Adding broadcast address %08lx\n",d); if (debug&DEBUG_PEERS) fprintf(stderr,"Adding broadcast address %08lx\n",d);
} }
if (*peer_count<peer_max) peers[(*peer_count)++].s_addr=d; if (*peer_count<peer_max) peers[(*peer_count)++].s_addr=d;
if (debug>2) fprintf(stderr,"Found peer %08lx from routing table\n",d); if (debug&DEBUG_PEERS) fprintf(stderr,"Found peer %08lx from routing table\n",d);
} }
fclose(fp); fclose(fp);
return 0; return 0;
@ -95,12 +95,12 @@ int readArpTable(struct in_addr peers[],int *peer_count,int peer_max){
unsigned long d; unsigned long d;
int q1,q2,q3,q4; int q1,q2,q3,q4;
if (debug) fprintf(stderr,"Reading ARP table\n"); if (debug&DEBUG_PEERS) fprintf(stderr,"Reading ARP table\n");
FILE *fp = fopen("/proc/net/arp","r"); FILE *fp = fopen("/proc/net/arp","r");
if (!fp) return -1; if (!fp) return -1;
if (debug>1) fprintf(stderr,"Skipping line\n"); if (debug&DEBUG_PEERS) fprintf(stderr,"Skipping line\n");
if (fscanf(fp, "%*[^\n]\n") < 0) if (fscanf(fp, "%*[^\n]\n") < 0)
goto ERROR; goto ERROR;
@ -108,7 +108,7 @@ int readArpTable(struct in_addr peers[],int *peer_count,int peer_max){
int r; int r;
r = fscanf(fp, "%d.%d.%d.%d%*[^\n]\n", r = fscanf(fp, "%d.%d.%d.%d%*[^\n]\n",
&q1,&q2,&q3,&q4); &q1,&q2,&q3,&q4);
if (debug>1) fprintf(stderr,"Reading next arp entry (r=%d, %d.%d.%d.%d)\n",r,q1,q2,q3,q4); if (debug&DEBUG_PEERS) fprintf(stderr,"Reading next arp entry (r=%d, %d.%d.%d.%d)\n",r,q1,q2,q3,q4);
d = (q1&0xff) d = (q1&0xff)
+((q2&0xff)<<8) +((q2&0xff)<<8)
@ -117,7 +117,7 @@ int readArpTable(struct in_addr peers[],int *peer_count,int peer_max){
if (r != 4) { if (r != 4) {
if ((r < 0) && feof(fp)) { /* EOF with no (nonspace) chars read. */ if ((r < 0) && feof(fp)) { /* EOF with no (nonspace) chars read. */
if (debug>1) fprintf(stderr,"eof\n"); if (debug&DEBUG_PEERS) fprintf(stderr,"eof\n");
break; break;
} }
ERROR: ERROR:
@ -126,7 +126,7 @@ int readArpTable(struct in_addr peers[],int *peer_count,int peer_max){
} }
if (*peer_count<peer_max) peers[(*peer_count)++].s_addr=d; if (*peer_count<peer_max) peers[(*peer_count)++].s_addr=d;
if (debug>2) fprintf(stderr,"Found peer %08lx from ARP table\n",d); if (debug&DEBUG_PEERS) fprintf(stderr,"Found peer %08lx from ARP table\n",d);
} }
fclose(fp); fclose(fp);
return 0; return 0;
@ -161,7 +161,7 @@ int readBatmanPeerFile(char *file_path,struct in_addr peers[],int *peer_count,in
timestamp=ntohl(timestamp); timestamp=ntohl(timestamp);
if (timestamp<(time(0)-3)) { if (timestamp<(time(0)-3)) {
if (debug>1) fprintf(stderr,"Ignoring stale BATMAN peer list (%d seconds old)\n",(int)(time(0)-timestamp)); if (debug&DEBUG_PEERS) fprintf(stderr,"Ignoring stale BATMAN peer list (%d seconds old)\n",(int)(time(0)-timestamp));
fclose(f); fclose(f);
return -1; return -1;
} }
@ -172,7 +172,7 @@ int readBatmanPeerFile(char *file_path,struct in_addr peers[],int *peer_count,in
if (!p.addr_len) break; if (!p.addr_len) break;
i.s_addr=*(unsigned int *)&p.addr[0]; i.s_addr=*(unsigned int *)&p.addr[0];
if (*peer_count<peer_max) peers[(*peer_count)++]=i; if (*peer_count<peer_max) peers[(*peer_count)++]=i;
if (debug>1) fprintf(stderr,"Found BATMAN peer '%s'\n",inet_ntoa(i)); if (debug&DEBUG_PEERS) fprintf(stderr,"Found BATMAN peer '%s'\n",inet_ntoa(i));
} }
fclose(f); fclose(f);
@ -222,7 +222,7 @@ int getBatmanPeerList(char *socket_path,struct in_addr peers[],int *peer_count,i
{ {
switch (poll(&fds,1,1500)) { switch (poll(&fds,1,1500)) {
case 1: /* Excellent - we have a response */ break; case 1: /* Excellent - we have a response */ break;
case 0: if (debug>1) fprintf(stderr,"BATMAN did not respond to peer enquiry.\n"); case 0: if (debug&DEBUG_PEERS) fprintf(stderr,"BATMAN did not respond to peer enquiry.\n");
close(sock); close(sock);
if (tries++<=3) goto askagain; if (tries++<=3) goto askagain;
return setReason("No response from BATMAN."); return setReason("No response from BATMAN.");
@ -239,7 +239,7 @@ int getBatmanPeerList(char *socket_path,struct in_addr peers[],int *peer_count,i
/* Got a partial response, then a dead line. /* Got a partial response, then a dead line.
Should probably ask again unless we have tried too many times. Should probably ask again unless we have tried too many times.
*/ */
if (debug>2) fprintf(stderr,"Trying again after cold drop.\n"); if (debug&DEBUG_PEERS) fprintf(stderr,"Trying again after cold drop.\n");
close(sock); close(sock);
bytes=0; bytes=0;
if (tries++<=3) goto askagain; if (tries++<=3) goto askagain;
@ -248,9 +248,9 @@ int getBatmanPeerList(char *socket_path,struct in_addr peers[],int *peer_count,i
return setReason("failed to read() from BATMAN socket."); return setReason("failed to read() from BATMAN socket.");
} }
if (!res) return 0; if (!res) return 0;
if (debug>1) fprintf(stderr,"BATMAN has responded with %d bytes.\n",res); if (debug&DEBUG_PEERS) fprintf(stderr,"BATMAN has responded with %d bytes.\n",res);
if (debug>2) dump("BATMAN says",&buf[bytes],res); if (debug&DEBUG_PEERS) dump("BATMAN says",&buf[bytes],res);
if (res<80 /*||buf[bytes]!='B' -- turns out we can't rely on this, either */ if (res<80 /*||buf[bytes]!='B' -- turns out we can't rely on this, either */
||buf[bytes+res-1]!=0x0a||buf[bytes+res-4]!='E') ||buf[bytes+res-1]!=0x0a||buf[bytes+res-4]!='E')
@ -265,7 +265,7 @@ int getBatmanPeerList(char *socket_path,struct in_addr peers[],int *peer_count,i
*/ */
if (buf[bytes+res-4]!='E') { if (buf[bytes+res-4]!='E') {
/* no end marker, so try adding record to the end. */ /* no end marker, so try adding record to the end. */
if (debug>2) fprintf(stderr,"Data has no end marker, accumulating.\n"); if (debug&DEBUG_PEERS) fprintf(stderr,"Data has no end marker, accumulating.\n");
bytes+=res; bytes+=res;
goto getmore; goto getmore;
} }
@ -276,7 +276,7 @@ int getBatmanPeerList(char *socket_path,struct in_addr peers[],int *peer_count,i
while(ofs<bytes) while(ofs<bytes)
{ {
if(debug>1) fprintf(stderr,"New line @ %d\n",ofs); if(debug&DEBUG_PEERS) fprintf(stderr,"New line @ %d\n",ofs);
/* Check for IP address of peers */ /* Check for IP address of peers */
if (isdigit(buf[ofs])) if (isdigit(buf[ofs]))
{ {
@ -285,7 +285,7 @@ int getBatmanPeerList(char *socket_path,struct in_addr peers[],int *peer_count,i
if (buf[i+ofs]==' ') { if (buf[i+ofs]==' ') {
buf[i+ofs]=0; buf[i+ofs]=0;
if (*peer_count<peer_max) peers[(*peer_count)++].s_addr=inet_addr((char *)&buf[ofs]); if (*peer_count<peer_max) peers[(*peer_count)++].s_addr=inet_addr((char *)&buf[ofs]);
if (debug>1) fprintf(stderr,"Found BATMAN peer '%s'\n",&buf[ofs]); if (debug&DEBUG_PEERS) fprintf(stderr,"Found BATMAN peer '%s'\n",&buf[ofs]);
buf[ofs+i]=' '; buf[ofs+i]=' ';
break; break;
} }

111
client.c
View File

@ -42,10 +42,10 @@ int packetSendFollowup(struct in_addr destination,
r=sendto(sock,packet,packet_len,0,(struct sockaddr *)&peer_addr,sizeof(peer_addr)); r=sendto(sock,packet,packet_len,0,(struct sockaddr *)&peer_addr,sizeof(peer_addr));
if (r<packet_len) { if (r<packet_len) {
if (debug) fprintf(stderr,"Could not send to %s (r=%d, packet_len=%d)\n",inet_ntoa(destination),r,packet_len); if (debug&DEBUG_PACKETXFER) fprintf(stderr,"Could not send to %s (r=%d, packet_len=%d)\n",inet_ntoa(destination),r,packet_len);
perror("sendto(a)"); perror("sendto(a)");
} else { } else {
if (debug>1) fprintf(stderr,"Sent request to client %s\n",inet_ntoa(destination)); if (debug&DEBUG_PACKETXFER) fprintf(stderr,"Sent request to client %s\n",inet_ntoa(destination));
} }
return 0; return 0;
} }
@ -83,11 +83,11 @@ int packetSendRequest(int method,unsigned char *packet,int packet_len,int batchP
else else
r=sendto(sock,packet,packet_len,0,recvaddr,sizeof(struct sockaddr_in)); r=sendto(sock,packet,packet_len,0,recvaddr,sizeof(struct sockaddr_in));
if (r<packet_len) { if (r<packet_len) {
if (debug) fprintf(stderr,"Could not send to client %s (packet=%p,len=%d,sock=%d)\n", if (debug&DEBUG_PACKETXFER) fprintf(stderr,"Could not send to client %s (packet=%p,len=%d,sock=%d)\n",
inet_ntoa(client_addr),packet,packet_len,sock); inet_ntoa(client_addr),packet,packet_len,sock);
perror("sendto(b)"); perror("sendto(b)");
} else { } else {
if (debug>1) fprintf(stderr,"Sent request to client %s\n",inet_ntoa(client_addr)); if (debug&DEBUG_PACKETXFER) fprintf(stderr,"Sent request to client %s\n",inet_ntoa(client_addr));
} }
return 0; return 0;
} }
@ -146,19 +146,19 @@ int packetSendRequest(int method,unsigned char *packet,int packet_len,int batchP
peers and so tests that we wait if not all peers have responded) */ peers and so tests that we wait if not all peers have responded) */
break; break;
case REQ_FIRSTREPLY: case REQ_FIRSTREPLY:
if (debug>1) fprintf(stderr,"Returning with first reply (REQ_FIRSTREPLY)\n"); if (debug&DEBUG_DNARESPONSES) fprintf(stderr,"Returning with first reply (REQ_FIRSTREPLY)\n");
if (!r) return 0; if (!r) return 0;
break; break;
case REQ_SERIAL: case REQ_SERIAL:
if (!r) { if (!r) {
/* Stop if we have an affirmative response. /* Stop if we have an affirmative response.
XXX - doesn't allow for out of order replies. */ XXX - doesn't allow for out of order replies. */
if (debug>1) dumpResponses(responses); if (debug&DEBUG_DNARESPONSES) dumpResponses(responses);
rr=responses->last_response; rr=responses->last_response;
while (rr) while (rr)
{ {
if (rr->checked) break; if (rr->checked) break;
if (debug>1) if (debug&DEBUG_DNARESPONSES)
fprintf(stderr,"Got a response code 0x%02x, checking if that is what we need.\n",rr->code); fprintf(stderr,"Got a response code 0x%02x, checking if that is what we need.\n",rr->code);
switch (rr->code) switch (rr->code)
{ {
@ -198,7 +198,7 @@ int packetSendRequest(int method,unsigned char *packet,int packet_len,int batchP
} }
cumulative_timeout+=this_timeout; cumulative_timeout+=this_timeout;
} }
if (debug>1) if (cumulative_timeout>=timeout) if (debug&DEBUG_DNARESPONSES) if (cumulative_timeout>=timeout)
fprintf(stderr,"Request timed out after retries (timeout=%d, elapsed=%d).\n", fprintf(stderr,"Request timed out after retries (timeout=%d, elapsed=%d).\n",
timeout,cumulative_timeout); timeout,cumulative_timeout);
@ -231,7 +231,7 @@ int requestNewHLR(char *did,char *pin,char *sid,struct sockaddr *recvaddr)
if (packetSendRequest(REQ_SERIAL,packet,packet_len,NONBATCH,transaction_id,recvaddr,&responses)) return -1; if (packetSendRequest(REQ_SERIAL,packet,packet_len,NONBATCH,transaction_id,recvaddr,&responses)) return -1;
/* Extract response */ /* Extract response */
if (debug>2) dumpResponses(&responses); if (debug&DEBUG_DNARESPONSES) dumpResponses(&responses);
if (!responses.response_count) { if (!responses.response_count) {
printf("NOREPLY\n"); printf("NOREPLY\n");
return -1; return -1;
@ -264,25 +264,28 @@ int fixResponses(struct response_set *responses)
{ {
struct response *rr; struct response *rr;
if (debug>1) fprintf(stderr,"Fixing response set\n"); if (debug&DEBUG_DNARESPONSES) fprintf(stderr,"Fixing response set\n");
if (!responses) return -1; if (!responses) return -1;
rr=responses->responses; rr=responses->responses;
while(rr) while(rr)
{ {
if (debug>1) fprintf(stderr," len=%d, rr->code=%02x, rr->var_id=%02x\n", if (debug&DEBUG_DNARESPONSES)
rr->value_bytes,rr->code,rr->var_id); fprintf(stderr," len=%d, rr->code=%02x, rr->var_id=%02x\n",
rr->value_bytes,rr->code,rr->var_id);
if (rr->value_bytes>0&&rr->code==ACTION_DATA&&rr->var_id==VAR_LOCATIONS) if (rr->value_bytes>0&&rr->code==ACTION_DATA&&rr->var_id==VAR_LOCATIONS)
{ {
if (debug>1) fprintf(stderr," response='%s'\n",rr->response); if (debug&DEBUG_DNARESPONSES)
fprintf(stderr," response='%s'\n",rr->response);
if (rr->response[rr->value_bytes-1]=='@') if (rr->response[rr->value_bytes-1]=='@')
{ {
/* Append response with IP address of sender */ /* Append response with IP address of sender */
char *addr=inet_ntoa(rr->sender); char *addr=inet_ntoa(rr->sender);
int alen=strlen(addr); int alen=strlen(addr);
char *new = malloc(rr->value_bytes+alen+1); char *new = malloc(rr->value_bytes+alen+1);
if (debug>1) fprintf(stderr,"Fixing LOCATIONS response '%s' received from '%s (0x%08x)'\n", if (debug&DEBUG_DNARESPONSES)
fprintf(stderr,"Fixing LOCATIONS response '%s' received from '%s (0x%08x)'\n",
rr->response,addr,(unsigned int)rr->sender.s_addr); rr->response,addr,(unsigned int)rr->sender.s_addr);
if (!new) return -1; if (!new) return -1;
bcopy(rr->response,new,rr->value_bytes); bcopy(rr->response,new,rr->value_bytes);
@ -292,7 +295,7 @@ int fixResponses(struct response_set *responses)
rr->value_len+=alen; rr->value_len+=alen;
rr->value_bytes+=alen; rr->value_bytes+=alen;
new[rr->value_len]=0; /* Make sure it is null terminated */ new[rr->value_len]=0; /* Make sure it is null terminated */
if (debug>1) fprintf(stderr,"Response string now '%s'\n",rr->response); if (debug&DEBUG_DNARESPONSES) fprintf(stderr,"Response string now '%s'\n",rr->response);
} }
} }
rr=rr->next; rr=rr->next;
@ -315,7 +318,7 @@ int getReplyPackets(int method,int peer,int batchP,struct response_set *response
int to=timeout; int to=timeout;
int len; int len;
if (debug>1) printf("getReplyPackets(policy=%d)\n",method); if (debug&DEBUG_DNARESPONSES) printf("getReplyPackets(policy=%d)\n",method);
/* Work out when the timeout will expire */ /* Work out when the timeout will expire */
gettimeofday(&t,NULL); gettimeofday(&t,NULL);
@ -350,13 +353,13 @@ int getReplyPackets(int method,int peer,int batchP,struct response_set *response
client_port=((struct sockaddr_in *)recvaddr)->sin_port; client_port=((struct sockaddr_in *)recvaddr)->sin_port;
client_addr=((struct sockaddr_in *)recvaddr)->sin_addr; client_addr=((struct sockaddr_in *)recvaddr)->sin_addr;
if (debug) fprintf(stderr,"Received reply from %s (len=%d).\n",inet_ntoa(client_addr),len); if (debug&DEBUG_DNARESPONSES) fprintf(stderr,"Received reply from %s (len=%d).\n",inet_ntoa(client_addr),len);
if (debug>1) dump("recvaddr",(unsigned char *)&sender,recvaddrlen); if (debug&DEBUG_DNARESPONSES) dump("recvaddr",(unsigned char *)&sender,recvaddrlen);
if (debug>2) dump("packet",(unsigned char *)buffer,len); if (debug&DEBUG_DNARESPONSES) dump("packet",(unsigned char *)buffer,len);
} }
if (dropPacketP(len)) { if (dropPacketP(len)) {
if (debug) fprintf(stderr,"Simulation mode: Dropped packet due to simulated link parameters.\n"); if (debug&DEBUG_SIMULATION) fprintf(stderr,"Simulation mode: Dropped packet due to simulated link parameters.\n");
continue; continue;
} }
if (!packetOk(-1,buffer,len,transaction_id,recvaddr,recvaddrlen,0)) { if (!packetOk(-1,buffer,len,transaction_id,recvaddr,recvaddrlen,0)) {
@ -381,10 +384,10 @@ int getReplyPackets(int method,int peer,int batchP,struct response_set *response
} }
} }
else { else {
if (debug>1) printf("Waiting for more packets, since called with policy %d\n",method); if (debug&DEBUG_DNARESPONSES) printf("Waiting for more packets, since called with policy %d\n",method);
} }
} else { } else {
if (debug) setReason("Ignoring invalid packet"); if (debug&(DEBUG_PACKETXFER|DEBUG_DNARESPONSES)) setReason("Ignoring invalid packet");
} }
} }
} }
@ -400,7 +403,7 @@ int writeItem(char *sid,int var_id,int instance,unsigned char *value,
bzero(&responses,sizeof(responses)); bzero(&responses,sizeof(responses));
if (debug>1) fprintf(stderr,"Writing %d bytes of var %02x/%02x @ 0x%d flags=%d\n", if (debug&DEBUG_DNAVARS) fprintf(stderr,"Writing %d bytes of var %02x/%02x @ 0x%d flags=%d\n",
value_length,var_id,instance,value_start,flags); value_length,var_id,instance,value_start,flags);
if (!sid) { if (!sid) {
@ -413,16 +416,16 @@ int writeItem(char *sid,int var_id,int instance,unsigned char *value,
if (value_length-value_start>MAX_DATA_BYTES) if (value_length-value_start>MAX_DATA_BYTES)
{ {
int o; int o;
if (debug) fprintf(stderr,"Writing large value (%d bytes)\n",value_length-value_start); if (debug&DEBUG_DNAVARS) fprintf(stderr,"Writing large value (%d bytes)\n",value_length-value_start);
for(o=value_start;o<value_length;o+=MAX_DATA_BYTES) for(o=value_start;o<value_length;o+=MAX_DATA_BYTES)
{ {
int bytes=MAX_DATA_BYTES; int bytes=MAX_DATA_BYTES;
if (o+bytes>value_length) bytes=value_length-o; if (o+bytes>value_length) bytes=value_length-o;
if (debug>1) fprintf(stderr," writing [%d,%d)\n",o,o+bytes-1); if (debug&DEBUG_DNAVARS) fprintf(stderr," writing [%d,%d)\n",o,o+bytes-1);
if (writeItem(sid,var_id,instance,&value[o-value_start],o,bytes, if (writeItem(sid,var_id,instance,&value[o-value_start],o,bytes,
flags|((o>value_start)?SET_FRAGMENT:0),NULL)) flags|((o>value_start)?SET_FRAGMENT:0),NULL))
{ {
if (debug) fprintf(stderr," - writing installment failed\n"); if (debug&DEBUG_DNAVARS) fprintf(stderr," - writing installment failed\n");
return setReason("Failure during multi-packet write of long-value"); return setReason("Failure during multi-packet write of long-value");
} }
} }
@ -497,47 +500,47 @@ int peerAddress(char *did,char *sid,int flags)
As these can get sent out quite often, don't waste time and energy signing. */ As these can get sent out quite often, don't waste time and energy signing. */
if (packetMakeHeader(packet,8000,&packet_len,transaction_id,CRYPT_PUBLIC)) if (packetMakeHeader(packet,8000,&packet_len,transaction_id,CRYPT_PUBLIC))
{ {
if (debug) fprintf(stderr,"%s() failed at line %d\n",__FUNCTION__,__LINE__); if (debug&DEBUG_PACKETFORMATS) fprintf(stderr,"%s() failed at line %d\n",__FUNCTION__,__LINE__);
return -1; return -1;
} }
if (did&&(!sid)) if (did&&(!sid))
{ if (packetSetDid(packet,8000,&packet_len,did)) { { if (packetSetDid(packet,8000,&packet_len,did)) {
if (debug) fprintf(stderr,"%s() failed at line %d\n",__FUNCTION__,__LINE__); if (debug&DEBUG_PACKETFORMATS) fprintf(stderr,"%s() failed at line %d\n",__FUNCTION__,__LINE__);
return -1; } return -1; }
} }
else if (sid&&(!did)) else if (sid&&(!did))
{ if (packetSetSid(packet,8000,&packet_len,sid)) { { if (packetSetSid(packet,8000,&packet_len,sid)) {
if (debug) fprintf(stderr,"%s() failed at line %d\n",__FUNCTION__,__LINE__); if (debug&DEBUG_PACKETFORMATS) fprintf(stderr,"%s() failed at line %d\n",__FUNCTION__,__LINE__);
return -1; return -1;
} }
} }
else { else {
if (debug) fprintf(stderr,"%s() failed at line %d\n",__FUNCTION__,__LINE__); if (debug&DEBUG_PACKETFORMATS) fprintf(stderr,"%s() failed at line %d\n",__FUNCTION__,__LINE__);
return setReason("You must request items by DID or SID, not neither, nor both"); return setReason("You must request items by DID or SID, not neither, nor both");
} }
if (packetAddVariableRequest(packet,8000,&packet_len, if (packetAddVariableRequest(packet,8000,&packet_len,
"dids",0,0,128 /* only small things please */)) { "dids",0,0,128 /* only small things please */)) {
if (debug) fprintf(stderr,"%s() failed at line %d\n",__FUNCTION__,__LINE__); if (debug&DEBUG_DNAVARS) fprintf(stderr,"%s() failed at line %d\n",__FUNCTION__,__LINE__);
return -1; return -1;
} }
if (packetFinalise(packet,8000,&packet_len,CRYPT_PUBLIC)) { if (packetFinalise(packet,8000,&packet_len,CRYPT_PUBLIC)) {
if (debug) fprintf(stderr,"%s() failed at line %d\n",__FUNCTION__,__LINE__); if (debug&DEBUG_PACKETFORMATS) fprintf(stderr,"%s() failed at line %d\n",__FUNCTION__,__LINE__);
return -1; return -1;
} }
method=REQ_PARALLEL; method=REQ_PARALLEL;
if (sid) method=REQ_FIRSTREPLY; if (sid) method=REQ_FIRSTREPLY;
if (packetSendRequest(method,packet,packet_len,NONBATCH,transaction_id,NULL,&responses)) { if (packetSendRequest(method,packet,packet_len,NONBATCH,transaction_id,NULL,&responses)) {
if (debug) fprintf(stderr,"peerAddress() failed because packetSendRequest() failed.\n"); if (debug&DEBUG_PACKETXFER) fprintf(stderr,"peerAddress() failed because packetSendRequest() failed.\n");
return -1; return -1;
} }
r=responses.responses; r=responses.responses;
if (!r) if (!r)
{ {
if (debug) fprintf(stderr,"peerAddress() failed because noone answered.\n"); if (debug&DEBUG_PEERS) fprintf(stderr,"peerAddress() failed because noone answered.\n");
return -1; return -1;
} }
while(r) while(r)
@ -578,40 +581,40 @@ int requestItem(char *did,char *sid,char *item,int instance,unsigned char *buffe
/* Prepare the request packet. Don't let anyone else see what we are asking for. */ /* Prepare the request packet. Don't let anyone else see what we are asking for. */
if (packetMakeHeader(packet,8000,&packet_len,transaction_id,CRYPT_SIGNED|CRYPT_CIPHERED)) if (packetMakeHeader(packet,8000,&packet_len,transaction_id,CRYPT_SIGNED|CRYPT_CIPHERED))
{ {
if (debug) fprintf(stderr,"requestItem() failed at line %d\n",__LINE__); if (debug&DEBUG_DNAREQUESTS) fprintf(stderr,"requestItem() failed at line %d\n",__LINE__);
return -1; return -1;
} }
if (did&&(!sid)) if (did&&(!sid))
{ if (packetSetDid(packet,8000,&packet_len,did)) { { if (packetSetDid(packet,8000,&packet_len,did)) {
if (debug) fprintf(stderr,"requestItem() failed at line %d\n",__LINE__); if (debug&DEBUG_DNAREQUESTS) fprintf(stderr,"requestItem() failed at line %d\n",__LINE__);
return -1; } return -1; }
} }
else if (sid&&(!did)) else if (sid&&(!did))
{ if (packetSetSid(packet,8000,&packet_len,sid)) { { if (packetSetSid(packet,8000,&packet_len,sid)) {
if (debug) fprintf(stderr,"requestItem() failed at line %d\n",__LINE__); if (debug&DEBUG_DNAREQUESTS) fprintf(stderr,"requestItem() failed at line %d\n",__LINE__);
return -1; return -1;
} }
} }
else { else {
if (debug) fprintf(stderr,"requestItem() failed at line %d\n",__LINE__); if (debug&DEBUG_DNAREQUESTS) fprintf(stderr,"requestItem() failed at line %d\n",__LINE__);
return setReason("You must request items by DID or SID, not neither, nor both"); return setReason("You must request items by DID or SID, not neither, nor both");
} }
if (packetAddVariableRequest(packet,8000,&packet_len, if (packetAddVariableRequest(packet,8000,&packet_len,
item,instance,0,buffer_length)) { item,instance,0,buffer_length)) {
if (debug) fprintf(stderr,"requestItem() failed at line %d\n",__LINE__); if (debug&DEBUG_PACKETFORMATS) fprintf(stderr,"requestItem() failed at line %d\n",__LINE__);
return -1; return -1;
} }
if (packetFinalise(packet,8000,&packet_len,CRYPT_SIGNED|CRYPT_CIPHERED)) { if (packetFinalise(packet,8000,&packet_len,CRYPT_SIGNED|CRYPT_CIPHERED)) {
if (debug) fprintf(stderr,"requestItem() failed at line %d\n",__LINE__); if (debug&DEBUG_PACKETFORMATS) fprintf(stderr,"requestItem() failed at line %d\n",__LINE__);
return -1; return -1;
} }
method=REQ_PARALLEL; method=REQ_PARALLEL;
if (sid) method=REQ_FIRSTREPLY; if (sid) method=REQ_FIRSTREPLY;
if (packetSendRequest(method,packet,packet_len,(instance==-1)?BATCH:NONBATCH,transaction_id,NULL,&responses)) { if (packetSendRequest(method,packet,packet_len,(instance==-1)?BATCH:NONBATCH,transaction_id,NULL,&responses)) {
if (debug) fprintf(stderr,"requestItem() failed because packetSendRequest() failed.\n"); if (debug&DEBUG_PACKETXFER) fprintf(stderr,"requestItem() failed because packetSendRequest() failed.\n");
return -1; return -1;
} }
@ -664,7 +667,7 @@ int requestItem(char *did,char *sid,char *item,int instance,unsigned char *buffe
snprintf(outputname,8192,outputtemplate,sid,r->var_id,r->var_instance); snprintf(outputname,8192,outputtemplate,sid,r->var_id,r->var_instance);
outputfile=fopen(outputname,"w"); outputfile=fopen(outputname,"w");
if (!outputfile) printf("ERROR:Could not open output file '%s'",outputname); if (!outputfile) printf("ERROR:Could not open output file '%s'",outputname);
if (debug) fprintf(stderr,"Writing output to '%s'\n",outputname); if (debug&DEBUG_VERBOSE) fprintf(stderr,"Writing output to '%s'\n",outputname);
} }
if (outputfile) fwrite(r->response,r->value_bytes,1,outputfile); if (outputfile) fwrite(r->response,r->value_bytes,1,outputfile);
@ -697,7 +700,7 @@ int requestItem(char *did,char *sid,char *item,int instance,unsigned char *buffe
while(needMoreData&&(tries++<15)) while(needMoreData&&(tries++<15))
{ {
if (debug>1) fprintf(stderr,"Multi-packet request: try %d, %d fragments remaining.\n",tries,needMoreData); if (debug&DEBUG_DNAREQUESTS) fprintf(stderr,"Multi-packet request: try %d, %d fragments remaining.\n",tries,needMoreData);
needMoreData=0; needMoreData=0;
for(i=0;i<recv_map_size;i++) for(i=0;i<recv_map_size;i++)
if (!recv_map[i]) if (!recv_map[i])
@ -705,13 +708,13 @@ int requestItem(char *did,char *sid,char *item,int instance,unsigned char *buffe
needMoreData++; needMoreData++;
offset=i*MAX_DATA_BYTES; offset=i*MAX_DATA_BYTES;
if (debug>1) fprintf(stderr,"Asking for variable segment @ offset %d\n",offset); if (debug&DEBUG_DNAREQUESTS) fprintf(stderr,"Asking for variable segment @ offset %d\n",offset);
/* Send accumulated request direct to the responder */ /* Send accumulated request direct to the responder */
if (packet_len>=MAX_DATA_BYTES) if (packet_len>=MAX_DATA_BYTES)
{ {
if (packetFinalise(packet,8000,&packet_len,CRYPT_CIPHERED|CRYPT_SIGNED)) { if (packetFinalise(packet,8000,&packet_len,CRYPT_CIPHERED|CRYPT_SIGNED)) {
if (debug) fprintf(stderr,"requestItem() failed at line %d\n",__LINE__); if (debug&DEBUG_DNAREQUESTS) fprintf(stderr,"requestItem() failed at line %d\n",__LINE__);
return -1; return -1;
} }
packetSendFollowup(r->sender,packet,packet_len); packetSendFollowup(r->sender,packet,packet_len);
@ -722,11 +725,11 @@ int requestItem(char *did,char *sid,char *item,int instance,unsigned char *buffe
{ {
/* We are requesting data, so ask for privacy */ /* We are requesting data, so ask for privacy */
if (packetMakeHeader(packet,8000,&packet_len,transaction_id,CRYPT_CIPHERED|CRYPT_SIGNED)) { if (packetMakeHeader(packet,8000,&packet_len,transaction_id,CRYPT_CIPHERED|CRYPT_SIGNED)) {
if (debug) fprintf(stderr,"requestItem() failed at line %d\n",__LINE__); if (debug&DEBUG_PACKETFORMATS) fprintf(stderr,"requestItem() failed at line %d\n",__LINE__);
return -1; return -1;
} }
if (packetSetSid(packet,8000,&packet_len,sid)) { if (packetSetSid(packet,8000,&packet_len,sid)) {
if (debug) fprintf(stderr,"requestItem() failed at line %d\n",__LINE__); if (debug&DEBUG_PACKETFORMATS) fprintf(stderr,"requestItem() failed at line %d\n",__LINE__);
return setReason("SID went mouldy during multi-packet get"); return setReason("SID went mouldy during multi-packet get");
} }
} }
@ -735,7 +738,7 @@ int requestItem(char *did,char *sid,char *item,int instance,unsigned char *buffe
if (max_bytes>buffer_length) max_bytes=buffer_length; if (max_bytes>buffer_length) max_bytes=buffer_length;
if (packetAddVariableRequest(packet,8000,&packet_len, if (packetAddVariableRequest(packet,8000,&packet_len,
item,r->var_instance,offset,max_bytes)) { item,r->var_instance,offset,max_bytes)) {
if (debug) fprintf(stderr,"requestItem() failed at line %d\n",__LINE__); if (debug&DEBUG_DNAREQUESTS) fprintf(stderr,"requestItem() failed at line %d\n",__LINE__);
return -1; return -1;
} }
} }
@ -743,7 +746,7 @@ int requestItem(char *did,char *sid,char *item,int instance,unsigned char *buffe
if (packet_len) if (packet_len)
{ {
if (packetFinalise(packet,8000,&packet_len,CRYPT_SIGNED|CRYPT_CIPHERED)) { if (packetFinalise(packet,8000,&packet_len,CRYPT_SIGNED|CRYPT_CIPHERED)) {
if (debug) fprintf(stderr,"requestItem() failed at line %d\n",__LINE__); if (debug&DEBUG_PACKETFORMATS) fprintf(stderr,"requestItem() failed at line %d\n",__LINE__);
return -1; return -1;
} }
packetSendFollowup(r->sender,packet,packet_len); packetSendFollowup(r->sender,packet,packet_len);
@ -763,8 +766,8 @@ int requestItem(char *did,char *sid,char *item,int instance,unsigned char *buffe
int piece=rr->value_offset/MAX_DATA_BYTES; int piece=rr->value_offset/MAX_DATA_BYTES;
if (!recv_map[piece]) if (!recv_map[piece])
{ {
if (debug>1) fprintf(stderr,"Extracted value fragment @ offset %d, with %d bytes\n",rr->value_offset,rr->value_bytes); if (debug&DEBUG_DNARESPONSES) fprintf(stderr,"Extracted value fragment @ offset %d, with %d bytes\n",rr->value_offset,rr->value_bytes);
if (debug>2) dump("Fragment",rr->response,rr->value_bytes); if (debug&DEBUG_DNARESPONSES) dump("Fragment",rr->response,rr->value_bytes);
fseek(outputfile,rr->value_offset,SEEK_SET); fseek(outputfile,rr->value_offset,SEEK_SET);
fwrite(rr->response,rr->value_bytes,1,outputfile); fwrite(rr->response,rr->value_bytes,1,outputfile);
if (buffer) bcopy(rr->response,&buffer[rr->value_offset],rr->value_bytes); if (buffer) bcopy(rr->response,&buffer[rr->value_offset],rr->value_bytes);
@ -772,7 +775,7 @@ int requestItem(char *did,char *sid,char *item,int instance,unsigned char *buffe
} }
else else
{ {
if (debug>1) fprintf(stderr,"DUPLICATE value fragment @ offset %d, with %d bytes\n",rr->value_offset,rr->value_bytes); if (debug&DEBUG_DNARESPONSES) fprintf(stderr,"DUPLICATE value fragment @ offset %d, with %d bytes\n",rr->value_offset,rr->value_bytes);
} }
} }
@ -787,7 +790,7 @@ int requestItem(char *did,char *sid,char *item,int instance,unsigned char *buffe
} }
if (outputtemplate) fclose(outputfile); else fflush(outputfile); if (outputtemplate) fclose(outputfile); else fflush(outputfile);
printf("\n"); printf("\n");
if (debug) fprintf(stderr,"requestItem() returned DATA\n"); if (debug&DEBUG_DNARESPONSES) fprintf(stderr,"requestItem() returned DATA\n");
if (!returnMultiVars) return 0; if (!returnMultiVars) return 0;
break; break;
} }
@ -809,6 +812,6 @@ int requestItem(char *did,char *sid,char *item,int instance,unsigned char *buffe
r=r->next; r=r->next;
} }
if (debug) fprintf(stderr,"requestItem() failed at line %d\n",__LINE__); if (debug&DEBUG_VERBOSE) fprintf(stderr,"requestItem() failed at line %d\n",__LINE__);
return -1; return -1;
} }

View File

@ -50,7 +50,7 @@ int stowDid(unsigned char *packet,int *ofs,char *did)
int nybl; int nybl;
int d=0; int d=0;
int len=0; int len=0;
if (debug>2) printf("Packing DID \"%s\"\n",did); if (debug&DEBUG_PACKETFORMATS) printf("Packing DID \"%s\"\n",did);
while(did[d]&&(d<DID_MAXSIZE)) while(did[d]&&(d<DID_MAXSIZE))
{ {
@ -106,7 +106,7 @@ int extractSid(unsigned char *packet,int *ofs,char *sid)
int stowSid(unsigned char *packet,int ofs,char *sid) int stowSid(unsigned char *packet,int ofs,char *sid)
{ {
int i; int i;
if (debug>2) printf("Stowing SID \"%s\"\n",sid); if (debug&DEBUG_PACKETFORMATS) printf("Stowing SID \"%s\"\n",sid);
if (strlen(sid)!=64) return setReason("Asked to stow invalid SID (should be 64 hex digits)"); if (strlen(sid)!=64) return setReason("Asked to stow invalid SID (should be 64 hex digits)");
for(i=0;i<SID_SIZE;i++) for(i=0;i<SID_SIZE;i++)
{ {
@ -127,7 +127,7 @@ int packetGetID(unsigned char *packet,int len,char *did,char *sid)
case 0: /* DID */ case 0: /* DID */
ofs++; ofs++;
if (extractDid(packet,&ofs,did)) return setReason("Could not decode DID"); if (extractDid(packet,&ofs,did)) return setReason("Could not decode DID");
if (debug>1) fprintf(stderr,"Decoded DID as %s\n",did); if (debug&DEBUG_PACKETFORMATS) fprintf(stderr,"Decoded DID as %s\n",did);
return 0; return 0;
break; break;
case 1: /* SID */ case 1: /* SID */
@ -165,7 +165,7 @@ int isFieldZeroP(unsigned char *packet,int start,int count)
mod&=0xff; mod&=0xff;
} }
if (debug>3) { if (debug&DEBUG_PACKETFORMATS) {
if (mod) fprintf(stderr,"Field [%d,%d) is non-zero (mod=0x%02x)\n",start,start+count,mod); if (mod) fprintf(stderr,"Field [%d,%d) is non-zero (mod=0x%02x)\n",start,start+count,mod);
else fprintf(stderr,"Field [%d,%d) is zero\n",start,start+count); else fprintf(stderr,"Field [%d,%d) is zero\n",start,start+count);
} }
@ -178,8 +178,9 @@ int safeZeroField(unsigned char *packet,int start,int count)
int mod=0; int mod=0;
int i; int i;
if (debug>3) fprintf(stderr,"Known plain-text counter-measure: safe-zeroing [%d,%d)\n", if (debug&DEBUG_PACKETFORMATS)
start,start+count); fprintf(stderr,"Known plain-text counter-measure: safe-zeroing [%d,%d)\n",
start,start+count);
for(i=start;i<(start+count-1);i++) for(i=start;i<(start+count-1);i++)
{ {

38
dna.c
View File

@ -220,26 +220,26 @@ int usage(char *complaint)
{ {
fprintf(stderr,"dna: %s\n",complaint); fprintf(stderr,"dna: %s\n",complaint);
fprintf(stderr,"usage:\n"); fprintf(stderr,"usage:\n");
fprintf(stderr," dna [-v ...] -S <hlr size in MB> [-f HLR backing file] [-I import.txt] [-N interface,...] [-G gateway specification] [-r rhizome path]\n"); fprintf(stderr," dna [-v <flags>] -S <hlr size in MB> [-f HLR backing file] [-I import.txt] [-N interface,...] [-G gateway specification] [-r rhizome path]\n");
fprintf(stderr,"or\n"); fprintf(stderr,"or\n");
fprintf(stderr," dna [-v ...] -f <HLR backing file> -E <hlr export file>\n"); fprintf(stderr," dna [-v <flags>] -f <HLR backing file> -E <hlr export file>\n");
fprintf(stderr,"or\n"); fprintf(stderr,"or\n");
fprintf(stderr," dna -r <rhizome path> -M <manifest name>\n"); fprintf(stderr," dna -r <rhizome path> -M <manifest name>\n");
fprintf(stderr,"or\n"); fprintf(stderr,"or\n");
fprintf(stderr," dna <-d|-s> id -A\n"); fprintf(stderr," dna <-d|-s> id -A\n");
fprintf(stderr,"or\n"); fprintf(stderr,"or\n");
fprintf(stderr," dna <-d|-s> id [-p pin] [-i variable instance] <-R variable[=value]>\n"); fprintf(stderr," dna <-d|-s> id [-p pin] [-i variable instance] <-R variable[=value]>\n");
fprintf(stderr," [-v ...] [-t request timeout in ms] [-O output file name template]\n"); fprintf(stderr," [-v <flags>] [-t request timeout in ms] [-O output file name template]\n");
fprintf(stderr,"or\n"); fprintf(stderr,"or\n");
fprintf(stderr," dna <-d|-s> id [-p pin] [-i variable instance] <-W|-U|-D variable[=[$|@]value]>\n"); fprintf(stderr," dna <-d|-s> id [-p pin] [-i variable instance] <-W|-U|-D variable[=[$|@]value]>\n");
fprintf(stderr," [-v ...] [-t request timeout in ms]\n"); fprintf(stderr," [-v <flags>] [-t request timeout in ms]\n");
fprintf(stderr,"or\n"); fprintf(stderr,"or\n");
fprintf(stderr," dna [-v ...] [-t timeout] -d did -C\n"); fprintf(stderr," dna [-v <flags>] [-t timeout] -d did -C\n");
fprintf(stderr,"or\n"); fprintf(stderr,"or\n");
fprintf(stderr," dna [-v ...] -f <hlr.dat> -E <export.txt>\n"); fprintf(stderr," dna [-v <flags>] -f <hlr.dat> -E <export.txt>\n");
fprintf(stderr,"\n"); fprintf(stderr,"\n");
fprintf(stderr," -v - increase verbosity.\n"); fprintf(stderr," -v - Set verbosity.\n");
fprintf(stderr," -E - Export specified HLR database into specified flat text file.\n"); fprintf(stderr," -E - Export specified HLR database into specified flat text file.\n");
fprintf(stderr," -I - Import a previously exported HLR database into this one.\n"); fprintf(stderr," -I - Import a previously exported HLR database into this one.\n");
fprintf(stderr," -A - Ask for address of subscriber.\n"); fprintf(stderr," -A - Ask for address of subscriber.\n");
@ -319,7 +319,7 @@ int main(int argc,char **argv)
srandomdev(); srandomdev();
while((c=getopt(argc,argv,"Ab:B:E:G:I:S:f:d:i:l:L:mnp:P:r:s:t:vR:W:U:D:CO:M:N:")) != -1 ) while((c=getopt(argc,argv,"Ab:B:E:G:I:S:f:d:i:l:L:mnp:P:r:s:t:v:R:W:U:D:CO:M:N:")) != -1 )
{ {
switch(c) switch(c)
{ {
@ -420,8 +420,26 @@ int main(int argc,char **argv)
case 't': /* request timeout (ms) */ case 't': /* request timeout (ms) */
timeout=atoi(optarg); timeout=atoi(optarg);
break; break;
case 'v': /* Increase verbosity */ case 'v': /* set verbosity */
debug++; debug=strtoll(optarg,NULL,10);
if (strstr(optarg,"interfaces")) debug|=DEBUG_OVERLAYINTERFACES;
if (strstr(optarg,"packetxfer")) debug|=DEBUG_PACKETXFER;
if (strstr(optarg,"verbose")) debug|=DEBUG_VERBOSE;
if (strstr(optarg,"verbio")) debug|=DEBUG_VERBOSE_IO;
if (strstr(optarg,"peers")) debug|=DEBUG_PEERS;
if (strstr(optarg,"dnaresponses")) debug|=DEBUG_DNARESPONSES;
if (strstr(optarg,"dnarequests")) debug|=DEBUG_DNAREQUESTS;
if (strstr(optarg,"simulation")) debug|=DEBUG_SIMULATION;
if (strstr(optarg,"dnavars")) debug|=DEBUG_DNAVARS;
if (strstr(optarg,"packetformats")) debug|=DEBUG_PACKETFORMATS;
if (strstr(optarg,"gateway")) debug|=DEBUG_GATEWAY;
if (strstr(optarg,"hlr")) debug|=DEBUG_HLR;
if (strstr(optarg,"sockio")) debug|=DEBUG_IO;
if (strstr(optarg,"frames")) debug|=DEBUG_OVERLAYFRAMES;
if (strstr(optarg,"abbreviations")) debug|=DEBUG_OVERLAYABBREVIATIONS;
if (strstr(optarg,"routing")) debug|=DEBUG_OVERLAYROUTING;
if (strstr(optarg,"security")) debug|=DEBUG_SECURITY;
if (strstr(optarg,"rhizome")) debug|=DEBUG_RHIZOME;
break; break;
case 'A': /* get address (IP or otherwise) of a given peer */ case 'A': /* get address (IP or otherwise) of a given peer */
peerAddress(did,sid,3 /* 1 = print list of addresses to stdout, 2 = set peer list to responders */); peerAddress(did,sid,3 /* 1 = print list of addresses to stdout, 2 = set peer list to responders */);

View File

@ -90,14 +90,14 @@ int runCommand(char *cmd)
{ {
FILE *f=fopen(cmd_file,"w"); FILE *f=fopen(cmd_file,"w");
if (!f) { if (!f) {
if (debug) fprintf(stderr,"%s:%d: Could not write to command file '%s'.\n",__FUNCTION__,__LINE__,cmd_file); if (debug&DEBUG_GATEWAY) fprintf(stderr,"%s:%d: Could not write to command file '%s'.\n",__FUNCTION__,__LINE__,cmd_file);
return 0; return 0;
} }
fprintf(f,"#!%s\n%s\n",shell,cmd); fprintf(f,"#!%s\n%s\n",shell,cmd);
fclose(f); fclose(f);
if (chmod(cmd_file,0000700)) if (chmod(cmd_file,0000700))
{ {
if (debug) fprintf(stderr,"%s:%d: Could not chmod command file '%s'.\n",__FUNCTION__,__LINE__,cmd_file); if (debug&DEBUG_GATEWAY) fprintf(stderr,"%s:%d: Could not chmod command file '%s'.\n",__FUNCTION__,__LINE__,cmd_file);
return 0; return 0;
} }
return safeSystem(cmd_file); return safeSystem(cmd_file);
@ -165,11 +165,11 @@ int asteriskCreateExtension(char *requestor_sid,char *did,char *uri_out)
if (extensions[index].uriprefixlen<0) { if (extensions[index].uriprefixlen<0) {
/* Whoops - something wrong with the extension/uri, so kill the record and fail. */ /* Whoops - something wrong with the extension/uri, so kill the record and fail. */
extensions[index].expires=1; extensions[index].expires=1;
if (debug) fprintf(stderr,"%s:%d: Generated extension appears to be malformed.\n",__FUNCTION__,__LINE__); if (debug&DEBUG_GATEWAY) fprintf(stderr,"%s:%d: Generated extension appears to be malformed.\n",__FUNCTION__,__LINE__);
return -1; return -1;
} }
if (debug) fprintf(stderr,"Created extension '%s' to dial %s\n",extensions[index].uri,did); if (debug&DEBUG_GATEWAY) fprintf(stderr,"Created extension '%s' to dial %s\n",extensions[index].uri,did);
strcpy(uri_out,extensions[index].uri); strcpy(uri_out,extensions[index].uri);
return 0; return 0;
@ -183,7 +183,7 @@ int asteriskWriteExtensions()
out=fopen(asterisk_extensions_conf,"w"); out=fopen(asterisk_extensions_conf,"w");
if (!out) { if (!out) {
if (debug) fprintf(stderr,"%s:%d: Could not write extensions file '%s'.\n",__FUNCTION__,__LINE__,asterisk_extensions_conf); if (debug&DEBUG_GATEWAY) fprintf(stderr,"%s:%d: Could not write extensions file '%s'.\n",__FUNCTION__,__LINE__,asterisk_extensions_conf);
return -1; return -1;
} }
@ -219,10 +219,10 @@ int asteriskReloadExtensions()
snprintf(cmd,8192,"%s -rx 'dialplan reload'",asterisk_binary); snprintf(cmd,8192,"%s -rx 'dialplan reload'",asterisk_binary);
if (runCommand(cmd)) if (runCommand(cmd))
{ {
if (debug) fprintf(stderr,"%s:%d: Dialplan reload failed.\n",__FUNCTION__,__LINE__); if (debug&DEBUG_GATEWAY) fprintf(stderr,"%s:%d: Dialplan reload failed.\n",__FUNCTION__,__LINE__);
return -1; return -1;
} }
if (debug) fprintf(stderr,"%s:%d: Dialplan reload appeared to succeed.\n",__FUNCTION__,__LINE__); if (debug&DEBUG_GATEWAY) fprintf(stderr,"%s:%d: Dialplan reload appeared to succeed.\n",__FUNCTION__,__LINE__);
return 0; return 0;
} }
@ -248,12 +248,12 @@ int asteriskGatewayUpP()
snprintf(cmd,8192,"%s -rx 'sip show registry' > %s",asterisk_binary,temp_file); snprintf(cmd,8192,"%s -rx 'sip show registry' > %s",asterisk_binary,temp_file);
if (runCommand(cmd)) { if (runCommand(cmd)) {
if (debug) { fprintf(stderr,"%s:%d: system(%s) might have failed.\n",__FUNCTION__,__LINE__,cmd_file); if (debug&DEBUG_GATEWAY) { fprintf(stderr,"%s:%d: system(%s) might have failed.\n",__FUNCTION__,__LINE__,cmd_file);
perror("system"); } perror("system"); }
} }
FILE *f=fopen(temp_file,"r"); FILE *f=fopen(temp_file,"r");
if (!f) { if (!f) {
if (debug) fprintf(stderr,"%s:%d: Could not read result of \"sip show registry\" from '%s'.\n",__FUNCTION__,__LINE__,temp_file); if (debug&DEBUG_GATEWAY) fprintf(stderr,"%s:%d: Could not read result of \"sip show registry\" from '%s'.\n",__FUNCTION__,__LINE__,temp_file);
return 0; return 0;
} }
@ -294,22 +294,22 @@ int asteriskObtainGateway(char *requestor_sid,char *did,char *uri_out)
*/ */
if (!asteriskGatewayUpP()) if (!asteriskGatewayUpP())
{ if (debug) fprintf(stderr,"Asterisk gatway is not up, so not offering gateway.\n"); return -1; } { if (debug&DEBUG_GATEWAY) fprintf(stderr,"Asterisk gatway is not up, so not offering gateway.\n"); return -1; }
if (asteriskCreateExtension(requestor_sid,did,uri_out)) if (asteriskCreateExtension(requestor_sid,did,uri_out))
{ {
if (debug) fprintf(stderr,"asteriskCreateExtension() failed, so not offering gateway.\n"); if (debug&DEBUG_GATEWAY) fprintf(stderr,"asteriskCreateExtension() failed, so not offering gateway.\n");
return -1; return -1;
} }
if (asteriskWriteExtensions()) if (asteriskWriteExtensions())
{ {
if (debug) fprintf(stderr,"asteriskWriteExtensions() failed, so not offering gateway.\n"); if (debug&DEBUG_GATEWAY) fprintf(stderr,"asteriskWriteExtensions() failed, so not offering gateway.\n");
return -1; return -1;
} }
if (asteriskReloadExtensions()) if (asteriskReloadExtensions())
{ {
if (debug) fprintf(stderr,"asteriskReloadExtensions() failed, so not offering gateway.\n"); if (debug&DEBUG_GATEWAY) fprintf(stderr,"asteriskReloadExtensions() failed, so not offering gateway.\n");
return -1; return -1;
} }
if (debug) fprintf(stderr,"asteriskReloadExtensions() suceeded, offering gateway.\n"); if (debug&DEBUG_GATEWAY) fprintf(stderr,"asteriskReloadExtensions() suceeded, offering gateway.\n");
return 0; return 0;
} }

View File

@ -93,14 +93,14 @@ int findHlr(unsigned char *hlr,int *ofs,char *sid,char *did)
if ((*ofs)>=hlr_size) return 0; if ((*ofs)>=hlr_size) return 0;
if (debug>4) fprintf(stderr,"Searching for HLR record sid=[%s]/did=[%s]\n",sid?sid:"NULL",did?did:"NULL"); if (debug&DEBUG_HLR) fprintf(stderr,"Searching for HLR record sid=[%s]/did=[%s]\n",sid?sid:"NULL",did?did:"NULL");
if (did&&did[0]) { if (did&&did[0]) {
/* Make packed version of DID so that we can compare faster with the DIDs in the HLR */ /* Make packed version of DID so that we can compare faster with the DIDs in the HLR */
if (stowDid(packed_id,&pid_len,did)) return setReason("DID appears to be invalid"); if (stowDid(packed_id,&pid_len,did)) return setReason("DID appears to be invalid");
/* Find significant length of packed DID */ /* Find significant length of packed DID */
for(pid_len=0;pid_len<DID_MAXSIZE;pid_len++) if ((packed_id[pid_len]&0x0f)==0x0f) { pid_len++; break; } for(pid_len=0;pid_len<DID_MAXSIZE;pid_len++) if ((packed_id[pid_len]&0x0f)==0x0f) { pid_len++; break; }
if (debug>1) dump("Searching for DID records that match",packed_id,pid_len); if (debug&DEBUG_HLR) dump("Searching for DID records that match",packed_id,pid_len);
} }
if (sid&&sid[0]) { if (sid&&sid[0]) {
@ -119,14 +119,14 @@ int findHlr(unsigned char *hlr,int *ofs,char *sid,char *did)
if (!record_length) return 0; if (!record_length) return 0;
if (debug>4) fprintf(stderr,"Considering HLR entry @ 0x%x\n",*ofs); if (debug&DEBUG_HLR) fprintf(stderr,"Considering HLR entry @ 0x%x\n",*ofs);
records_searched++; records_searched++;
if (sid&&sid[0]) { if (sid&&sid[0]) {
/* Lookup by SID, so just see if it matches */ /* Lookup by SID, so just see if it matches */
if (!bcompare(packed_id,&hlr[(*ofs)+4],SID_SIZE)) { if (!bcompare(packed_id,&hlr[(*ofs)+4],SID_SIZE)) {
if (debug>1) fprintf(stderr,"Found requested SID at address 0x%x.\n",*ofs); if (debug&DEBUG_HLR) fprintf(stderr,"Found requested SID at address 0x%x.\n",*ofs);
match=1; match=1;
} }
} }
@ -137,22 +137,22 @@ int findHlr(unsigned char *hlr,int *ofs,char *sid,char *did)
while(h) while(h)
{ {
/* Search through variables for matching DIDs */ /* Search through variables for matching DIDs */
if (debug>2) { if (debug&DEBUG_HLR) {
fprintf(stderr,"Considering variable 0x%02x, instance %d.\n", fprintf(stderr,"Considering variable 0x%02x, instance %d.\n",
h->var_id,h->var_instance); h->var_id,h->var_instance);
dump("variable value",h->value,h->value_len); dump("variable value",h->value,h->value_len);
} }
if (h->var_id==VAR_DIDS) { /* DID entry */ if (h->var_id==VAR_DIDS) { /* DID entry */
if (debug>2) fprintf(stderr,"Checking DID against record DID\n"); if (debug&DEBUG_HLR) fprintf(stderr,"Checking DID against record DID\n");
if (!bcompare(packed_id,h->value,pid_len)) { if (!bcompare(packed_id,h->value,pid_len)) {
if (debug>1) fprintf(stderr,"Found matching DID in HLR record #%d\n",records_searched); if (debug&DEBUG_HLR) fprintf(stderr,"Found matching DID in HLR record #%d\n",records_searched);
match=1; match=1;
break; break;
} }
} }
else else
{ {
if (debug>2) fprintf(stderr,"Skipping non-DID variable while searching for DID.\n"); if (debug&DEBUG_HLR) fprintf(stderr,"Skipping non-DID variable while searching for DID.\n");
} }
h=hlrentrygetent(h); h=hlrentrygetent(h);
} }
@ -162,7 +162,7 @@ int findHlr(unsigned char *hlr,int *ofs,char *sid,char *did)
/* For each match ... */ /* For each match ... */
if (match) if (match)
{ {
if (debug>4) fprintf(stderr,"Returning HLR entry @ 0x%x\n",*ofs); if (debug&DEBUG_HLR) fprintf(stderr,"Returning HLR entry @ 0x%x\n",*ofs);
return 1; return 1;
} }
@ -179,20 +179,20 @@ int createHlr(char *did,char *sid) {
int i; int i;
int record_offset=0; int record_offset=0;
if (debug) fprintf(stderr,"Asked to create a new HLR record\n"); if (debug&DEBUG_HLR) fprintf(stderr,"Asked to create a new HLR record\n");
/* Generate random SID */ /* Generate random SID */
for(i=1;i<64;i++) sid[i]=hexdigit[random()&0xf]; sid[64]=0; for(i=1;i<64;i++) sid[i]=hexdigit[random()&0xf]; sid[64]=0;
/* But make sure first digit is non-zero as required by the overlay mesh */ /* But make sure first digit is non-zero as required by the overlay mesh */
sid[0]=hexdigit[1+(random()&0xe)]; sid[0]=hexdigit[1+(random()&0xe)];
if (debug>1) fprintf(stderr,"Creating new HLR entry with sid %s\n",sid); if (debug&DEBUG_HLR) fprintf(stderr,"Creating new HLR entry with sid %s\n",sid);
/* Find first free byte of HLR. /* Find first free byte of HLR.
Keep calling findHlr() until we find the end. */ Keep calling findHlr() until we find the end. */
while((i=hlrGetRecordLength(hlr,record_offset))>0) while((i=hlrGetRecordLength(hlr,record_offset))>0)
{ {
record_offset+=i; record_offset+=i;
if (debug>1) fprintf(stderr,"Skipping %d bytes to 0x%x\n",i,record_offset); if (debug&DEBUG_HLR) fprintf(stderr,"Skipping %d bytes to 0x%x\n",i,record_offset);
} }
if (i<0) return setReason("Corrupt HLR: Negative length field encountered."); if (i<0) return setReason("Corrupt HLR: Negative length field encountered.");
@ -207,7 +207,7 @@ int createHlr(char *did,char *sid) {
int bytes=hlr_size-record_offset; int bytes=hlr_size-record_offset;
if (bytes<1024) return setReason("<1KB space in HLR"); if (bytes<1024) return setReason("<1KB space in HLR");
if (debug>2) fprintf(stderr,"Creating new HLR entry @ 0x%x\n",record_offset); if (debug&DEBUG_HLR) fprintf(stderr,"Creating new HLR entry @ 0x%x\n",record_offset);
/* Write shiny fresh new record. /* Write shiny fresh new record.
32bit - record length 32bit - record length
@ -232,9 +232,9 @@ int createHlr(char *did,char *sid) {
hlrSetVariable(hlr,record_offset,VAR_DIDS,0x00,packeddid,pdidlen); hlrSetVariable(hlr,record_offset,VAR_DIDS,0x00,packeddid,pdidlen);
} }
if (debug) fprintf(stderr,"Created new 36 byte HLR record for DID=[%s] @ 0x%x with SID=[%s]\n", if (debug&DEBUG_HLR) fprintf(stderr,"Created new 36 byte HLR record for DID=[%s] @ 0x%x with SID=[%s]\n",
did,record_offset,sid); did,record_offset,sid);
if (debug>2) dump("after HLR create",&hlr[0],256); if (debug&DEBUG_HLR) dump("after HLR create",&hlr[0],256);
return 0; return 0;
} }
@ -251,11 +251,11 @@ int hlrGetRecordLength(unsigned char *hlr,int hofs)
record_length|=hlr[hofs+1]<<16; record_length|=hlr[hofs+1]<<16;
record_length|=hlr[hofs+0]<<24; record_length|=hlr[hofs+0]<<24;
if (debug>2) fprintf(stderr,"HLR record @ 0x%x is %d bytes long.\n",hofs,record_length); if (debug&DEBUG_HLR) fprintf(stderr,"HLR record @ 0x%x is %d bytes long.\n",hofs,record_length);
if (record_length<0) { if (record_length<0) {
// fix corrupt entries // fix corrupt entries
if (debug>2) fprintf(stderr,"HLR record @ 0x%x ZEROED.\n",hofs); if (debug&DEBUG_HLR) fprintf(stderr,"HLR record @ 0x%x ZEROED.\n",hofs);
hlr[hofs+3]=0; hlr[hofs+3]=0;
hlr[hofs+2]=0; hlr[hofs+2]=0;
hlr[hofs+1]=0; hlr[hofs+1]=0;
@ -288,7 +288,7 @@ struct hlrentry_handle *openhlrentry(unsigned char *hlr,int hofs)
/* If record has zero length, then open fails */ /* If record has zero length, then open fails */
if (record_length<1) if (record_length<1)
{ {
if (debug>2) fprintf(stderr,"HLR record is zero length -- aborting.\n"); if (debug&DEBUG_HLR) fprintf(stderr,"HLR record is zero length -- aborting.\n");
return NULL; return NULL;
} }
@ -316,25 +316,25 @@ struct hlrentry_handle *hlrentrygetent(struct hlrentry_handle *h)
if (h->entry_offset==0) if (h->entry_offset==0)
{ {
/* First entry */ /* First entry */
if (debug>2) fprintf(stderr,"Considering first entry of HLR record.\n"); if (debug&DEBUG_HLR) fprintf(stderr,"Considering first entry of HLR record.\n");
h->entry_offset=HLR_RECORD_LEN_SIZE+SID_SIZE; h->entry_offset=HLR_RECORD_LEN_SIZE+SID_SIZE;
} }
else else
{ {
/* subsequent entry */ /* subsequent entry */
if (debug>2) fprintf(stderr,"Considering entry @ 0x%x\n",h->entry_offset); if (debug&DEBUG_HLR) fprintf(stderr,"Considering entry @ 0x%x\n",h->entry_offset);
h->entry_offset+=1+2+h->value_len+(h->var_id&0x80?1:0); h->entry_offset+=1+2+h->value_len+(h->var_id&0x80?1:0);
} }
/* XXX Check if end of record */ /* XXX Check if end of record */
if (h->entry_offset>=h->record_length) { if (h->entry_offset>=h->record_length) {
if (debug>2) fprintf(stderr,"Reached end of HLR record (%d>=%d).\n",h->entry_offset,h->record_length); if (debug&DEBUG_HLR) fprintf(stderr,"Reached end of HLR record (%d>=%d).\n",h->entry_offset,h->record_length);
return NULL; return NULL;
} }
/* XXX Extract variable */ /* XXX Extract variable */
ptr=h->hlr_offset+h->entry_offset; ptr=h->hlr_offset+h->entry_offset;
if (debug>2) fprintf(stderr,"Extracting HLR variable @ 0x%x\n",ptr); if (debug&DEBUG_HLR) fprintf(stderr,"Extracting HLR variable @ 0x%x\n",ptr);
h->var_id=hlr[ptr]; h->var_id=hlr[ptr];
h->value_len=(hlr[ptr+1]<<8)+hlr[ptr+2]; h->value_len=(hlr[ptr+1]<<8)+hlr[ptr+2];
ptr+=3; ptr+=3;
@ -384,7 +384,7 @@ int hlrSetVariable(unsigned char *hlr,int hofs,int varid,int varinstance,
int hlr_offset=-1; int hlr_offset=-1;
int hlr_size=hlrGetRecordLength(hlr,hofs); int hlr_size=hlrGetRecordLength(hlr,hofs);
if (debug) fprintf(stderr,"hlrSetVariable(varid=%02x, instance=%02x, len=%d)\n", if (debug&DEBUG_HLR) fprintf(stderr,"hlrSetVariable(varid=%02x, instance=%02x, len=%d)\n",
varid,varinstance,len); varid,varinstance,len);
h=openhlrentry(hlr,hofs); h=openhlrentry(hlr,hofs);
@ -392,18 +392,18 @@ int hlrSetVariable(unsigned char *hlr,int hofs,int varid,int varinstance,
/* Find the place in the HLR record where this variable should go */ /* Find the place in the HLR record where this variable should go */
while(h) while(h)
{ {
if (debug>1) fprintf(stderr,"h->var_id=%02x, h->h->var_instance=%02x, h->entry_offset=%x\n", if (debug&DEBUG_HLR) fprintf(stderr,"h->var_id=%02x, h->h->var_instance=%02x, h->entry_offset=%x\n",
h->var_id,h->var_instance,h->entry_offset); h->var_id,h->var_instance,h->entry_offset);
if ((h->var_id<varid) if ((h->var_id<varid)
||((h->var_id&0x80)&&(h->var_id==varid&&h->var_instance<varinstance))) ||((h->var_id&0x80)&&(h->var_id==varid&&h->var_instance<varinstance)))
{ {
hlr_offset=h->entry_offset; hlr_offset=h->entry_offset;
if (debug>1) fprintf(stderr,"Found variable instance prior: hlr_offset=%d.\n",hlr_offset); if (debug&DEBUG_HLR) fprintf(stderr,"Found variable instance prior: hlr_offset=%d.\n",hlr_offset);
} }
else else
{ {
/* Value goes here */ /* Value goes here */
if (debug>1) fprintf(stderr,"Found variable instance to overwrite: hlr_offset=%d.\n",hlr_offset); if (debug&DEBUG_HLR) fprintf(stderr,"Found variable instance to overwrite: hlr_offset=%d.\n",hlr_offset);
hlr_offset=h->entry_offset; hlr_offset=h->entry_offset;
break; break;
} }
@ -415,19 +415,19 @@ int hlrSetVariable(unsigned char *hlr,int hofs,int varid,int varinstance,
if (h&&hlr_offset>-1) if (h&&hlr_offset>-1)
{ {
if (debug>2) printf("hlr_offset=%d\n",hlr_offset); if (debug&DEBUG_HLR) printf("hlr_offset=%d\n",hlr_offset);
if (h&&h->var_id==varid&&((h->var_instance==varinstance)||(!(h->var_id&0x80)))) if (h&&h->var_id==varid&&((h->var_instance==varinstance)||(!(h->var_id&0x80))))
{ {
int existing_size; int existing_size;
/* Replace existing value */ /* Replace existing value */
if (debug) fprintf(stderr,"Replacing value in HLR:\n"); if (debug&DEBUG_HLR) fprintf(stderr,"Replacing value in HLR:\n");
existing_size=1+2+((h->var_id&0x80)?1:0)+h->value_len; existing_size=1+2+((h->var_id&0x80)?1:0)+h->value_len;
hlrMakeSpace(hlr,hofs,hlr_offset,1+2+len+((varid&0x80)?1:0)-existing_size); hlrMakeSpace(hlr,hofs,hlr_offset,1+2+len+((varid&0x80)?1:0)-existing_size);
} }
else else
{ {
/* Insert value here */ /* Insert value here */
if (debug) fprintf(stderr,"Inserting value in HLR\n"); if (debug&DEBUG_HLR) fprintf(stderr,"Inserting value in HLR\n");
hlrMakeSpace(hlr,hofs,hlr_offset,1+2+len+((varid&0x80)?1:0)); hlrMakeSpace(hlr,hofs,hlr_offset,1+2+len+((varid&0x80)?1:0));
} }
} }
@ -435,7 +435,7 @@ int hlrSetVariable(unsigned char *hlr,int hofs,int varid,int varinstance,
{ {
/* HLR record has no entries, or this entry needs to go at the end, /* HLR record has no entries, or this entry needs to go at the end,
so insert value at end of the record */ so insert value at end of the record */
if (debug) fprintf(stderr,"Inserting value at end of HLR @ 0x%x\n",hlr_size); if (debug&DEBUG_HLR) fprintf(stderr,"Inserting value at end of HLR @ 0x%x\n",hlr_size);
hlrMakeSpace(hlr,hofs,hlr_size,1+2+len+((varid&0x80)?1:0)); hlrMakeSpace(hlr,hofs,hlr_size,1+2+len+((varid&0x80)?1:0));
hlr_offset=hlr_size; hlr_offset=hlr_size;
} }
@ -468,7 +468,7 @@ int hlrMakeSpace(unsigned char *hlr,int hofs,int hlr_offset,int bytes)
/* Deal with easy case first */ /* Deal with easy case first */
if (!bytes) return 0; if (!bytes) return 0;
if (debug>2) { if (debug&DEBUG_HLR) {
fprintf(stderr,"hlrMakeSpace: Inserting %d bytes at offset %d with hofs=%d. shifted bytes=%d\n", fprintf(stderr,"hlrMakeSpace: Inserting %d bytes at offset %d with hofs=%d. shifted bytes=%d\n",
bytes,hlr_offset,hofs,shifted_bytes); bytes,hlr_offset,hofs,shifted_bytes);
fflush(stderr); fflush(stderr);
@ -484,7 +484,7 @@ int hlrMakeSpace(unsigned char *hlr,int hofs,int hlr_offset,int bytes)
length=hlrGetRecordLength(hlr,hofs); length=hlrGetRecordLength(hlr,hofs);
length+=bytes; length+=bytes;
hlrSetRecordLength(hlr,hofs,length); hlrSetRecordLength(hlr,hofs,length);
if (debug>1) fprintf(stderr,"hlrMakeSpace: HLR entry now %d bytes long.\n",length); if (debug&DEBUG_HLR) fprintf(stderr,"hlrMakeSpace: HLR entry now %d bytes long.\n",length);
return 0; return 0;
} }
@ -515,7 +515,7 @@ int openHlrFile(char *backing_file,int size)
/* transitory storage of HLR data, so just malloc() the memory */ /* transitory storage of HLR data, so just malloc() the memory */
hlr=calloc(size,1); hlr=calloc(size,1);
if (!hlr) exit(setReason("Failed to calloc() HLR database.")); if (!hlr) exit(setReason("Failed to calloc() HLR database."));
if (debug) fprintf(stderr,"Allocated %d byte temporary HLR store\n",size); if (debug&DEBUG_HLR) fprintf(stderr,"Allocated %d byte temporary HLR store\n",size);
} }
else else
{ {
@ -553,7 +553,7 @@ int openHlrFile(char *backing_file,int size)
perror("mmap"); perror("mmap");
exit(setReason("Memory mapping of HLR backing file failed.")); exit(setReason("Memory mapping of HLR backing file failed."));
} }
if (debug) fprintf(stderr,"Allocated %d byte HLR store backed by file `%s'\n", if (debug&DEBUG_HLR) fprintf(stderr,"Allocated %d byte HLR store backed by file `%s'\n",
size,backing_file); size,backing_file);
} }
hlr_size=size; hlr_size=size;

14
mphlr.h
View File

@ -878,5 +878,19 @@ int rhizome_server_poll();
#define DEBUG_PACKETXFER 1 #define DEBUG_PACKETXFER 1
#define DEBUG_VERBOSE 4 #define DEBUG_VERBOSE 4
#define DEBUG_VERBOSE_IO 8 #define DEBUG_VERBOSE_IO 8
#define DEBUG_PEERS 16
#define DEBUG_DNARESPONSES 32
#define DEBUG_DNAREQUESTS 64
#define DEBUG_SIMULATION 128
#define DEBUG_DNAVARS 256
#define DEBUG_PACKETFORMATS 512
#define DEBUG_GATEWAY 1024
#define DEBUG_HLR 2048
#define DEBUG_IO 4096
#define DEBUG_OVERLAYFRAMES 8192
#define DEBUG_OVERLAYABBREVIATIONS 16384
#define DEBUG_OVERLAYROUTING 32768
#define DEBUG_SECURITY 65536
#define DEBUG_RHIZOME 131072
int serval_packetvisualise(FILE *f,char *message,unsigned char *packet,int plen); int serval_packetvisualise(FILE *f,char *message,unsigned char *packet,int plen);

View File

@ -100,7 +100,7 @@ int overlayServerMode()
int ofs=0; int ofs=0;
while(findHlr(hlr,&ofs,NULL,NULL)) { while(findHlr(hlr,&ofs,NULL,NULL)) {
int i; int i;
if (debug) { if (debug&DEBUG_OVERLAYINTERFACES) {
fprintf(stderr,"Adding "); fprintf(stderr,"Adding ");
for(i=0;i<SID_SIZE;i++) fprintf(stderr,"%02x",hlr[ofs+4+i]); for(i=0;i<SID_SIZE;i++) fprintf(stderr,"%02x",hlr[ofs+4+i]);
fprintf(stderr," to list of local addresses.\n"); fprintf(stderr," to list of local addresses.\n");
@ -141,16 +141,16 @@ int overlayServerMode()
int r=select(maxfd+1,&read_fds,NULL,NULL,&waittime); int r=select(maxfd+1,&read_fds,NULL,NULL,&waittime);
if (r<0) { if (r<0) {
/* select had a problem */ /* select had a problem */
if (debug&4) perror("select()"); if (debug&DEBUG_IO) perror("select()");
WHY("select() complained."); WHY("select() complained.");
} else if (r>0) { } else if (r>0) {
/* We have data, so try to receive it */ /* We have data, so try to receive it */
if (debug&4) fprintf(stderr,"select() reports packets waiting\n"); if (debug&DEBUG_IO) fprintf(stderr,"select() reports packets waiting\n");
overlay_rx_messages(); overlay_rx_messages();
} else { } else {
/* No data before tick occurred, so do nothing. /* No data before tick occurred, so do nothing.
Well, for now let's just check anyway. */ Well, for now let's just check anyway. */
if (debug&DEBUG_VERBOSE_IO) fprintf(stderr,"select() timeout.\n"); if (debug&DEBUG_IO) fprintf(stderr,"select() timeout.\n");
overlay_rx_messages(); overlay_rx_messages();
} }
/* Check if we need to trigger any ticks on any interfaces */ /* Check if we need to trigger any ticks on any interfaces */
@ -169,7 +169,7 @@ int overlay_frame_process(int interface,overlay_frame *f)
if (overlay_address_is_local(f->source)) if (overlay_address_is_local(f->source))
return -1; /* WHY("Dropping frame claiming to come from myself."); */ return -1; /* WHY("Dropping frame claiming to come from myself."); */
if (debug>1) fprintf(stderr,">>> Received frame (type=%02x)\n",f->type); if (debug&DEBUG_OVERLAYFRAMES) fprintf(stderr,">>> Received frame (type=%02x)\n",f->type);
/* First order of business is whether the nexthop address has been resolved. /* First order of business is whether the nexthop address has been resolved.
If not, we need to think about asking for it to be resolved. If not, we need to think about asking for it to be resolved.
@ -221,7 +221,7 @@ int overlay_frame_process(int interface,overlay_frame *f)
/* It's for us, so resolve the addresses */ /* It's for us, so resolve the addresses */
if (overlay_frame_resolve_addresses(interface,f)) if (overlay_frame_resolve_addresses(interface,f))
return WHY("Failed to resolve destination and sender addresses in frame"); return WHY("Failed to resolve destination and sender addresses in frame");
if (debug&4) { if (debug&DEBUG_OVERLAYFRAMES) {
fprintf(stderr,"Destination for this frame is (resolve code=%d): ",f->destination_address_status); fprintf(stderr,"Destination for this frame is (resolve code=%d): ",f->destination_address_status);
if (f->destination_address_status==OA_RESOLVED) for(i=0;i<SID_SIZE;i++) fprintf(stderr,"%02x",f->destination[i]); else fprintf(stderr,"???"); if (f->destination_address_status==OA_RESOLVED) for(i=0;i<SID_SIZE;i++) fprintf(stderr,"%02x",f->destination[i]); else fprintf(stderr,"???");
fprintf(stderr,"\n"); fprintf(stderr,"\n");
@ -231,7 +231,7 @@ int overlay_frame_process(int interface,overlay_frame *f)
} }
if (f->source_address_status!=OA_RESOLVED) { if (f->source_address_status!=OA_RESOLVED) {
if (debug>1) WHY("Source address could not be resolved, so dropping frame."); if (debug&DEBUG_OVERLAYFRAMES) WHY("Source address could not be resolved, so dropping frame.");
return -1; return -1;
} }
@ -240,12 +240,12 @@ int overlay_frame_process(int interface,overlay_frame *f)
if (i==SID_SIZE) { ultimatelyForMe=1; broadcast=1; } if (i==SID_SIZE) { ultimatelyForMe=1; broadcast=1; }
if (overlay_address_is_local(f->destination)) ultimatelyForMe=1; if (overlay_address_is_local(f->destination)) ultimatelyForMe=1;
} else { } else {
if (debug>1) WHY("Destination address could not be resolved, so dropping frame."); if (debug&DEBUG_OVERLAYFRAMES) WHY("Destination address could not be resolved, so dropping frame.");
return -1; return -1;
} }
} }
if (debug>2) { if (debug&DEBUG_OVERLAYFRAMES) {
fprintf(stderr,"This frame does%s have me listed as next hop.\n",forMe?"":" not"); fprintf(stderr,"This frame does%s have me listed as next hop.\n",forMe?"":" not");
fprintf(stderr,"This frame is%s for me.\n",ultimatelyForMe?"":" not"); fprintf(stderr,"This frame is%s for me.\n",ultimatelyForMe?"":" not");
fprintf(stderr,"This frame is%s broadcast.\n",broadcast?"":" not"); fprintf(stderr,"This frame is%s broadcast.\n",broadcast?"":" not");
@ -270,7 +270,7 @@ int overlay_frame_process(int interface,overlay_frame *f)
// Similarly, rhizome advertisement traffic is always link local, so don't // Similarly, rhizome advertisement traffic is always link local, so don't
// forward that either. // forward that either.
} else { } else {
if (debug>2) fprintf(stderr,"\nForwarding frame.\n"); if (debug&DEBUG_OVERLAYFRAMES) fprintf(stderr,"\nForwarding frame.\n");
if (overlay_get_nexthop(f->destination,f->nexthop,&len,&f->nexthop_interface)) if (overlay_get_nexthop(f->destination,f->nexthop,&len,&f->nexthop_interface))
return WHY("Could not find next hop for host - dropping frame"); return WHY("Could not find next hop for host - dropping frame");
f->ttl--; f->ttl--;

View File

@ -179,7 +179,7 @@ int overlay_abbreviate_cache_address(unsigned char *sid)
/* Not yet in cache, so store it */ /* Not yet in cache, so store it */
bcopy(sid,&cache->sids[index].b[0],SID_SIZE); bcopy(sid,&cache->sids[index].b[0],SID_SIZE);
if (debug&4) { if (debug&DEBUG_OVERLAYABBREVIATIONS) {
fprintf(stderr,"Cached address "); fprintf(stderr,"Cached address ");
int i; int i;
for(i=0;i<SID_SIZE;i++) fprintf(stderr,"%02x",cache->sids[index].b[i]); for(i=0;i<SID_SIZE;i++) fprintf(stderr,"%02x",cache->sids[index].b[i]);
@ -311,7 +311,7 @@ int overlay_abbreviate_address(unsigned char *in,unsigned char *out,int *ofs)
int overlay_abbreviate_expand_address(int interface,unsigned char *in,int *inofs,unsigned char *out,int *ofs) int overlay_abbreviate_expand_address(int interface,unsigned char *in,int *inofs,unsigned char *out,int *ofs)
{ {
int bytes=0,r; int bytes=0,r;
if (debug>3) fprintf(stderr,"Address first byte/abbreviation code=%02x (input offset=%d)\n",in[*inofs],*inofs); if (debug&DEBUG_OVERLAYABBREVIATIONS) fprintf(stderr,"Address first byte/abbreviation code=%02x (input offset=%d)\n",in[*inofs],*inofs);
switch(in[*inofs]) switch(in[*inofs])
{ {
case OA_CODE_02: case OA_CODE_04: case OA_CODE_0C: case OA_CODE_02: case OA_CODE_04: case OA_CODE_0C:
@ -424,7 +424,7 @@ int overlay_abbreviate_cache_lookup(unsigned char *in,unsigned char *out,int *of
int index=((in[0]<<16)|(in[0]<<8)|in[2])>>cache->shift; int index=((in[0]<<16)|(in[0]<<8)|in[2])>>cache->shift;
int i; int i;
if (debug>3) { if (debug&DEBUG_OVERLAYABBREVIATIONS) {
fprintf(stderr,"Looking in cache slot #%d for: ",index); fprintf(stderr,"Looking in cache slot #%d for: ",index);
for(i=0;i<prefix_bytes;i++) fprintf(stderr,"%02x",in[i]); for(i=0;i<prefix_bytes;i++) fprintf(stderr,"%02x",in[i]);
fprintf(stderr,"*\n"); fprintf(stderr,"*\n");
@ -442,7 +442,7 @@ int overlay_abbreviate_cache_lookup(unsigned char *in,unsigned char *out,int *of
colliding prefixes and ask the sender to resolve them for us, or better yet dynamically colliding prefixes and ask the sender to resolve them for us, or better yet dynamically
size the prefix length based on whether any given short prefix has collided */ size the prefix length based on whether any given short prefix has collided */
if (debug>3) { if (debug&DEBUG_OVERLAYABBREVIATIONS) {
/* It is here, so let's return it */ /* It is here, so let's return it */
fprintf(stderr,"I think I looked up the following: "); fprintf(stderr,"I think I looked up the following: ");
for(i=0;i<SID_SIZE;i++) fprintf(stderr,"%02x",cache->sids[index].b[i]); for(i=0;i<SID_SIZE;i++) fprintf(stderr,"%02x",cache->sids[index].b[i]);
@ -474,7 +474,7 @@ int overlay_abbreviate_set_current_sender(unsigned char *in)
int overlay_abbreviate_set_most_recent_address(unsigned char *in) int overlay_abbreviate_set_most_recent_address(unsigned char *in)
{ {
bcopy(in,&overlay_abbreviate_previous_address.b[0],SID_SIZE); bcopy(in,&overlay_abbreviate_previous_address.b[0],SID_SIZE);
if (debug>3) fprintf(stderr,"Most recent address=%s\n", if (debug&DEBUG_OVERLAYABBREVIATIONS) fprintf(stderr,"Most recent address=%s\n",
overlay_render_sid(in)); overlay_render_sid(in));
return 0; return 0;
} }

View File

@ -194,12 +194,12 @@ int overlay_interface_init_socket(int interface,struct sockaddr_in src_addr,stru
/* XXX Is this right? Are we really setting the local side address? /* XXX Is this right? Are we really setting the local side address?
I was in a plane when at the time, so couldn't Google it. I was in a plane when at the time, so couldn't Google it.
*/ */
if (debug&4) fprintf(stderr,"src_addr=%08x\n",(unsigned int)src_addr.sin_addr.s_addr); if (debug&DEBUG_PACKETXFER) fprintf(stderr,"src_addr=%08x\n",(unsigned int)src_addr.sin_addr.s_addr);
if(bind(I(fd),(struct sockaddr *)&src_addr,sizeof(src_addr))) { if(bind(I(fd),(struct sockaddr *)&src_addr,sizeof(src_addr))) {
perror("bind()"); perror("bind()");
return WHY("MP HLR server could not bind to requested UDP port (bind() failed)"); return WHY("MP HLR server could not bind to requested UDP port (bind() failed)");
} }
if (debug&4) fprintf(stderr,"Bound to port 0x%04x\n",src_addr.sin_port); if (debug&(DEBUG_PACKETXFER|DEBUG_IO)) fprintf(stderr,"Bound to port 0x%04x\n",src_addr.sin_port);
int broadcastP=1; int broadcastP=1;
if(setsockopt(I(fd), SOL_SOCKET, SO_BROADCAST, &broadcastP, sizeof(broadcastP)) < 0) { if(setsockopt(I(fd), SOL_SOCKET, SO_BROADCAST, &broadcastP, sizeof(broadcastP)) < 0) {
@ -303,9 +303,10 @@ int overlay_rx_messages()
plen=2048-128; plen=2048-128;
plen=packet[110]+(packet[111]<<8); plen=packet[110]+(packet[111]<<8);
if (plen>(2048-128)) plen=-1; if (plen>(2048-128)) plen=-1;
if (debug) serval_packetvisualise(stderr, if (debug&DEBUG_PACKETXFER)
"Read from dummy interface", serval_packetvisualise(stderr,
&packet[128],plen); "Read from dummy interface",
&packet[128],plen);
bzero(&transaction_id[0],8); bzero(&transaction_id[0],8);
bzero(&src_addr,sizeof(src_addr)); bzero(&src_addr,sizeof(src_addr));
if ((plen>=0)&&(packet[0]==0x01)&&!(packet[1]|packet[2]|packet[3])) { if ((plen>=0)&&(packet[0]==0x01)&&!(packet[1]|packet[2]|packet[3])) {
@ -320,8 +321,9 @@ int overlay_rx_messages()
&src_addr,&addrlen); &src_addr,&addrlen);
if (plen<0) { c[i]=0; count--; } else { if (plen<0) { c[i]=0; count--; } else {
/* We have a frame from this interface */ /* We have a frame from this interface */
if (debug) serval_packetvisualise(stderr,"Read from real interface", if (debug&DEBUG_PACKETXFER)
packet,plen); serval_packetvisualise(stderr,"Read from real interface",
packet,plen);
if (debug&DEBUG_OVERLAYINTERFACES)fprintf(stderr,"Received %d bytes on interface #%d\n",plen,i); if (debug&DEBUG_OVERLAYINTERFACES)fprintf(stderr,"Received %d bytes on interface #%d\n",plen,i);
if (packetOk(i,packet,plen,NULL,&src_addr,addrlen,1)) WHY("Malformed packet"); if (packetOk(i,packet,plen,NULL,&src_addr,addrlen,1)) WHY("Malformed packet");
@ -366,7 +368,7 @@ int overlay_broadcast_ensemble(int interface_number,
else { else {
s = overlay_interfaces[interface_number].broadcast_address; s = overlay_interfaces[interface_number].broadcast_address;
s.sin_family = AF_INET; s.sin_family = AF_INET;
if (debug&4) fprintf(stderr,"Port=%d\n",overlay_interfaces[interface_number].port); if (debug&DEBUG_PACKETXFER) fprintf(stderr,"Port=%d\n",overlay_interfaces[interface_number].port);
s.sin_port = htons( overlay_interfaces[interface_number].port ); s.sin_port = htons( overlay_interfaces[interface_number].port );
} }
@ -429,15 +431,21 @@ int overlay_broadcast_ensemble(int interface_number,
interface they came in. */ interface they came in. */
int overlay_sendto(struct sockaddr_in *recipientaddr,unsigned char *bytes,int len) int overlay_sendto(struct sockaddr_in *recipientaddr,unsigned char *bytes,int len)
{ {
if (debug>1) fprintf(stderr,"Sending %d bytes.\n",len); if (debug&DEBUG_PACKETXFER) fprintf(stderr,"Sending %d bytes.\n",len);
if(overlay_broadcast_ensemble(overlay_last_interface_number,recipientaddr,bytes,len)) if(overlay_broadcast_ensemble(overlay_last_interface_number,recipientaddr,bytes,len))
return -1; return -1;
else else
return len; return len;
} }
time_t overlay_last_interface_discover_time=0;
int overlay_interface_discover() int overlay_interface_discover()
{ {
/* Don't waste too much time and effort on interface discovery,
especially if we can't attach to a given interface for some reason. */
if ((time(0)-overlay_last_interface_discover_time)<2) return 0;
overlay_last_interface_discover_time=time(0);
#ifdef HAVE_IFADDRS_H #ifdef HAVE_IFADDRS_H
struct ifaddrs *ifaddr,*ifa; struct ifaddrs *ifaddr,*ifa;
int family,i; int family,i;
@ -465,7 +473,7 @@ int overlay_interface_discover()
1000000,PORT_DNA,OVERLAY_INTERFACE_WIFI)) 1000000,PORT_DNA,OVERLAY_INTERFACE_WIFI))
WHY("Could not initialise newly seen interface"); WHY("Could not initialise newly seen interface");
else else
if (debug&4)fprintf(stderr,"Registered interface %s\n",r->namespec); if (debug&DEBUG_OVERLAYINTERFACES) fprintf(stderr,"Registered interface %s\n",r->namespec);
} }
} }
r=r->next; r=r->next;
@ -483,7 +491,7 @@ int overlay_interface_discover()
unsigned int broadcast_bits=local.sin_addr.s_addr|~netmask.sin_addr.s_addr; unsigned int broadcast_bits=local.sin_addr.s_addr|~netmask.sin_addr.s_addr;
struct sockaddr_in broadcast=local; struct sockaddr_in broadcast=local;
broadcast.sin_addr.s_addr=broadcast_bits; broadcast.sin_addr.s_addr=broadcast_bits;
if (debug>3) printf("%s: %08x %08x %08x\n",name,local.sin_addr.s_addr,netmask.sin_addr.s_addr,broadcast.sin_addr.s_addr); if (debug&DEBUG_OVERLAYINTERFACES) printf("%s: %08x %08x %08x\n",name,local.sin_addr.s_addr,netmask.sin_addr.s_addr,broadcast.sin_addr.s_addr);
/* Now register the interface, or update the existing interface registration */ /* Now register the interface, or update the existing interface registration */
struct interface_rules *r=interface_filter,*me=NULL; struct interface_rules *r=interface_filter,*me=NULL;
while(r) { while(r) {
@ -492,7 +500,8 @@ int overlay_interface_discover()
r=r->next; r=r->next;
} }
if (me&&(!me->excludeP)) { if (me&&(!me->excludeP)) {
if (debug&4)fprintf(stderr,"Interface %s is interesting.\n",name); if (debug&DEBUG_OVERLAYINTERFACES)
fprintf(stderr,"Interface %s is interesting.\n",name);
/* We should register or update this interface. */ /* We should register or update this interface. */
int i; int i;
for(i=0;i<overlay_interface_count;i++) if (!strcasecmp(overlay_interfaces[i].name,(char *)name)) break; for(i=0;i<overlay_interface_count;i++) if (!strcasecmp(overlay_interfaces[i].name,(char *)name)) break;
@ -520,7 +529,7 @@ int overlay_interface_discover()
me->speed_in_bits,me->port,me->type)) me->speed_in_bits,me->port,me->type))
WHY("Could not initialise newly seen interface"); WHY("Could not initialise newly seen interface");
else else
if (debug&4) fprintf(stderr,"Registered interface %s\n",name); if (debug&DEBUG_OVERLAYINTERFACES) fprintf(stderr,"Registered interface %s\n",name);
} }
} }
break; break;
@ -594,7 +603,7 @@ int overlay_tick_interface(int i, long long now)
return 0; return 0;
} }
if (debug&4) fprintf(stderr,"Ticking interface #%d\n",i); if (debug&DEBUG_OVERLAYINTERFACES) fprintf(stderr,"Ticking interface #%d\n",i);
/* Get a buffer ready, and limit it's size appropriately. /* Get a buffer ready, and limit it's size appropriately.
XXX size limit should be reduced from MTU. XXX size limit should be reduced from MTU.
@ -639,7 +648,8 @@ int overlay_tick_interface(int i, long long now)
/* Now send the frame. This takes the form of a special DNA packet with a different /* Now send the frame. This takes the form of a special DNA packet with a different
service code, which we setup earlier. */ service code, which we setup earlier. */
if (debug&4) fprintf(stderr,"Sending %d bytes\n",e->length); if (debug&DEBUG_OVERLAYINTERFACES)
fprintf(stderr,"Sending %d byte tick packet\n",e->length);
if (!overlay_broadcast_ensemble(i,NULL,e->bytes,e->length)) if (!overlay_broadcast_ensemble(i,NULL,e->bytes,e->length))
{ {
overlay_update_sequence_number(); overlay_update_sequence_number();
@ -684,7 +694,7 @@ int overlay_check_ticks()
/* Now check if the next tick time for the interfaces is no later than that time. /* Now check if the next tick time for the interfaces is no later than that time.
If so, trigger a tick on the interface. */ If so, trigger a tick on the interface. */
if (debug&4) fprintf(stderr,"Examining %d interfaces.\n",overlay_interface_count); if (debug&DEBUG_OVERLAYINTERFACES) fprintf(stderr,"Examining %d interfaces.\n",overlay_interface_count);
for(i=0;i<overlay_interface_count;i++) for(i=0;i<overlay_interface_count;i++)
{ {
/* Only tick live interfaces */ /* Only tick live interfaces */

View File

@ -108,7 +108,7 @@ int packetOkOverlay(int interface,unsigned char *packet,int len,unsigned char *t
f.type=packet[ofs]&OF_TYPE_BITS; f.type=packet[ofs]&OF_TYPE_BITS;
f.modifiers=packet[ofs]&OF_MODIFIER_BITS; f.modifiers=packet[ofs]&OF_MODIFIER_BITS;
if (debug>3) fprintf(stderr,"f.type=0x%02x, f.modifiers=0x%02x, ofs=%d\n", if (debug&DEBUG_PACKETFORMATS) fprintf(stderr,"f.type=0x%02x, f.modifiers=0x%02x, ofs=%d\n",
f.type,f.modifiers,ofs); f.type,f.modifiers,ofs);
switch(packet[ofs]&OF_TYPE_BITS) switch(packet[ofs]&OF_TYPE_BITS)
@ -147,7 +147,7 @@ int packetOkOverlay(int interface,unsigned char *packet,int len,unsigned char *t
/* Decode length of remainder of frame */ /* Decode length of remainder of frame */
f.rfs=rfs_decode(packet,&ofs); f.rfs=rfs_decode(packet,&ofs);
if (debug>3) fprintf(stderr,"f.rfs=%d, ofs=%d\n",f.rfs,ofs); if (debug&DEBUG_PACKETFORMATS) fprintf(stderr,"f.rfs=%d, ofs=%d\n",f.rfs,ofs);
if (!f.rfs) { if (!f.rfs) {
/* Zero length -- assume we fell off the end of the packet */ /* Zero length -- assume we fell off the end of the packet */
@ -168,7 +168,7 @@ int packetOkOverlay(int interface,unsigned char *packet,int len,unsigned char *t
if (f.bytecount<0) { if (f.bytecount<0) {
f.bytecount=0; f.bytecount=0;
WHY("negative residual byte count after extracting addresses from frame header"); WHY("negative residual byte count after extracting addresses from frame header");
if (debug>3) fprintf(stderr,"f.rfs=%d, offset=%d, ofs=%d\n", if (debug&DEBUG_PACKETFORMATS) fprintf(stderr,"f.rfs=%d, offset=%d, ofs=%d\n",
f.rfs,offset,ofs); f.rfs,offset,ofs);
return WHY("negative residual byte count after extracting addresses from frame header"); return WHY("negative residual byte count after extracting addresses from frame header");
} }
@ -178,7 +178,7 @@ int packetOkOverlay(int interface,unsigned char *packet,int len,unsigned char *t
/* Skip the rest of the bytes in this frame so that we can examine the next one in this /* Skip the rest of the bytes in this frame so that we can examine the next one in this
ensemble */ ensemble */
if (debug&4) fprintf(stderr,"ofs=%d, f.rfs=%d, len=%d\n",ofs,f.rfs,len); if (debug&DEBUG_PACKETFORMATS) fprintf(stderr,"ofs=%d, f.rfs=%d, len=%d\n",ofs,f.rfs,len);
ofs+=f.rfs; ofs+=f.rfs;
} }

View File

@ -374,7 +374,7 @@ int overlay_get_nexthop(unsigned char *d,unsigned char *nexthop,int *nexthoplen,
if (neh->scores[i]>neh->scores[*interface]) *interface=i; if (neh->scores[i]>neh->scores[*interface]) *interface=i;
} }
if (neh->scores[*interface]<1) { if (neh->scores[*interface]<1) {
if (debug>2) { if (debug>DEBUG_OVERLAYROUTING) {
int i; int i;
fprintf(stderr,"No open path to "); fprintf(stderr,"No open path to ");
for(i=0;i<SID_SIZE;i++) fprintf(stderr,"%02x",neh->node->sid[i]); for(i=0;i<SID_SIZE;i++) fprintf(stderr,"%02x",neh->node->sid[i]);
@ -405,7 +405,7 @@ unsigned int overlay_route_hash_sid(unsigned char *sid)
/* Mask out extranous bits to return only a valid bin number */ /* Mask out extranous bits to return only a valid bin number */
bin&=(overlay_bin_count-1); bin&=(overlay_bin_count-1);
if (debug>3) { if (debug>DEBUG_OVERLAYROUTING) {
int zeroes=0; int zeroes=0;
fprintf(stderr,"The following address resolves to bin #%d\n",bin); fprintf(stderr,"The following address resolves to bin #%d\n",bin);
for(i=0;i<SID_SIZE;i++) { fprintf(stderr,"%02x",sid[i]); if (!sid[i]) zeroes++; } for(i=0;i<SID_SIZE;i++) { fprintf(stderr,"%02x",sid[i]); if (!sid[i]) zeroes++; }
@ -886,7 +886,7 @@ int overlay_route_recalc_neighbour_metrics(overlay_neighbour *n,long long now)
if (score<0) score=0; if (score<0) score=0;
n->scores[i]=score; n->scores[i]=score;
if (debug>3&&score) fprintf(stderr,"Neighbour score on interface #%d = %d (observations for %dms)\n",i,score,ms_observed[i]); if ((debug&DEBUG_OVERLAYROUTING)&&score) fprintf(stderr,"Neighbour score on interface #%d = %d (observations for %dms)\n",i,score,ms_observed[i]);
} }
return 0; return 0;
@ -1026,7 +1026,7 @@ int overlay_address_is_local(unsigned char *s)
for (ii=0;ii<overlay_local_identity_count;ii++) { for (ii=0;ii<overlay_local_identity_count;ii++) {
for(i=0;i<SID_SIZE;i++) for(i=0;i<SID_SIZE;i++)
if (s[i]!=overlay_local_identities[ii][i]) if (s[i]!=overlay_local_identities[ii][i])
{ if (debug>3) fprintf(stderr,"address is not local address #%d, since byte %d = %02x != %02x\n", { if (debug&DEBUG_OVERLAYROUTING) fprintf(stderr,"address is not local address #%d, since byte %d = %02x != %02x\n",
ii,i,s[i],overlay_local_identities[ii][i]); ii,i,s[i],overlay_local_identities[ii][i]);
break; } break; }
if (i==SID_SIZE) { return 1; } if (i==SID_SIZE) { return 1; }
@ -1127,7 +1127,7 @@ int overlay_route_tick()
long long start_time=overlay_gettime_ms(); long long start_time=overlay_gettime_ms();
if (debug>3) if (debug&DEBUG_OVERLAYROUTING)
fprintf(stderr,"Neighbours: %d@%d, Nodes: %d@%d\n", fprintf(stderr,"Neighbours: %d@%d, Nodes: %d@%d\n",
overlay_route_tick_neighbour_bundle_size,overlay_route_tick_next_neighbour_id, overlay_route_tick_neighbour_bundle_size,overlay_route_tick_next_neighbour_id,
overlay_route_tick_node_bundle_size,overlay_route_tick_next_node_bin_id); overlay_route_tick_node_bundle_size,overlay_route_tick_next_node_bin_id);
@ -1183,7 +1183,7 @@ int overlay_route_tick()
if (ticks>5000) ticks=5000; if (ticks>5000) ticks=5000;
int interval=5000/ticks; int interval=5000/ticks;
if (debug>3) fprintf(stderr,"route tick interval = %dms (%d ticks per 5sec, neigh=%lldms, node=%lldms)\n",interval,ticks,neighbour_time,node_time); if (debug&DEBUG_OVERLAYROUTING) fprintf(stderr,"route tick interval = %dms (%d ticks per 5sec, neigh=%lldms, node=%lldms)\n",interval,ticks,neighbour_time,node_time);
return interval; return interval;
} }

View File

@ -37,7 +37,7 @@ int process_packet(unsigned char *packet,int len,struct sockaddr *sender,int sen
/* Authentication has been attempted. /* Authentication has been attempted.
If it is incorrect, then we need to return with ACTION_DECLINED If it is incorrect, then we need to return with ACTION_DECLINED
*/ */
if (debug>1) fprintf(stderr,"A PIN has been supplied.\n"); if (debug&DEBUG_SECURITY) fprintf(stderr,"A PIN has been supplied.\n");
/* Can only authenticate by SID, not DID (since DIDs are ambiguous) */ /* Can only authenticate by SID, not DID (since DIDs are ambiguous) */
if (packet[OFS_SIDDIDFIELD]!=1) return setReason("You can only authenticate against a SID"); if (packet[OFS_SIDDIDFIELD]!=1) return setReason("You can only authenticate against a SID");
@ -49,7 +49,7 @@ int process_packet(unsigned char *packet,int len,struct sockaddr *sender,int sen
{ {
/* No attempt at authentication was made */ /* No attempt at authentication was made */
authenticatedP=0; authenticatedP=0;
if (debug>1) fprintf(stderr,"No PIN was supplied.\n"); if (debug&DEBUG_SECURITY) fprintf(stderr,"No PIN was supplied.\n");
} }
if (serverMode) return processRequest(packet,len,sender,sender_len,transaction_id,did,sid); if (serverMode) return processRequest(packet,len,sender,sender_len,transaction_id,did,sid);
@ -120,8 +120,8 @@ int packetOkDNA(unsigned char *packet,int len,unsigned char *transaction_id,
bcopy(&temp[0],&packet[HEADERFIELDS_LEN],payloadRotation); bcopy(&temp[0],&packet[HEADERFIELDS_LEN],payloadRotation);
} }
if (debug>1) fprintf(stderr,"Packet passes sanity checks and is ready for decoding.\n"); if (debug&DEBUG_PACKETFORMATS) fprintf(stderr,"Packet passes sanity checks and is ready for decoding.\n");
if (debug>2) dump("unrotated packet",packet,len); if (debug&DEBUG_PACKETFORMATS) dump("unrotated packet",packet,len);
if (parseP) return process_packet(packet,len,recvaddr,recvaddrlen); else return 0; if (parseP) return process_packet(packet,len,recvaddr,recvaddrlen); else return 0;
} }
@ -193,7 +193,7 @@ int packetSetSid(unsigned char *packet,int packet_maxlen,int *packet_len,char *s
int ofs=OFS_SIDDIDFIELD; /* where the DID/subscriber ID gets written */ int ofs=OFS_SIDDIDFIELD; /* where the DID/subscriber ID gets written */
if (strlen(sid)!=64) { if (strlen(sid)!=64) {
if (debug) fprintf(stderr,"Invalid SID: [%s] - should be 64 hex digits\n",sid); if (debug&DEBUG_PACKETFORMATS) fprintf(stderr,"Invalid SID: [%s] - should be 64 hex digits\n",sid);
return setReason("SID must consist of 64 hex digits"); return setReason("SID must consist of 64 hex digits");
} }
@ -229,10 +229,10 @@ int packetFinalise(unsigned char *packet,int packet_maxlen,int *packet_len,int c
payloadRotation=(*packet_len)-HEADERFIELDS_LEN; payloadRotation=(*packet_len)-HEADERFIELDS_LEN;
if (payloadRotation>0xff) payloadRotation=0xff; if (payloadRotation>0xff) payloadRotation=0xff;
payloadRotation=random()%payloadRotation; payloadRotation=random()%payloadRotation;
if (debug>2) if (debug&DEBUG_SECURITY)
fprintf(stderr,"Known Plaintext counter-measure: rotating packet payload by 0x%02x bytes.\n", fprintf(stderr,"Known Plaintext counter-measure: rotating packet payload by 0x%02x bytes.\n",
payloadRotation); payloadRotation);
if (debug>2) dump("unrotated packet",packet,*packet_len); if (debug&DEBUG_SECURITY) dump("unrotated packet",packet,*packet_len);
/* Now rotate the payload */ /* Now rotate the payload */
{ {
@ -247,7 +247,7 @@ int packetFinalise(unsigned char *packet,int packet_maxlen,int *packet_len,int c
bcopy(&temp[0],&packet[(*packet_len)-payloadRotation],payloadRotation); bcopy(&temp[0],&packet[(*packet_len)-payloadRotation],payloadRotation);
} }
packet[OFS_ROTATIONFIELD]=payloadRotation; packet[OFS_ROTATIONFIELD]=payloadRotation;
if (debug>3) dump("rotated packet",packet,*packet_len); if (debug&DEBUG_SECURITY) dump("rotated packet",packet,*packet_len);
if (cryptoflags) return packetEncipher(packet,packet_maxlen,packet_len,cryptoflags); if (cryptoflags) return packetEncipher(packet,packet_maxlen,packet_len,cryptoflags);
@ -261,7 +261,7 @@ int packetAddHLRCreateRequest(unsigned char *packet,int packet_maxlen,int *packe
CHECK_PACKET_LEN(1); CHECK_PACKET_LEN(1);
packet[(*packet_len)++]=ACTION_CREATEHLR; packet[(*packet_len)++]=ACTION_CREATEHLR;
if (debug>2) dump("Variable request octets (HLR create)",&packet[packet_len_in],(*packet_len)-packet_len_in); if (debug&(DEBUG_HLR|DEBUG_PACKETFORMATS)) dump("Variable request octets (HLR create)",&packet[packet_len_in],(*packet_len)-packet_len_in);
return 0; return 0;
} }
@ -279,7 +279,7 @@ int packetAddVariableRequest(unsigned char *packet,int packet_maxlen,int *packet
/* Sanity check the request */ /* Sanity check the request */
if (!vars[itemId].name) { if (!vars[itemId].name) {
if (debug) fprintf(stderr,"`%s' is not a known HLR variable.\n",item); if (debug&(DEBUG_DNAVARS|DEBUG_PACKETFORMATS)) fprintf(stderr,"`%s' is not a known HLR variable.\n",item);
return setReason("Requested unknown HLR variable"); return setReason("Requested unknown HLR variable");
} }
itemId=vars[itemId].id; itemId=vars[itemId].id;
@ -290,7 +290,7 @@ int packetAddVariableRequest(unsigned char *packet,int packet_maxlen,int *packet
} }
if (start_offset<0||start_offset>0xffff) return setReason("Asked for illegal variable value starting offset"); if (start_offset<0||start_offset>0xffff) return setReason("Asked for illegal variable value starting offset");
if (bytes<0||(start_offset+bytes)>0xffff) { if (bytes<0||(start_offset+bytes)>0xffff) {
if (debug) fprintf(stderr,"Asked for %d bytes at offset %d\n",bytes,start_offset); if (debug&(DEBUG_PACKETFORMATS|DEBUG_DNAVARS)) fprintf(stderr,"Asked for %d bytes at offset %d\n",bytes,start_offset);
return setReason("Asked for illegal variable value ending offset"); return setReason("Asked for illegal variable value ending offset");
} }
@ -304,7 +304,7 @@ int packetAddVariableRequest(unsigned char *packet,int packet_maxlen,int *packet
packet[(*packet_len)++]=bytes>>8; packet[(*packet_len)++]=bytes>>8;
packet[(*packet_len)++]=bytes&0xff; packet[(*packet_len)++]=bytes&0xff;
if (debug>2) dump("Variable request octets (var)",&packet[packet_len_in],(*packet_len)-packet_len_in); if (debug&DEBUG_PACKETFORMATS) dump("Variable request octets (var)",&packet[packet_len_in],(*packet_len)-packet_len_in);
return 0; return 0;
} }
@ -319,7 +319,7 @@ int packetAddVariableWrite(unsigned char *packet,int packet_maxlen,
int max_offset=start_offset+value_len-1; int max_offset=start_offset+value_len-1;
if (debug>1) printf("packetAddVariableWrite(start=%d,len=%d,flags=%d)\n",start_offset,value_len,flags); if (debug&DEBUG_PACKETFORMATS) printf("packetAddVariableWrite(start=%d,len=%d,flags=%d)\n",start_offset,value_len,flags);
/* Sanity check */ /* Sanity check */
if (itemId&0x80) { if (itemId&0x80) {
@ -341,13 +341,13 @@ int packetAddVariableWrite(unsigned char *packet,int packet_maxlen,
packet[(*packet_len)++]=value_len&0xff; packet[(*packet_len)++]=value_len&0xff;
packet[(*packet_len)++]=flags; packet[(*packet_len)++]=flags;
if (debug>2) dump("Packet with var write header",&packet[0],*packet_len); if (debug&DEBUG_PACKETFORMATS) dump("Packet with var write header",&packet[0],*packet_len);
CHECK_PACKET_LEN(value_len); CHECK_PACKET_LEN(value_len);
bcopy(&value[0],&packet[*packet_len],value_len); bcopy(&value[0],&packet[*packet_len],value_len);
(*packet_len)+=value_len; (*packet_len)+=value_len;
if (debug>2) dump("Variable request octets (write)",&packet[packet_len_in],(*packet_len)-packet_len_in); if (debug&DEBUG_PACKETFORMATS) dump("Variable request octets (write)",&packet[packet_len_in],(*packet_len)-packet_len_in);
return 0; return 0;
} }
@ -371,11 +371,11 @@ int extractRequest(unsigned char *packet,int *packet_ofs,int packet_len,
*bytes|=packet[(*packet_ofs)++]; *bytes|=packet[(*packet_ofs)++];
*flags=packet[(*packet_ofs)++]; *flags=packet[(*packet_ofs)++];
if (debug>2) printf("Write flags = 0x%02x\n",*flags); if (debug&DEBUG_DNAREQUESTS) printf("Write flags = 0x%02x\n",*flags);
if (*packet_ofs<0||(*packet_ofs)+(*bytes)>=packet_len) if (*packet_ofs<0||(*packet_ofs)+(*bytes)>=packet_len)
{ {
if (debug) fprintf(stderr,"Packet offset is %d, length is %d, and asked for %d bytes.\n",*packet_ofs,packet_len,*bytes); if (debug&DEBUG_PACKETFORMATS) fprintf(stderr,"Packet offset is %d, length is %d, and asked for %d bytes.\n",*packet_ofs,packet_len,*bytes);
return setReason("mal-formed request packet (too short for claimed data)"); return setReason("mal-formed request packet (too short for claimed data)");
} }
@ -404,7 +404,7 @@ int extractResponses(struct in_addr sender,unsigned char *buffer,int len,struct
switch(buffer[ofs]) switch(buffer[ofs])
{ {
case ACTION_EOT: case ACTION_EOT:
if (debug>1) fprintf(stderr,"Reached response packet EOT.\n"); if (debug&DEBUG_DNARESPONSES) fprintf(stderr,"Reached response packet EOT.\n");
case ACTION_DECLINED: case ACTION_OKAY: case ACTION_DECLINED: case ACTION_OKAY:
case ACTION_CREATEHLR: case ACTION_CREATEHLR:
r->response_len=0; break; r->response_len=0; break;
@ -438,7 +438,7 @@ int extractResponses(struct in_addr sender,unsigned char *buffer,int len,struct
case ACTION_XFER: case ACTION_XFER:
default: default:
free(r); free(r);
if (debug>1) fprintf(stderr,"Encountered unimplemented response code 0x%02x @ 0x%x\n",buffer[ofs],ofs); if (debug&(DEBUG_DNARESPONSES|DEBUG_PACKETFORMATS)) fprintf(stderr,"Encountered unimplemented response code 0x%02x @ 0x%x\n",buffer[ofs],ofs);
fixResponses(responses); fixResponses(responses);
return setReason("Encountered unimplemented response type"); return setReason("Encountered unimplemented response type");
} }
@ -463,7 +463,7 @@ int extractResponses(struct in_addr sender,unsigned char *buffer,int len,struct
if (r->peer_id>peer_count) r->peer_id=-1; if (r->peer_id>peer_count) r->peer_id=-1;
/* Link new response into chain */ /* Link new response into chain */
if (debug>2) printf("Linking response into response set.\n"); if (debug&DEBUG_DNARESPONSES) printf("Linking response into response set.\n");
r->prev=responses->last_response; r->prev=responses->last_response;
if (responses->last_response) if (responses->last_response)
responses->last_response->next=r; responses->last_response->next=r;
@ -474,7 +474,7 @@ int extractResponses(struct in_addr sender,unsigned char *buffer,int len,struct
responseFromPeer(responses,r->peer_id); responseFromPeer(responses,r->peer_id);
if (debug>2) dumpResponses(responses); if (debug&DEBUG_DNARESPONSES) dumpResponses(responses);
} }
fixResponses(responses); fixResponses(responses);
@ -493,7 +493,7 @@ int packageVariableSegment(unsigned char *data,int *dlen,struct hlrentry_handle
bytes=buffer_size-(*dlen)-8; bytes=buffer_size-(*dlen)-8;
if ((h->value_len-offset)<bytes) bytes=h->value_len-offset; if ((h->value_len-offset)<bytes) bytes=h->value_len-offset;
if (bytes<0) bytes=0; if (bytes<0) bytes=0;
if (debug>1) fprintf(stderr,"Packaging %d bytes of variable\n",bytes); if (debug&DEBUG_PACKETFORMATS) fprintf(stderr,"Packaging %d bytes of variable\n",bytes);
/* Describe variable */ /* Describe variable */
@ -512,13 +512,13 @@ int packageVariableSegment(unsigned char *data,int *dlen,struct hlrentry_handle
/* Number of bytes in this segment */ /* Number of bytes in this segment */
data[(*dlen)++]=(bytes>>8)&0xff; data[(*dlen)++]=(bytes>>8)&0xff;
data[(*dlen)++]=bytes&0xff; data[(*dlen)++]=bytes&0xff;
if (debug>1) fprintf(stderr,"Packaging %d bytes\n",bytes); if (debug&DEBUG_PACKETFORMATS) fprintf(stderr,"Packaging %d bytes\n",bytes);
/* Package the variable value itself (or part thereof) */ /* Package the variable value itself (or part thereof) */
bcopy(&h->value[offset],&data[*dlen],bytes); bcopy(&h->value[offset],&data[*dlen],bytes);
(*dlen)+=bytes; (*dlen)+=bytes;
if (debug>2) dump("Variable segment octets",&data[dlen_in],(*dlen)-dlen_in); if (debug&DEBUG_PACKETFORMATS) dump("Variable segment octets",&data[dlen_in],(*dlen)-dlen_in);
return 0; return 0;
} }

16
peers.c
View File

@ -60,7 +60,7 @@ int getBroadcastAddresses(struct in_addr peers[],int *peer_count,int peer_max){
size_t bytesRead; size_t bytesRead;
struct nlmsghdr *hdr; struct nlmsghdr *hdr;
if (debug>1) fprintf(stderr,"Reading broadcast addresses (linux style)\n"); if (debug&DEBUG_PEERS) fprintf(stderr,"Reading broadcast addresses (linux style)\n");
netsock = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE); netsock = socket(AF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE);
@ -110,7 +110,7 @@ int getBroadcastAddresses(struct in_addr peers[],int *peer_count,int peer_max){
struct ifaddrs *ifaddr,*ifa; struct ifaddrs *ifaddr,*ifa;
int family; int family;
if (debug>1) fprintf(stderr,"Reading broadcast addresses (posix style)\n"); if (debug&DEBUG_PEERS) fprintf(stderr,"Reading broadcast addresses (posix style)\n");
if (getifaddrs(&ifaddr) == -1) { if (getifaddrs(&ifaddr) == -1) {
perror("getifaddr()"); perror("getifaddr()");
@ -135,7 +135,7 @@ int getBroadcastAddresses(struct in_addr peers[],int *peer_count,int peer_max){
} }
} }
#else #else
if (debug>1) fprintf(stderr,"Don't know how to read broadcast addresses :(\n"); if (debug&DEBUG_PEERS) fprintf(stderr,"Don't know how to read broadcast addresses :(\n");
#endif #endif
#endif #endif
return 0; return 0;
@ -201,27 +201,27 @@ int sendToPeers(unsigned char *packet,int packet_len,int method,int peerId,struc
{ {
peer_addr.sin_addr=peers[i]; peer_addr.sin_addr=peers[i];
if (debug>1) fprintf(stderr,"Sending packet to peer #%d\n",i); if (debug&(DEBUG_PACKETXFER|DEBUG_PEERS)) fprintf(stderr,"Sending packet to peer #%d\n",i);
ret=sendto(sock,packet,packet_len,0,(struct sockaddr *)&peer_addr,sizeof(peer_addr)); ret=sendto(sock,packet,packet_len,0,(struct sockaddr *)&peer_addr,sizeof(peer_addr));
if (ret<packet_len) if (ret<packet_len)
{ {
/* XXX something bad happened */ /* XXX something bad happened */
if (debug) fprintf(stderr,"Could not send to peer %s\n",inet_ntoa(peer_addr.sin_addr)); if (debug&(DEBUG_PACKETXFER|DEBUG_PEERS)) fprintf(stderr,"Could not send to peer %s\n",inet_ntoa(peer_addr.sin_addr));
} }
else else
{ {
if (debug>1) fprintf(stderr,"Sent request to peer %s\n",inet_ntoa(peer_addr.sin_addr)); if (debug&(DEBUG_PACKETXFER|DEBUG_PEERS)) fprintf(stderr,"Sent request to peer %s\n",inet_ntoa(peer_addr.sin_addr));
n++; n++;
/* If sending to only one peer, return now */ /* If sending to only one peer, return now */
if (method==i) break; if (method==i) break;
} }
} }
else else
if (debug>1) fprintf(stderr,"Peer %s has already replied, so not sending again.\n", if (debug&DEBUG_PEERS) fprintf(stderr,"Peer %s has already replied, so not sending again.\n",
inet_ntoa(peer_addr.sin_addr)); inet_ntoa(peer_addr.sin_addr));
if (debug) fprintf(stderr,"Sent request to %d peers.\n",n); if (debug&DEBUG_PEERS) fprintf(stderr,"Sent request to %d peers.\n",n);
return 0; return 0;

View File

@ -1479,7 +1479,7 @@ int overlay_rhizome_add_advertisements(int interface_number,overlay_buffer *e)
} }
} }
if (debug>1) printf("Appended %d rhizome advertisements to packet.\n",slots_used); if (debug&DEBUG_RHIZOME) printf("Appended %d rhizome advertisements to packet.\n",slots_used);
e->bytes[rfs_offset]=1+1+1+1+RHIZOME_BAR_BYTES*slots_used; e->bytes[rfs_offset]=1+1+1+1+RHIZOME_BAR_BYTES*slots_used;
sqlite3_finalize(statement); sqlite3_finalize(statement);

View File

@ -137,7 +137,7 @@ int rhizome_server_poll()
/* Process the existing requests. /* Process the existing requests.
XXX - should use poll or select here */ XXX - should use poll or select here */
if (debug>1) printf("Checking %d active connections\n", if (debug&DEBUG_RHIZOME) printf("Checking %d active connections\n",
rhizome_server_live_request_count); rhizome_server_live_request_count);
for(rn=0;rn<rhizome_server_live_request_count;rn++) for(rn=0;rn<rhizome_server_live_request_count;rn++)
{ {
@ -594,7 +594,7 @@ int rhizome_server_http_send_bytes(int rn,rhizome_http_request *r)
int bytes; int bytes;
fcntl(r->socket,F_SETFL,fcntl(r->socket, F_GETFL, NULL)|O_NONBLOCK); fcntl(r->socket,F_SETFL,fcntl(r->socket, F_GETFL, NULL)|O_NONBLOCK);
if (debug>1) fprintf(stderr,"Request #%d, type=0x%x\n",rn,r->request_type); if (debug&DEBUG_RHIZOME) fprintf(stderr,"Request #%d, type=0x%x\n",rn,r->request_type);
/* Flush anything out of the buffer if present, before doing any further /* Flush anything out of the buffer if present, before doing any further
processing */ processing */
@ -614,7 +614,7 @@ int rhizome_server_http_send_bytes(int rn,rhizome_http_request *r)
WHY("Finished sending data"); WHY("Finished sending data");
return rhizome_server_close_http_request(rn); return rhizome_server_close_http_request(rn);
} else { } else {
if (debug>1) { fprintf(stderr,"request type = 0x%x after sending buffer.\n", if (debug&DEBUG_RHIZOME) { fprintf(stderr,"request type = 0x%x after sending buffer.\n",
r->request_type); r->request_type);
} }
} }

View File

@ -73,7 +73,7 @@ int getBackingStore(char *backing_file,int size)
/* transitory storage of HLR data, so just malloc() the memory */ /* transitory storage of HLR data, so just malloc() the memory */
hlr=calloc(size,1); hlr=calloc(size,1);
if (!hlr) exit(setReason("Failed to calloc() HLR database.")); if (!hlr) exit(setReason("Failed to calloc() HLR database."));
if (debug) fprintf(stderr,"Allocated %d byte temporary HLR store\n",size); if (debug&DEBUG_HLR) fprintf(stderr,"Allocated %d byte temporary HLR store\n",size);
} }
else else
{ {
@ -107,7 +107,7 @@ int getBackingStore(char *backing_file,int size)
perror("mmap"); perror("mmap");
exit(setReason("Memory mapping of HLR backing file failed.")); exit(setReason("Memory mapping of HLR backing file failed."));
} }
if (debug) fprintf(stderr,"Allocated %d byte HLR store backed by file `%s'\n", if (debug&DEBUG_HLR) fprintf(stderr,"Allocated %d byte HLR store backed by file `%s'\n",
size,backing_file); size,backing_file);
} }
hlr_size=size; hlr_size=size;
@ -130,7 +130,7 @@ int processRequest(unsigned char *packet,int len,
while(pofs<len) while(pofs<len)
{ {
if (debug>1) fprintf(stderr," processRequest: len=%d, pofs=%d, pofs_prev=%d\n",len,pofs,prev_pofs); if (debug&DEBUG_DNAREQUESTS) fprintf(stderr," processRequest: len=%d, pofs=%d, pofs_prev=%d\n",len,pofs,prev_pofs);
/* Avoid infinite loops */ /* Avoid infinite loops */
if (pofs<=prev_pofs) break; if (pofs<=prev_pofs) break;
prev_pofs=pofs; prev_pofs=pofs;
@ -139,10 +139,10 @@ int processRequest(unsigned char *packet,int len,
{ {
/* Creating an HLR requires an initial DID number and definately no SID - /* Creating an HLR requires an initial DID number and definately no SID -
you can't choose a SID. */ you can't choose a SID. */
if (debug>1) fprintf(stderr,"Creating a new HLR record. did='%s', sid='%s'\n",did,sid); if (debug&DEBUG_HLR) fprintf(stderr,"Creating a new HLR record. did='%s', sid='%s'\n",did,sid);
if (!did[0]) return respondSimple(NULL,ACTION_DECLINED,NULL,0,transaction_id,sender,CRYPT_CIPHERED|CRYPT_SIGNED); if (!did[0]) return respondSimple(NULL,ACTION_DECLINED,NULL,0,transaction_id,sender,CRYPT_CIPHERED|CRYPT_SIGNED);
if (sid[0]) return respondSimple(sid,ACTION_DECLINED,NULL,0,transaction_id,sender,CRYPT_CIPHERED|CRYPT_SIGNED); if (sid[0]) return respondSimple(sid,ACTION_DECLINED,NULL,0,transaction_id,sender,CRYPT_CIPHERED|CRYPT_SIGNED);
if (debug>1) fprintf(stderr,"Verified that create request supplies DID but not SID\n"); if (debug&DEBUG_HLR) fprintf(stderr,"Verified that create request supplies DID but not SID\n");
{ {
char sid[128]; char sid[128];
@ -157,7 +157,7 @@ int processRequest(unsigned char *packet,int len,
} }
else else
{ {
if (debug>2) fprintf(stderr,"Looking at action code 0x%02x @ packet offset 0x%x\n", if (debug&DEBUG_DNAREQUESTS) fprintf(stderr,"Looking at action code 0x%02x @ packet offset 0x%x\n",
packet[pofs],pofs); packet[pofs],pofs);
switch(packet[pofs]) switch(packet[pofs])
{ {
@ -186,7 +186,7 @@ int processRequest(unsigned char *packet,int len,
break; break;
case ACTION_DIGITALTELEGRAM: case ACTION_DIGITALTELEGRAM:
// Unpack SMS message. // Unpack SMS message.
if (debug>1) fprintf(stderr,"In ACTION_DIGITALTELEGRAM\n"); if (debug&DEBUG_DNAREQUESTS) fprintf(stderr,"In ACTION_DIGITALTELEGRAM\n");
{ {
char emitterPhoneNumber[256]; char emitterPhoneNumber[256];
char message[256]; char message[256];
@ -212,7 +212,7 @@ int processRequest(unsigned char *packet,int len,
// Send SMS to android // Send SMS to android
char amCommand[576]; // 64 char + 2*256(max) char = 576 char amCommand[576]; // 64 char + 2*256(max) char = 576
sprintf(amCommand, "am broadcast -a org.servalproject.DT -e number \"%s\" -e content \"%s\"", emitterPhoneNumber, message); sprintf(amCommand, "am broadcast -a org.servalproject.DT -e number \"%s\" -e content \"%s\"", emitterPhoneNumber, message);
if (debug>1) fprintf(stderr,"Delivering DT message via intent: %s\n",amCommand); if (debug&DEBUG_DNAREQUESTS) fprintf(stderr,"Delivering DT message via intent: %s\n",amCommand);
runCommand(amCommand); runCommand(amCommand);
respondSimple(hlrSid(hlr, ofs),ACTION_OKAY,NULL,0,transaction_id,sender,CRYPT_CIPHERED|CRYPT_SIGNED); respondSimple(hlrSid(hlr, ofs),ACTION_OKAY,NULL,0,transaction_id,sender,CRYPT_CIPHERED|CRYPT_SIGNED);
} }
@ -220,7 +220,7 @@ int processRequest(unsigned char *packet,int len,
break; break;
case ACTION_SET: case ACTION_SET:
ofs=0; ofs=0;
if (debug>1) fprintf(stderr,"Looking for hlr entries with sid='%s' / did='%s'\n",sid,did); if (debug&DEBUG_DNAREQUESTS) fprintf(stderr,"Looking for hlr entries with sid='%s' / did='%s'\n",sid,did);
if ((!sid)||(!sid[0])) { if ((!sid)||(!sid[0])) {
setReason("You can only set variables by SID"); setReason("You can only set variables by SID");
@ -234,8 +234,8 @@ int processRequest(unsigned char *packet,int len,
unsigned char value[9000],oldvalue[65536]; unsigned char value[9000],oldvalue[65536];
int oldr,oldl; int oldr,oldl;
if (debug>1) fprintf(stderr,"findHlr found a match for writing at 0x%x\n",ofs); if (debug&DEBUG_HLR) fprintf(stderr,"findHlr found a match for writing at 0x%x\n",ofs);
if (debug>2) hlrDump(hlr,ofs); if (debug&DEBUG_HLR) hlrDump(hlr,ofs);
/* XXX consider taking action on this HLR /* XXX consider taking action on this HLR
(check PIN first depending on the action requested) */ (check PIN first depending on the action requested) */
@ -271,7 +271,7 @@ int processRequest(unsigned char *packet,int len,
} else { } else {
if (flags==SET_NOREPLACE) { if (flags==SET_NOREPLACE) {
setReason("Tried to SET_NOREPLACE an existing value"); setReason("Tried to SET_NOREPLACE an existing value");
if (debug>1) dump("Existing value",oldvalue,oldl); if (debug&DEBUG_DNAREQUESTS) dump("Existing value (in SET_NOREPLACE flagged request)",oldvalue,oldl);
return return
respondSimple(NULL,ACTION_ERROR, respondSimple(NULL,ACTION_ERROR,
(unsigned char *)"Cannot SET NOREPLACE; a value exists", (unsigned char *)"Cannot SET NOREPLACE; a value exists",
@ -293,7 +293,7 @@ int processRequest(unsigned char *packet,int len,
respondSimple(NULL,ACTION_ERROR,(unsigned char *)"Failed to SET variable",0,transaction_id, respondSimple(NULL,ACTION_ERROR,(unsigned char *)"Failed to SET variable",0,transaction_id,
sender,CRYPT_CIPHERED|CRYPT_SIGNED); sender,CRYPT_CIPHERED|CRYPT_SIGNED);
} }
if (debug>2) { fprintf(stderr,"HLR after writing:\n"); hlrDump(hlr,ofs); } if (debug&DEBUG_HLR) { fprintf(stderr,"HLR after writing:\n"); hlrDump(hlr,ofs); }
/* Reply that we wrote the fragment */ /* Reply that we wrote the fragment */
respondSimple(sid,ACTION_WROTE,&packet[rofs],6, respondSimple(sid,ACTION_WROTE,&packet[rofs],6,
@ -309,7 +309,7 @@ int processRequest(unsigned char *packet,int len,
int dlen=0; int dlen=0;
int sendDone=0; int sendDone=0;
if (debug>2) dump("Request bytes",&packet[pofs],8); if (debug&DEBUG_HLR) dump("Request bytes",&packet[pofs],8);
pofs++; pofs++;
int var_id=packet[pofs]; int var_id=packet[pofs];
@ -321,10 +321,10 @@ int processRequest(unsigned char *packet,int len,
pofs+=2; pofs+=2;
if (debug>1) fprintf(stderr,"Processing ACTION_GET (var_id=%02x, instance=%02x, pofs=0x%x, len=%d)\n",var_id,instance,pofs,len); if (debug&DEBUG_DNAREQUESTS) fprintf(stderr,"Processing ACTION_GET (var_id=%02x, instance=%02x, pofs=0x%x, len=%d)\n",var_id,instance,pofs,len);
ofs=0; ofs=0;
if (debug>1) fprintf(stderr,"Looking for hlr entries with sid='%s' / did='%s'\n",sid?sid:"null",did?did:"null"); if (debug&DEBUG_HLR) fprintf(stderr,"Looking for hlr entries with sid='%s' / did='%s'\n",sid?sid:"null",did?did:"null");
while(1) while(1)
{ {
@ -333,9 +333,9 @@ int processRequest(unsigned char *packet,int len,
// if an empty did was passed in, get results from all hlr records // if an empty did was passed in, get results from all hlr records
if (*sid || *did){ if (*sid || *did){
if (!findHlr(hlr,&ofs,sid,did)) break; if (!findHlr(hlr,&ofs,sid,did)) break;
if (debug>1) fprintf(stderr,"findHlr found a match @ 0x%x\n",ofs); if (debug&DEBUG_HLR) fprintf(stderr,"findHlr found a match @ 0x%x\n",ofs);
} }
if (debug>2) hlrDump(hlr,ofs); if (debug&DEBUG_HLR) hlrDump(hlr,ofs);
/* XXX consider taking action on this HLR /* XXX consider taking action on this HLR
(check PIN first depending on the action requested) */ (check PIN first depending on the action requested) */
@ -346,17 +346,17 @@ int processRequest(unsigned char *packet,int len,
/* Step through HLR to find any matching instances of the requested variable */ /* Step through HLR to find any matching instances of the requested variable */
h=openhlrentry(hlr,ofs); h=openhlrentry(hlr,ofs);
if (debug>1) fprintf(stderr,"openhlrentry(hlr,%d) returned %p\n",ofs,h); if (debug&DEBUG_HLR) fprintf(stderr,"openhlrentry(hlr,%d) returned %p\n",ofs,h);
while(h) while(h)
{ {
/* Is this the variable? */ /* Is this the variable? */
if (debug>2) fprintf(stderr," considering var_id=%02x, instance=%02x\n", if (debug&DEBUG_HLR) fprintf(stderr," considering var_id=%02x, instance=%02x\n",
h->var_id,h->var_instance); h->var_id,h->var_instance);
if (h->var_id==var_id) if (h->var_id==var_id)
{ {
if (h->var_instance==instance||instance==-1) if (h->var_instance==instance||instance==-1)
{ {
if (debug>1) fprintf(stderr,"Sending matching variable value instance (instance #%d), value offset %d.\n", if (debug&DEBUG_HLR) fprintf(stderr,"Sending matching variable value instance (instance #%d), value offset %d.\n",
h->var_instance,offset); h->var_instance,offset);
// only send each value when the *next* record is found, that way we can easily stamp the last response with DONE // only send each value when the *next* record is found, that way we can easily stamp the last response with DONE
@ -372,11 +372,11 @@ int processRequest(unsigned char *packet,int len,
sendDone++; sendDone++;
} }
else else
if (debug>2) fprintf(stderr,"Ignoring variable instance %d (not %d)\n", if (debug&DEBUG_HLR) fprintf(stderr,"Ignoring variable instance %d (not %d)\n",
h->var_instance,instance); h->var_instance,instance);
} }
else else
if (debug>2) fprintf(stderr,"Ignoring variable ID %d (not %d)\n", if (debug&DEBUG_HLR) fprintf(stderr,"Ignoring variable ID %d (not %d)\n",
h->var_id,var_id); h->var_id,var_id);
h=hlrentrygetent(h); h=hlrentrygetent(h);
} }
@ -425,14 +425,14 @@ int processRequest(unsigned char *packet,int len,
break; break;
default: default:
setReason("Asked to perform unsupported action"); setReason("Asked to perform unsupported action");
if (debug) fprintf(stderr,"Packet offset = 0x%x\n",pofs); if (debug&DEBUG_PACKETFORMATS) fprintf(stderr,"Asked to perform unsipported action at Packet offset = 0x%x\n",pofs);
if (debug) dump("Packet",packet,len); if (debug&DEBUG_PACKETFORMATS) dump("Packet",packet,len);
return WHY("Asked to perform unsupported action."); return WHY("Asked to perform unsupported action.");
} }
} }
} }
if (debug>1) fprintf(stderr,"Searched %d HLR entries.\n",records_searched); if (debug&DEBUG_HLR) fprintf(stderr,"Searched %d HLR entries.\n",records_searched);
return 0; return 0;
} }
@ -476,12 +476,12 @@ int respondSimple(char *sid,int action,unsigned char *action_text,int action_len
if (action==ACTION_ERROR) packet[(*packet_len)++]=action_len; if (action==ACTION_ERROR) packet[(*packet_len)++]=action_len;
for(i=0;i<action_len;i++) packet[(*packet_len)++]=action_text[i]; for(i=0;i<action_len;i++) packet[(*packet_len)++]=action_text[i];
if (debug>2) dump("Simple response octets",action_text,action_len); if (debug&DEBUG_DNARESPONSES) dump("Simple response octets",action_text,action_len);
if (packetFinalise(packet,8000,packet_len,cryptoFlags)) if (packetFinalise(packet,8000,packet_len,cryptoFlags))
return WHY("packetFinalise() failed."); return WHY("packetFinalise() failed.");
if (debug) fprintf(stderr,"Sending response of %d bytes.\n",*packet_len); if (debug&DEBUG_DNARESPONSES) fprintf(stderr,"Sending response of %d bytes.\n",*packet_len);
if (packetSendRequest(REQ_REPLY,packet,*packet_len,NONBATCH,transaction_id,recvaddr,NULL)) if (packetSendRequest(REQ_REPLY,packet,*packet_len,NONBATCH,transaction_id,recvaddr,NULL))
return WHY("packetSendRequest() failed."); return WHY("packetSendRequest() failed.");
@ -537,7 +537,7 @@ int simpleServerMode()
fds[0].fd=sock; fds[0].events=POLLIN; fds[0].fd=sock; fds[0].events=POLLIN;
fdcount=1; fdcount=1;
rhizome_server_get_fds(fds,&fdcount,128); rhizome_server_get_fds(fds,&fdcount,128);
if (debug>2) { if (debug&DEBUG_IO) {
printf("poll()ing file descriptors:"); printf("poll()ing file descriptors:");
{ int i; { int i;
for(i=0;i<fdcount;i++) { printf(" %d",fds[i].fd); } } for(i=0;i<fdcount;i++) { printf(" %d",fds[i].fd); } }
@ -558,18 +558,18 @@ int simpleServerMode()
client_port=((struct sockaddr_in*)&recvaddr)->sin_port; client_port=((struct sockaddr_in*)&recvaddr)->sin_port;
client_addr=((struct sockaddr_in*)&recvaddr)->sin_addr; client_addr=((struct sockaddr_in*)&recvaddr)->sin_addr;
if (debug) fprintf(stderr,"Received packet from %s:%d (len=%d).\n",inet_ntoa(client_addr),client_port,len); if (debug&DEBUG_DNAREQUESTS) fprintf(stderr,"Received packet from %s:%d (len=%d).\n",inet_ntoa(client_addr),client_port,len);
if (debug>1) dump("recvaddr",(unsigned char *)&recvaddr,recvaddrlen); if (debug&DEBUG_PACKETXFER) dump("recvaddr",(unsigned char *)&recvaddr,recvaddrlen);
if (debug>3) dump("packet",(unsigned char *)buffer,len); if (debug&DEBUG_PACKETXFER) dump("packet",(unsigned char *)buffer,len);
if (dropPacketP(len)) { if (dropPacketP(len)) {
if (debug) fprintf(stderr,"Simulation mode: Dropped packet due to simulated link parameters.\n"); if (debug&DEBUG_SIMULATION) fprintf(stderr,"Simulation mode: Dropped packet due to simulated link parameters.\n");
continue; continue;
} }
/* Simple server mode doesn't really use interface numbers, so lie and say interface -1 */ /* Simple server mode doesn't really use interface numbers, so lie and say interface -1 */
if (packetOk(-1,buffer,len,NULL,&recvaddr,recvaddrlen,1)) { if (packetOk(-1,buffer,len,NULL,&recvaddr,recvaddrlen,1)) {
if (debug) setReason("Ignoring invalid packet"); if (debug&DEBUG_PACKETFORMATS) setReason("Ignoring invalid packet");
} }
if (debug>1) fprintf(stderr,"Finished processing packet, waiting for next one.\n"); if (debug&DEBUG_PACKETXFER) fprintf(stderr,"Finished processing packet, waiting for next one.\n");
} }
} }
return 0; return 0;