2 * Dolda Connect - Modular multiuser Direct Connect-style client
3 * Copyright (C) 2004 Fredrik Tolf <fredrik@dolda2000.com>
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 #include <netinet/in.h>
26 #include <arpa/inet.h>
43 #include "sysevents.h"
48 * The Direct Connect protocol is extremely ugly. Thus, this code must
49 * also be a bit ugly in certain places. Please forgive me. =/
51 * This also means that there might be some pieces of the code that
52 * look completely illogical to you, and you think that you may make
53 * them much neater/better. However, in many cases it might just be
54 * that it's required to cope with some oddity of the protocol, such
55 * as the amazingly ugly delayed key response in the peer protocol.
58 /* I assume this is the correct character set to use for DC,
59 * considering it was developed without i18n support under Windows */
60 #define DCCHARSET "windows-1252"
62 #ifdef DCPP_MASQUERADE
64 * I honestly don't want to pretend being a client that I'm not, but
65 * there are so many hubs that simply do not accept any clients
66 * outside their whitelists, for no obvious reasons, so I feel that I
67 * am left with little choice. Anyhow, as long as I actually support
68 * all the features that my faked DC++ version does, there should be
69 * very little harm done.
72 #define DCIDTAGV "0.674"
73 #define DCIDFULL "DC++ 0.674"
75 #define DCIDTAG "Dolda"
76 #define DCIDTAGV VERSION
77 #define DCIDFULL "DoldaConnect " VERSION
92 void (*handler)(struct socket *sk, void *data, char *cmd, char *args);
98 struct qcommand *next;
106 size_t inbufdata, inbufsize;
107 struct qcommand *queue;
108 int extended, dcppemu;
117 struct dcexppeer *next, *prev;
120 struct timer *expire;
125 struct dcpeer *next, *prev;
129 size_t inbufdata, inbufsize;
130 off_t curread, totalsize;
132 struct timer *timeout;
133 struct qcommand *queue;
134 struct transfer *transfer;
136 int ptclose; /* Close after transfer is complete */
137 int accepted; /* If false, we connected, otherwise, we accepted */
138 int extended, dcppemu;
139 int direction; /* Using the constants from transfer.h */
141 int hascurpos, fetchingtthl, notthl;
142 struct tigertreehash tth;
151 static struct fnet dcnet;
152 static struct transferiface dctransfer;
153 static struct socket *udpsock = NULL;
154 static struct socket *tcpsock = NULL;
155 static struct dcpeer *peers = NULL;
157 static struct dcexppeer *expected = NULL;
158 static char *hmlistname = NULL;
159 static char *xmllistname = NULL;
160 static char *xmlbz2listname = NULL;
161 static struct timer *listwritetimer = NULL;
163 static void peerconnect(struct socket *sk, int err, struct fnetnode *fn);
164 static void freedcpeer(struct dcpeer *peer);
165 static void transread(struct socket *sk, struct dcpeer *peer);
166 static void transerr(struct socket *sk, int err, struct dcpeer *peer);
167 static void transwrite(struct socket *sk, struct dcpeer *peer);
168 static void updatehmlist(void);
169 static void updatexmllist(void);
170 static void updatexmlbz2list(void);
171 static void requestfile(struct dcpeer *peer);
172 static void updatelists(int now);
174 static int reservedchar(unsigned char c)
176 return((c == 0) || (c == 5) || (c == 124) || (c == 96) || (c == 126) || (c == 36));
179 /* Oh, how I despise having to do this... */
180 static char *dcmakekey(char *lock)
186 buf = smalloc(strlen(lock));
189 for(i = 0; lock[i]; i++)
191 buf[i] = lock[i] ^ save;
192 buf[i] = ((buf[i] & 0x0F) << 4) | ((buf[i] & 0xF0) >> 4);
194 if((i != 0) && reservedchar(buf[i]))
199 buf[0] ^= buf[i - 1];
200 if(reservedchar(buf[0]))
204 key = smalloc(len + 1);
206 for(i = 0; lock[i] != 0; i++)
208 if(reservedchar(buf[i]))
209 offset += sprintf(key + offset, "/%%DCN%03i%%/", buf[i]);
211 key[offset++] = buf[i];
218 static char *pathnmdc2adc(char *path)
221 size_t retsize, retdata;
223 if(!strcmp(path, "files.xml") || !strcmp(path, "files.xml.bz2") || !strcmp(path, "MyList.DcLst"))
224 return(sstrdup(path));
226 retsize = retdata = 0;
233 addtobuf(ret, *path);
239 static int isdchash(struct hash *hash)
241 if(wcscmp(hash->algo, L"TTH"))
249 * Uncomment when used!
251 static int hubsupports(struct dchub *hub, char *cap)
255 if(hub->supports == NULL)
257 for(p = hub->supports; *p != NULL; p++)
259 if(!strcasecmp(*p, cap))
266 static int supports(struct dcpeer *peer, char *cap)
270 if(peer->supports == NULL)
272 for(p = peer->supports; *p != NULL; p++)
274 if(!strcasecmp(*p, cap))
280 static void endcompress(struct dcpeer *peer)
282 if(peer->compress == CPRS_ZLIB)
284 deflateEnd(peer->cprsdata);
285 free(peer->cprsdata);
287 peer->compress = CPRS_NONE;
290 static void initcompress(struct dcpeer *peer, int algo)
295 peer->compress = algo;
296 if(algo == CPRS_ZLIB)
298 peer->cprsdata = smalloc(sizeof(z_stream));
299 memset(peer->cprsdata, 0, sizeof(z_stream));
300 if((ret = deflateInit(peer->cprsdata, 3)) != Z_OK)
302 flog(LOG_CRIT, "Aiya! zlib refuses to init (%i)!", ret);
308 static void unquote(wchar_t *in)
312 for(p = in; *p != L'\0'; p++)
316 for(p2 = p + 1; (*p2 != L'\0') && (*p2 != L';') && (*p2 != L'&'); p2++);
323 if(!wcscmp(p + 1, L"amp"))
326 } else if(p[1] == L'#') {
327 nc = ucptowc(wcstol(p + 2, NULL, 10));
336 memmove(p + 1, p2 + 1, (wcslen(p2 + 1) + 1) * sizeof(wchar_t));
341 static void freeexppeer(struct dcexppeer *ep)
344 ep->next->prev = ep->prev;
346 ep->prev->next = ep->next;
351 if(ep->expire != NULL)
352 canceltimer(ep->expire);
356 static void exppeerexpire(int cancelled, struct dcexppeer *ep)
363 static struct dcexppeer *expectpeer(char *nick, struct fnetnode *fn)
365 struct dcexppeer *ep;
367 ep = smalloc(sizeof(*ep));
368 ep->nick = sstrdup(nick);
369 getfnetnode(ep->fn = fn);
370 ep->expire = timercallback(ntime() + 300, (void (*)(int, void *))exppeerexpire, ep);
379 static struct qcommand *newqcmd(struct qcommand **queue, char *string)
381 struct qcommand *new;
383 while(*queue != NULL)
384 queue = &(*queue)->next;
385 new = smalloc(sizeof(*new));
386 new->string = sstrdup(string);
392 static struct qcommand *ulqcmd(struct qcommand **queue)
394 struct qcommand *qcmd;
396 if((qcmd = *queue) == NULL)
402 static void freeqcmd(struct qcommand *qcmd)
408 static void hubrecvchat(struct socket *sk, struct fnetnode *fn, char *from, char *string)
410 wchar_t *chat, *wfrom, *wpeer;
412 struct fnetpeer *peer;
416 end = string + strlen(string);
417 while((p = strchr(string, 13)) != NULL)
418 memmove(p, p + 1, (end-- - p));
421 if((strlen(string) > strlen(from) + 2) && (*string == '<') && !memcmp(string + 1, from, strlen(from)) && (*(string + strlen(from) + 1) == '>'))
422 string += strlen(from) + 2;
423 if((wfrom = icmbstowcs(from, hub->charset)) == NULL)
425 wpeer = swcsdup(wfrom);
431 for(p = string + 1; *p; p++)
433 if((*p == ' ') || (*p == '>'))
441 if((wpeer = icmbstowcs(string + 1, hub->charset)) == NULL)
447 wpeer = swcsdup(L"");
449 if((chat = icmbstowcs(string, hub->charset)) == NULL)
459 if((peer = fnetfindpeer(fn, wfrom)) == NULL) /* Assume public chat */
460 fnethandlechat(fn, 1, wfrom, wpeer, chat);
462 fnethandlechat(fn, 0, wfrom, wpeer, chat);
464 fnethandlechat(fn, 1, L"", wpeer, chat);
472 static void peertimeout(int cancelled, struct dcpeer *peer)
474 peer->timeout = NULL;
480 static void sendadc(struct socket *sk, char *arg)
483 size_t bufsize, bufdata;
486 bufsize = bufdata = 0;
492 bufcat(buf, "\\s", 2);
493 } else if(*arg == '\n') {
494 bufcat(buf, "\\n", 2);
495 } else if(*arg == '\\') {
496 bufcat(buf, "\\\\", 2);
501 sockqueue(sk, buf, bufdata);
505 #if defined(__GNUC__)
506 static void __attribute__ ((format (printf, 2, 3))) sendadcf(struct socket *sk, char *arg, ...)
508 static void sendadcf(struct socket *sk, char *arg, ...)
515 buf = vsprintf2(arg, args);
523 static char **parseadc(char *args)
526 size_t retbufsize, retbufdata;
528 size_t bufsize, bufdata;
533 retbufsize = retbufdata = bufsize = bufdata = 0;
542 else if(*args != ' ')
546 if((*args == ' ') || (*args == 0))
549 addtobuf(retbuf, buf);
551 bufsize = bufdata = 0;
554 } else if(*args == '\\') {
557 addtobuf(buf, *args);
566 addtobuf(retbuf, NULL);
569 } else if((*args == 's') || (*args == ' ')) {
571 } else if(*args == 'n') {
573 } else if(*args == '\\') {
583 addtobuf(retbuf, NULL);
587 /* Macros useful in command handlers */
588 #define skipspace(s) ({if(((s) = strchr((s), ' ')) == NULL) return; else (s)++;})
589 #define qstr(sk, str) sockqueue(sk, str, strlen(str))
590 #define qstrf(sk, strandargs...) \
593 if((__buf__ = sprintf2(strandargs)) != NULL) { \
594 sockqueue(sk, __buf__, strlen(__buf__)); \
599 static char *tr(char *str, char *trans)
603 for(; *trans; trans += 2)
605 for(p = strchr(str, trans[0]); p != NULL; p = strchr(p, trans[0]))
611 static char *getadcid(struct dcpeer *peer)
618 if(!wcscmp(peer->transfer->path, L"files.xml") || !wcscmp(peer->transfer->path, L"files.xml.bz2") || !wcscmp(peer->transfer->path, L"MyList.DcLst"))
620 if(!isfilelist && (peer->transfer->hash != NULL) && isdchash(peer->transfer->hash) && supports(peer, "tthf"))
622 buf = base32encode(peer->transfer->hash->buf, 24);
623 ret = sprintf2("TTH/%.39s", buf);
626 if((buf = icwcstombs(peer->transfer->path, "UTF-8")) == NULL)
628 ret = pathnmdc2adc(buf);
635 static int trresumecb(struct transfer *transfer, wchar_t *cmd, wchar_t *arg, struct dcpeer *peer)
637 if(!wcscmp(cmd, L"resume"))
641 flog(LOG_WARNING, "filter returned no position for \"resume\" on transfer %i", transfer->id);
644 transfer->curpos = wcstoll(arg, NULL, 10);
653 static void sendmynick(struct dcpeer *peer)
659 qstrf(peer->sk, "$MyNick %s|", icswcstombs(confgetstr("cli", "defnick"), peer->charset, "DoldaConnectUser-IN"));
661 qstrf(peer->sk, "$MyNick %s|", icswcstombs(fn->mynick, peer->charset, "DoldaConnectUser-IN"));
664 static void sendpeerlock(struct dcpeer *peer)
667 qstrf(peer->sk, "$Lock EXTENDEDPROTOCOLABCABCABCABCABCABC Pk=DCPLUSPLUS0.674ABCABC|");
669 qstrf(peer->sk, "$Lock EXTENDEDPROTOCOLABCABCABCABCABCABC Pk=DOLDA%sABCABCABC|", VERSION);
672 static void sendsupports(struct dcpeer *peer)
675 qstr(peer->sk, "$Supports MiniSlots XmlBZList ADCGet TTHL TTHF GetZBlock ZLIG |");
677 qstr(peer->sk, "$Supports MiniSlots XmlBZList ADCGet TTHL TTHF");
678 if(!confgetint("dc", "hidedeflate"))
679 qstr(peer->sk, " GetZBlock ZLIG");
684 static void requestfile(struct dcpeer *peer)
688 if(peer->transfer->size == -1)
690 /* Use DCCHARSET for $Get paths until further researched... */
691 if((buf = icswcstombs(peer->transfer->path, DCCHARSET, NULL)) == NULL)
693 transferseterror(peer->transfer, TRNSE_NOTFOUND);
697 /* The transfer will be restarted later from
698 * cmd_filelength when it detects that the sizes
700 qstrf(peer->sk, "$Get %s$1|", buf);
703 if((peer->transfer->hash == NULL) && !peer->notthl)
705 if(supports(peer, "adcget") && supports(peer, "tthl"))
707 qstr(peer->sk, "$ADCGET");
708 sendadc(peer->sk, "tthl");
709 if((buf = getadcid(peer)) == NULL)
711 transferseterror(peer->transfer, TRNSE_NOTFOUND);
715 sendadc(peer->sk, buf);
717 sendadc(peer->sk, "0");
718 sendadc(peer->sk, "-1");
720 peer->fetchingtthl = 1;
726 if(forkfilter(peer->transfer))
728 flog(LOG_WARNING, "could not fork filter for transfer %i: %s", peer->transfer->id, strerror(errno));
732 CBREG(peer->transfer, trans_filterout, (int (*)(struct transfer *, wchar_t *, wchar_t *, void *))trresumecb, NULL, peer);
735 if(supports(peer, "adcget"))
737 qstr(peer->sk, "$ADCGET");
738 sendadc(peer->sk, "file");
739 if((buf = getadcid(peer)) == NULL)
741 transferseterror(peer->transfer, TRNSE_NOTFOUND);
745 sendadc(peer->sk, buf);
747 sendadcf(peer->sk, "%ji", (intmax_t)peer->transfer->curpos);
748 sendadcf(peer->sk, "%ji", (intmax_t)(peer->transfer->size - peer->transfer->curpos));
750 } else if(supports(peer, "xmlbzlist")) {
751 if((buf = icswcstombs(peer->transfer->path, "UTF-8", NULL)) == NULL)
753 transferseterror(peer->transfer, TRNSE_NOTFOUND);
757 qstrf(peer->sk, "$UGetBlock %ji %ji %s|", (intmax_t)peer->transfer->curpos, (intmax_t)(peer->transfer->size - peer->transfer->curpos), buf);
759 /* Use DCCHARSET for $Get paths until further researched... */
760 if((buf = icswcstombs(peer->transfer->path, DCCHARSET, NULL)) == NULL)
762 transferseterror(peer->transfer, TRNSE_NOTFOUND);
766 qstrf(peer->sk, "$Get %s$%ji|", buf, (intmax_t)peer->transfer->curpos + 1);
770 static void sendmyinfo(struct socket *sk, struct fnetnode *fn)
774 struct fnetnode *cfn;
778 qstrf(sk, "$MyINFO $ALL %s ", hub->nativenick);
779 buf = tr(icswcstombs(confgetstr("dc", "desc"), hub->charset, "Charset_conv_failure"), "$_|_");
780 qstrf(sk, "%s", buf);
782 for(cfn = fnetnodes; cfn != NULL; cfn = cfn->next)
784 if((cfn->state == FNN_EST) || (cfn->state == FNN_HS))
786 if(cfn->regstatus == FNNS_OP)
788 else if(cfn->regstatus == FNNS_REG)
794 qstrf(sk, "<%s V:%s,M:%c,H:%i/%i/%i,S:%i>",
795 (hub->dcppemu)?"++":"Dolda",
796 (hub->dcppemu)?"0.674":VERSION,
797 (tcpsock == NULL)?'P':'A',
799 confgetint("transfer", "slots")
802 buf = tr(icswcstombs(confgetstr("dc", "speedstring"), hub->charset, "Charset_conv_failure"), "$_|_");
803 qstrf(sk, "%s\x01$", buf);
804 buf = tr(icswcstombs(confgetstr("dc", "email"), hub->charset, "Charset_conv_failure"), "$_|_");
805 qstrf(sk, "%s$", buf);
806 qstrf(sk, "%llu$|", sharesize);
809 static void hubhandleaction(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
814 if(!strcmp(cmd, "$Lock"))
816 qstrf(sk, "$ValidateNick %s|", hub->nativenick);
817 } else if(!strcmp(cmd, "$Hello")) {
818 if(fn->state == FNN_HS)
820 qstrf(sk, "$Version 1,0091|");
821 qstrf(sk, "$GetNickList|");
823 fnetsetstate(fn, FNN_EST);
825 qstrf(sk, "$GetINFO %s %s|", args, hub->nativenick);
830 static void cmd_lock(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
837 if(!strncmp(args, "EXTENDEDPROTOCOL", 16))
839 if((p = strchr(args, ' ')) != NULL)
844 qstrf(sk, "$Supports UserCommand NoGetINFO NoHello UserIP2 TTHSearch GetZBlock |");
846 qstrf(sk, "$Supports UserCommand NoGetINFO NoHello UserIP2 TTHSearch");
847 if(!confgetint("dc", "hidedeflate"))
848 qstr(sk, " GetZBlock");
852 key = dcmakekey(args);
853 qstrf(sk, "$Key %s|", key);
855 hubhandleaction(sk, fn, cmd, args);
858 static void cmd_hubname(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
864 if(hub->nativename == NULL)
865 free(hub->nativename);
866 hub->nativename = sstrdup(args);
867 buf = icmbstowcs(args, hub->charset);
868 fnetsetname(fn, (buf == NULL)?L"Hubname conv error":buf);
871 hubhandleaction(sk, fn, cmd, args);
874 static void cmd_hello(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
880 if((nick = icmbstowcs(args, hub->charset)) == NULL)
882 if(strcmp(args, hub->nativenick) && (fnetfindpeer(fn, nick) == NULL))
883 fnetaddpeer(fn, nick, nick);
885 hubhandleaction(sk, fn, cmd, args);
888 static void cmd_quit(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
891 struct fnetpeer *peer;
895 if((nick = icmbstowcs(args, hub->charset)) == NULL)
897 if((peer = fnetfindpeer(fn, nick)) != NULL)
900 hubhandleaction(sk, fn, cmd, args);
903 static void cmd_nicklist(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
908 struct fnetpeer *peer, *npeer;
911 for(peer = fn->peers; peer != NULL; peer = peer->next)
912 peer->flags.b.delete = 1;
913 while((p = strstr(args, "$$")) != NULL)
916 if((buf = icmbstowcs(args, hub->charset)) != NULL)
918 if((peer = fnetfindpeer(fn, buf)) == NULL)
919 peer = fnetaddpeer(fn, buf, buf);
921 peer->flags.b.delete = 0;
923 qstrf(sk, "$GetINFO %s %s|", args, hub->nativenick);
927 for(peer = fn->peers; peer != NULL; peer = npeer)
930 if(peer->flags.b.delete)
933 hubhandleaction(sk, fn, cmd, args);
936 static void cmd_oplist(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
941 struct fnetpeer *peer;
944 for(peer = fn->peers; peer != NULL; peer = peer->next)
945 peer->flags.b.op = 0;
946 while((p = strstr(args, "$$")) != NULL)
949 if((buf = icmbstowcs(args, hub->charset)) != NULL)
951 if((peer = fnetfindpeer(fn, buf)) != NULL)
952 peer->flags.b.op = 1;
957 hubhandleaction(sk, fn, cmd, args);
960 static void cmd_myinfo(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
963 wchar_t *buf, *wp, *wp2;
965 struct fnetpeer *peer;
970 if(strncmp(p, "$ALL ", 5))
973 if((p2 = strchr(p, ' ')) == NULL)
976 if((buf = icmbstowcs(p, hub->charset)) == NULL)
978 if((peer = fnetfindpeer(fn, buf)) == NULL)
979 peer = fnetaddpeer(fn, buf, buf);
982 if((p2 = strstr(p, "$ $")) == NULL)
985 if((buf = icmbstowcs(p, hub->charset)) == NULL)
987 if((wcslen(buf) > 0) && (buf[wcslen(buf) - 1] == L'>') && ((wp = wcsrchr(buf, L'<')) != NULL))
989 buf[wcslen(buf) - 1] = L'\0';
991 if((wp2 = wcschr(wp, L' ')) != NULL)
994 fnetpeersetstr(peer, L"dc-client", wp);
998 if((wp2 = wcschr(wp, L',')) != NULL)
1002 swprintf(abuf, 10, L"dc-tag-%lc", wp[0]);
1003 fnetpeersetstr(peer, abuf, wp + 2);
1005 } while(wp2 != NULL);
1008 fnetpeersetstr(peer, L"descr", buf);
1011 if((p2 = strchr(p, '$')) == NULL)
1014 if((buf = icmbstowcs(p, hub->charset)) == NULL)
1016 fnetpeersetstr(peer, L"dc-speed", buf);
1019 if((p2 = strchr(p, '$')) == NULL)
1022 if((buf = icmbstowcs(p, hub->charset)) == NULL)
1024 fnetpeersetstr(peer, L"email", buf);
1029 fnetpeersetlnum(peer, L"share", strtoll(p, NULL, 10));
1030 hubhandleaction(sk, fn, cmd, args);
1033 /* I do not implement the fully in that I do not disconnect from the
1034 * old hub. I do this since I believe that if the hub owner really
1035 * wants to get rid of us, then it is his responsibility to disconnect
1037 static void cmd_forcemove(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1040 struct fnetnode *newfn;
1044 if(strchr(args, ':') == NULL)
1046 args = strcpy(smalloc(strlen(args) + 5), args);
1047 strcat(args, ":411");
1052 if((newfn = fnetinitconnect(L"dc", fn->owner, args, NULL)) != NULL)
1054 linkfnetnode(newfn);
1057 hubhandleaction(sk, fn, cmd, args);
1062 static char *getdcpath(struct sharecache *node, size_t *retlen, char *charset)
1067 if(node->parent == NULL)
1069 if(node->parent == shareroot)
1071 if((buf = icwcstombs(node->name, charset)) == NULL)
1074 *retlen = strlen(buf);
1077 if((buf2 = icwcstombs(node->name, charset)) == NULL)
1079 if((buf = getdcpath(node->parent, &len, charset)) == NULL)
1084 len2 = strlen(buf2);
1085 buf = srealloc(buf, len + 1 + len2 + 1);
1087 strcpy(buf + len, buf2);
1088 buf[len + len2] = 0;
1091 *retlen = len + len2;
1097 * This is the main share searching function for Direct Connect
1098 * peers. Feel free to optimize it if you feel the need for it. I
1099 * haven't ever seen it take any noticable CPU time anyway, so I
1100 * haven't felt that need.
1102 * It may feel dubious to just return the directory when all terms are
1103 * satisfied rather than all the files in it, but it really benefits
1104 * everyone: Less cycles used for us, less UDP squelching for active
1105 * searchers, and less bandwidth waste for hubs when serving passive
1108 static void cmd_search(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1113 char *prefix, *infix, *postfix, *buf, *buf2;
1115 struct sockaddr_in addr;
1116 struct sharecache *node;
1117 int minsize, maxsize;
1120 int termnum, satisfied, skipcheck;
1121 int level, tersat[32];
1126 if((p = strchr(args, ' ')) == NULL)
1130 memset(terms, 0, sizeof(terms));
1131 prefix = infix = postfix = NULL;
1135 if(!strncmp(args, "Hub:", 4))
1137 if(!strcmp(cmd, "$MultiSearch"))
1139 if(!strcmp(args + 4, hub->nativenick))
1141 prefix = sprintf2("$SR %s ", hub->nativenick);
1142 infix = sprintf2(" %i/%i\005", slotsleft(), confgetint("transfer", "slots"));
1143 postfix = sprintf2(" (%s)\005%s|", formataddress(hub->sk->remote, hub->sk->remotelen), args + 4);
1147 if((p2 = strchr(args, ':')) == NULL)
1150 addr.sin_family = AF_INET;
1151 if(!inet_aton(args, &addr.sin_addr))
1153 addr.sin_port = htons(atoi(p2));
1154 prefix = sprintf2("$SR %s ", hub->nativenick);
1155 infix = sprintf2(" %i/%i\005", slotsleft(), confgetint("transfer", "slots"));
1156 postfix = sprintf2(" (%s)|", formataddress(hub->sk->remote, hub->sk->remotelen));
1157 netdgramconn(dsk = netdupsock(udpsock), (struct sockaddr *)&addr, sizeof(addr));
1160 minsize = maxsize = -1;
1169 if((*(p++) == 'T') && (minsize == 0))
1176 if((p2 = strchr(p, '?')) == NULL)
1191 if((*p2 == 0) || (*p2 == '$'))
1199 if(!dotth && !strncmp(p, "TTH:", 4))
1202 if(((buf = base32decode(p + 4, &buflen)) == NULL) || (buflen != 24))
1207 memcpy(hashtth, buf, 24);
1210 if((terms[termnum] = icmbstowcs(p, hub->charset)) != NULL)
1221 node = shareroot->child;
1223 for(i = 0; i < termnum; i++)
1229 if(node->f.b.type == FILE_REG)
1231 if((minsize >= 0) && (node->size < minsize))
1233 if((maxsize >= 0) && (node->size > maxsize))
1236 if(!skipcheck && dotth)
1238 if((node->f.b.type != FILE_REG) || (node->f.b.hastth && memcmp(hashtth, node->hashtth, 24)))
1243 for(i = 0; i < termnum; i++)
1247 if(wcsexists(node->name, terms[i]))
1251 } else if(node->child == NULL) {
1256 if(!skipcheck && (satisfied == termnum))
1258 /* Use DCCHARSET in $Get paths until further researched... */
1259 if((buf = getdcpath(node, NULL, DCCHARSET)) != NULL)
1261 if(node->f.b.hastth)
1263 buf2 = base32encode(node->hashtth, 24);
1264 qstrf(dsk, "%s%s\005%ji%sTTH:%.39s%s", prefix, buf, (intmax_t)node->size, infix, buf2, postfix);
1267 qstrf(dsk, "%s%s\005%ji%s%s%s", prefix, buf, (intmax_t)node->size, infix, hub->nativename, postfix);
1272 if((!skipcheck && (satisfied == termnum)) || (node->child == NULL))
1274 while(node->next == NULL)
1276 if((node = node->parent) == shareroot)
1280 if(node == shareroot)
1282 for(i = 0; i < termnum; i++)
1284 if(tersat[i] >= level)
1297 hubhandleaction(sk, fn, cmd, args);
1308 for(i = 0; (i < 32) && (terms[i] != NULL); i++)
1312 static void cmd_connecttome(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1316 struct socket *newsk;
1317 struct sockaddr_in addr;
1320 if((p = strchr(args, ' ')) == NULL)
1323 if(strcmp(args, hub->nativenick))
1325 addr.sin_family = AF_INET;
1327 if((p = strchr(args, ':')) == NULL)
1330 addr.sin_port = htons(atoi(p));
1331 if(!inet_aton(args, &addr.sin_addr))
1333 newsk = netcsconn((struct sockaddr *)&addr, sizeof(addr), (void (*)(struct socket *, int, void *))peerconnect, fn);
1335 hubhandleaction(sk, fn, cmd, args);
1338 static void sendctm(struct socket *sk, char *nick)
1340 struct sockaddr *addr;
1345 if(sockgetremotename2(tcpsock, sk, &addr, &addrlen) < 0)
1347 if(addr->sa_family == AF_INET)
1348 qstrf(sk, "$ConnectToMe %s %s|", nick, formataddress(addr, addrlen));
1350 flog(LOG_WARNING, "Direct Connect TCP socket is suddenly not AF_INET, but %i", addr->sa_family);
1354 static void cmd_revconnecttome(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1360 if((p = strchr(args, ' ')) == NULL)
1363 if(strcmp(p, hub->nativenick))
1366 expectpeer(args, fn);
1367 hubhandleaction(sk, fn, cmd, args);
1370 static void cmd_getnetinfo(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1373 struct fnetnode *node;
1378 for(node = fnetnodes; node != NULL; node = node->next)
1380 if(node->state == FNN_EST)
1383 qstrf(sk, "$NetInfo %i$%i$%c$0|", confgetint("transfer", "slots"), numhubs, (tcpsock == NULL)?'P':'A');
1384 hubhandleaction(sk, fn, cmd, args);
1387 static void cmd_to(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1394 if((p2 = strchr(p, ' ')) == NULL)
1398 if((p2 = strchr(p, ' ')) == NULL)
1401 if(strcmp(p, "From:"))
1404 if((p2 = strstr(p, " $")) == NULL)
1408 hubrecvchat(hub->sk, fn, p, p2);
1409 hubhandleaction(sk, fn, cmd, args);
1412 static void cmd_sr(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1416 char *nick, *filename, *hubname;
1421 wchar_t *wnick, *wfile;
1425 if((p2 = strchr(p, ' ')) == NULL)
1430 if((p2 = strchr(p, 5)) == NULL)
1434 if((p2 = strchr(p, ' ')) == NULL)
1437 size = strtoll(p, NULL, 10);
1439 if((p2 = strchr(p, '/')) == NULL)
1444 if((p2 = strchr(p, 5)) == NULL)
1448 if((p2 = strstr(p, " (")) == NULL)
1451 if((wnick = icmbstowcs(nick, hub->charset)) == NULL)
1453 /* Use DCCHARSET in $Get paths until further researched... */
1454 if((wfile = icmbstowcs(filename, DCCHARSET)) == NULL)
1459 sr = newsrchres(&dcnet, wfile, wnick);
1460 if(sr->peernick != NULL)
1462 sr->peernick = swcsdup(wnick);
1467 if(!strncmp(hubname, "TTH:", 4))
1469 if((buf = base32decode(hubname + 4, &buflen)) != NULL)
1472 sr->hash = newhash(L"TTH", 24, buf);
1476 getfnetnode(sr->fn = fn);
1479 hubhandleaction(sk, fn, cmd, args);
1482 static void cmd_usercommand(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1484 /* Do nothing for now. */
1487 static void cmd_getpass(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1494 pw = wpfind(fn->args, L"password");
1495 if((pw == NULL) || ((mbspw = icwcstombs(pw, hub->charset)) == NULL))
1500 qstrf(sk, "$MyPass %s|", mbspw);
1502 fn->regstatus = FNNS_REG;
1503 hubhandleaction(sk, fn, cmd, args);
1506 static void cmd_logedin(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1511 fn->regstatus = FNNS_OP;
1512 hubhandleaction(sk, fn, cmd, args);
1515 static void cmd_hubsupports(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1521 size_t arrsize, arrdata;
1524 if(hub->supports != NULL)
1526 for(i = 0; hub->supports[i] != NULL; i++)
1527 free(hub->supports[i]);
1528 free(hub->supports);
1531 arrsize = arrdata = 0;
1535 if((p2 = strchr(p, ' ')) != NULL)
1539 addtobuf(arr, sstrdup(p));
1540 } while((p = p2) != NULL);
1541 addtobuf(arr, NULL);
1542 hub->supports = arr;
1545 static void cmd_mynick(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1547 struct dcexppeer *expect;
1550 if(peer->nativename != NULL)
1551 free(peer->nativename);
1552 peer->nativename = sstrdup(args);
1553 if(peer->wcsname != NULL)
1554 free(peer->wcsname);
1555 if((peer->wcsname = icmbstowcs(peer->nativename, peer->charset)) == NULL)
1562 for(expect = expected; expect != NULL; expect = expect->next)
1564 if(!strcmp(expect->nick, args))
1571 hub = expect->fn->data;
1572 peer->fn = expect->fn;
1573 getfnetnode(peer->fn);
1574 peer->dcppemu = hub->dcppemu;
1575 freeexppeer(expect);
1580 static void cmd_direction(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1584 struct transfer *transfer;
1586 if((p = strchr(args, ' ')) == NULL)
1589 if(!strcmp(args, "Upload"))
1591 if(!strcmp(args, "Download"))
1595 if((peer->transfer == NULL) || (mydir != peer->direction))
1600 if(peer->direction == TRNSD_DOWN)
1603 if(peer->wcsname == NULL)
1608 peer->direction = mydir;
1609 if(peer->direction == TRNSD_UP)
1611 if(confgetint("transfer", "ulquota") && hasupload(&dcnet, peer->wcsname))
1616 transfer = newupload(peer->fn, &dcnet, peer->wcsname, &dctransfer, peer);
1618 if((transfer = finddownload(peer->wcsname)) == NULL)
1623 transferattach(transfer, &dctransfer, peer);
1624 transfersetstate(transfer, TRNS_HS);
1626 transfersetnick(transfer, peer->wcsname);
1627 peer->transfer = transfer;
1630 qstrf(sk, "$Direction %s %i|", (peer->direction == TRNSD_UP)?"Upload":"Download", rand() % 10000);
1631 if(peer->key != NULL)
1632 qstrf(sk, "$Key %s|", peer->key);
1633 if(peer->direction == TRNSD_DOWN)
1638 static void cmd_peerlock(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1641 struct transfer *transfer;
1643 if((p = strchr(args, ' ')) == NULL)
1646 if(!strncmp(args, "EXTENDEDPROTOCOL", 16))
1648 key = dcmakekey(args);
1651 if(peer->wcsname == NULL)
1660 if((transfer = finddownload(peer->wcsname)) == NULL)
1662 if(confgetint("transfer", "ulquota") && hasupload(&dcnet, peer->wcsname))
1667 peer->direction = TRNSD_UP;
1668 transfer = newupload(peer->fn, &dcnet, peer->wcsname, &dctransfer, peer);
1670 peer->direction = TRNSD_DOWN;
1671 transferattach(transfer, &dctransfer, peer);
1672 transfersetstate(transfer, TRNS_HS);
1674 transfersetnick(transfer, peer->wcsname);
1675 peer->transfer = transfer;
1676 qstrf(sk, "$Direction %s %i|", (peer->direction == TRNSD_UP)?"Upload":"Download", rand() % 10000);
1677 qstrf(sk, "$Key %s|", key);
1680 if(peer->key != NULL)
1686 static void cmd_key(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1691 static void startdl(struct dcpeer *peer)
1693 if(peer->timeout != NULL)
1694 canceltimer(peer->timeout);
1695 peer->state = PEER_TRNS;
1696 transferstartdl(peer->transfer, peer->sk);
1697 peer->sk->readcb = (void (*)(struct socket *, void *))transread;
1698 peer->sk->errcb = (void (*)(struct socket *, int, void *))transerr;
1701 static void startul(struct dcpeer *peer)
1703 if(peer->timeout != NULL)
1704 canceltimer(peer->timeout);
1705 peer->state = PEER_TRNS;
1706 transferstartul(peer->transfer, peer->sk);
1707 peer->sk->writecb = (void (*)(struct socket *, void *))transwrite;
1710 static void cmd_filelength(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1713 struct transfer *transfer;
1715 if(peer->transfer == NULL)
1720 size = strtoll(args, NULL, 10);
1721 if(peer->transfer->size != size)
1723 transfersetsize(peer->transfer, size);
1724 transfer = peer->transfer;
1726 trytransferbypeer(transfer->fnet, transfer->peerid);
1730 qstr(peer->sk, "$Send|");
1733 static void cmd_error(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1735 if(peer->fetchingtthl)
1737 peer->fetchingtthl = 0;
1742 if((peer->transfer != NULL) && (peer->transfer->dir == TRNSD_DOWN))
1744 transferseterror(peer->transfer, TRNSE_NOTFOUND);
1745 resettransfer(peer->transfer);
1751 static void cmd_maxedout(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1753 if((peer->transfer != NULL) && (peer->transfer->dir == TRNSD_DOWN))
1755 transferseterror(peer->transfer, TRNSE_NOSLOTS);
1756 resettransfer(peer->transfer);
1769 {"MyList.DcLst", &hmlistname, updatehmlist},
1770 {"files.xml", &xmllistname, updatexmllist},
1771 {"files.xml.bz2", &xmlbz2listname, updatexmlbz2list},
1775 static int openfilelist(char *name)
1780 for(i = 0; lists[i].name != NULL; i++)
1782 if(!strcmp(name, lists[i].name))
1786 if(lists[i].name == NULL)
1789 if((*lists[i].file == NULL) || ((fd = open(*lists[i].file, O_RDONLY)) < 0))
1791 if((fd < 0) && ((*lists[i].file == NULL) || ((fd = open(*lists[i].file, O_RDONLY)) < 0)))
1794 flog(LOG_ERR, "could not open filelist tempfile: %s", strerror(errno));
1801 static struct sharecache *findbytth(char *tth32)
1805 struct sharecache *node;
1807 if((buf = base32decode(tth32, &buflen)) == NULL)
1814 for(node = shareroot->child; node != NULL; node = nextscnode(node))
1816 if(node->f.b.hastth && !memcmp(node->hashtth, buf, 24))
1823 static struct sharecache *resdcpath(char *path, char *charset, char sep)
1825 struct sharecache *node;
1832 if((p2 = strchr(p, sep)) != NULL)
1834 if((node = findcache(node, icsmbstowcs(p, charset, L""))) == NULL)
1841 static void cmd_get(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1846 struct sharecache *node;
1847 struct socket *lesk;
1851 if(peer->transfer == NULL)
1856 if((p = strchr(args, '$')) == NULL)
1862 if((offset = (strtoll(p, NULL, 10) - 1)) < 0)
1867 if(((fd = openfilelist(args)) < 0) && (errno != 0))
1869 qstr(sk, "$Error Could not send file list|");
1872 } else if(fd >= 0) {
1873 if((buf2 = icsmbstowcs(args, DCCHARSET, NULL)) != NULL)
1874 transfersetpath(peer->transfer, buf2);
1875 peer->transfer->flags.b.minislot = 1;
1879 /* Use DCCHARSET in $Get paths until further researched... */
1880 if((node = resdcpath(args, DCCHARSET, '\\')) == NULL)
1882 qstrf(sk, "$Error File not in share|");
1886 if((fd = opensharecache(node)) < 0)
1888 qstrf(sk, "$Error %s|", strerror(errno));
1892 buf = getfspath(node);
1893 if((buf2 = icsmbstowcs(buf, NULL, NULL)) == NULL)
1894 flog(LOG_WARNING, "could not convert native path into a wcs (%s): %s", buf, strerror(errno));
1896 transfersetpath(peer->transfer, buf2);
1899 if(fstat(fd, &sb) < 0)
1902 flog(LOG_WARNING, "could not stat file %ls: %s", node->name, strerror(errno));
1903 qstrf(sk, "$Error|");
1907 if(sb.st_size < 65536)
1908 peer->transfer->flags.b.minislot = 1;
1909 if(!peer->transfer->flags.b.minislot && (slotsleft() < 1)) {
1911 qstr(sk, "$MaxedOut|");
1915 if((offset != 0) && (lseek(fd, offset, SEEK_SET) < 0))
1918 qstrf(sk, "$Error Offset out of range|");
1922 lesk = wrapsock(fd);
1923 transferprepul(peer->transfer, sb.st_size, offset, -1, lesk);
1925 qstrf(sk, "$FileLength %ji|", (intmax_t)peer->transfer->size);
1928 static void cmd_send(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1930 if(peer->transfer == NULL)
1935 if(peer->transfer->localend == NULL)
1944 static void cmd_supports(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1949 size_t arrsize, arrdata;
1951 if(peer->supports != NULL)
1953 for(i = 0; peer->supports[i] != NULL; i++)
1954 free(peer->supports[i]);
1955 free(peer->supports);
1958 arrsize = arrdata = 0;
1962 if((p2 = strchr(p, ' ')) != NULL)
1966 addtobuf(arr, sstrdup(p));
1967 } while((p = p2) != NULL);
1968 addtobuf(arr, NULL);
1969 peer->supports = arr;
1972 static void cmd_getblock(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1976 off_t start, numbytes;
1977 char *charset, *buf;
1979 struct sharecache *node;
1981 struct socket *lesk;
1983 if(peer->transfer == NULL)
1989 if((p2 = strchr(p, ' ')) == NULL)
1995 start = strtoll(p, NULL, 10);
1997 if((p2 = strchr(p, ' ')) == NULL)
2003 numbytes = strtoll(p, NULL, 10);
2005 if(!strcmp(cmd, "$UGetBlock") || !strcmp(cmd, "$UGetZBlock"))
2008 /* Use DCCHARSET in $Get paths until further researched... */
2009 charset = DCCHARSET;
2010 if(!strcmp(cmd, "$GetZBlock") || !strcmp(cmd, "$UGetZBlock"))
2011 initcompress(peer, CPRS_ZLIB);
2012 if(((fd = openfilelist(p)) < 0) && (errno != 0))
2014 qstr(sk, "$Error Could not send file list|");
2016 } else if(fd >= 0) {
2017 if((buf2 = icsmbstowcs(args, charset, NULL)) != NULL)
2018 transfersetpath(peer->transfer, buf2);
2019 peer->transfer->flags.b.minislot = 1;
2023 if((node = resdcpath(p, charset, '\\')) == NULL)
2025 qstr(sk, "$Error File not in cache|");
2028 if((fd = opensharecache(node)) < 0)
2030 qstrf(sk, "$Error %s|", strerror(errno));
2033 buf = getfspath(node);
2034 if((buf2 = icsmbstowcs(buf, NULL, NULL)) == NULL)
2035 flog(LOG_WARNING, "could not convert native path into a wcs (%s): %s", buf, strerror(errno));
2037 transfersetpath(peer->transfer, buf2);
2040 if(fstat(fd, &sb) < 0)
2043 flog(LOG_WARNING, "could not stat file %ls: %s", node->name, strerror(errno));
2044 qstr(sk, "$Error|");
2047 if(sb.st_size < 65536)
2048 peer->transfer->flags.b.minislot = 1;
2049 if(!peer->transfer->flags.b.minislot && (slotsleft() < 1)) {
2051 qstr(sk, "$MaxedOut|");
2054 if((start != 0) && ((start >= sb.st_size) || (lseek(fd, start, SEEK_SET) < 0)))
2057 qstr(sk, "$Error Offset out of range|");
2060 if((numbytes < 0) || (start + numbytes > sb.st_size))
2061 numbytes = sb.st_size - start;
2062 lesk = wrapsock(fd);
2063 transferprepul(peer->transfer, sb.st_size, start, start + numbytes, lesk);
2065 qstrf(sk, "$Sending %ji|", (intmax_t)numbytes);
2069 static void cmd_adcget(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2073 off_t start, numbytes;
2074 struct sharecache *node;
2076 struct socket *lesk;
2080 if(peer->transfer == NULL)
2085 if((argv = parseadc(args)) == NULL)
2090 if(parrlen(argv) < 4)
2095 start = strtoll(argv[2], NULL, 10);
2096 numbytes = strtoll(argv[3], NULL, 10);
2099 if(((fd = openfilelist(argv[1])) < 0) && (errno != 0))
2101 qstr(sk, "$Error Could not send file list|");
2103 } else if(fd >= 0) {
2104 if((wbuf = icsmbstowcs(argv[1], "UTF-8", NULL)) != NULL)
2105 transfersetpath(peer->transfer, wbuf);
2106 peer->transfer->flags.b.minislot = 1;
2110 if(!strncmp(argv[1], "TTH/", 4))
2112 if((node = findbytth(argv[1] + 4)) == NULL)
2114 qstr(sk, "$Error File not in cache|");
2118 if((node = resdcpath((argv[1][0] == '/')?(argv[1] + 1):(argv[1]), "UTF-8", '/')) == NULL)
2120 qstr(sk, "$Error File not in cache|");
2124 if((fd = opensharecache(node)) < 0)
2126 qstrf(sk, "$Error %s|", strerror(errno));
2129 buf = getfspath(node);
2130 if((wbuf = icsmbstowcs(buf, NULL, NULL)) == NULL)
2131 flog(LOG_WARNING, "could not convert native path into a wcs (%s): %s", buf, strerror(errno));
2133 transfersetpath(peer->transfer, wbuf);
2136 if(!strcmp(argv[0], "file"))
2138 for(i = 4; argv[i] != NULL; i++)
2140 if(!strcmp(argv[i], "ZL1"))
2141 initcompress(peer, CPRS_ZLIB);
2143 if(fstat(fd, &sb) < 0)
2145 flog(LOG_WARNING, "could not stat file %ls: %s", node->name, strerror(errno));
2146 qstr(sk, "$Error|");
2149 if(sb.st_size < 65536)
2150 peer->transfer->flags.b.minislot = 1;
2151 if(!peer->transfer->flags.b.minislot && (slotsleft() < 1)) {
2152 qstr(sk, "$MaxedOut|");
2155 if((start != 0) && ((start >= sb.st_size) || (lseek(fd, start, SEEK_SET) < 0)))
2157 qstr(sk, "$Error Offset out of range|");
2160 if((numbytes < 0) || (start + numbytes > sb.st_size))
2161 numbytes = sb.st_size - start;
2162 lesk = wrapsock(fd);
2163 transferprepul(peer->transfer, sb.st_size, start, start + numbytes, lesk);
2166 qstr(sk, "$ADCSND");
2167 sendadc(sk, "file");
2168 sendadc(sk, argv[1]);
2169 sendadcf(sk, "%ji", (intmax_t)start);
2170 sendadcf(sk, "%ji", (intmax_t)numbytes);
2171 if(peer->compress == CPRS_ZLIB)
2175 } else if(!strcmp(argv[0], "tthl")) {
2177 * XXX: Implement full TTHL support.
2179 * In the meantime, this is better than nothing, since it at
2180 * least allows fetching of the TTH root if it isn't already
2185 qstr(sk, "$Error no TTHL data for virtual files|");
2188 qstr(sk, "$ADCSND");
2189 sendadc(sk, "tthl");
2190 sendadc(sk, argv[1]);
2194 sockqueue(sk, node->hashtth, 24);
2196 qstr(sk, "$Error Namespace not implemented|");
2206 static void handletthl(struct dcpeer *peer)
2210 while(peer->inbufdata >= 24)
2212 pushtigertree(&peer->tth, peer->inbuf);
2213 memmove(peer->inbuf, peer->inbuf + 24, peer->inbufdata -= 24);
2214 peer->curread += 24;
2216 if(peer->curread >= peer->totalsize)
2218 if(peer->timeout == NULL)
2219 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
2220 peer->state = PEER_CMD;
2221 synctigertree(&peer->tth);
2222 restigertree(&peer->tth, buf);
2223 transfersethash(peer->transfer, newhash(L"TTH", 24, buf));
2228 static void cmd_adcsnd(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2231 off_t start, numbytes;
2233 if(peer->transfer == NULL)
2238 if((argv = parseadc(args)) == NULL)
2243 if(parrlen(argv) < 4)
2248 start = strtoll(argv[2], NULL, 10);
2249 numbytes = strtoll(argv[3], NULL, 10);
2250 if(!strcmp(argv[0], "tthl"))
2252 if((start != 0) || (numbytes % 24 != 0))
2254 /* Weird. Bail out. */
2258 if(peer->timeout != NULL)
2259 canceltimer(peer->timeout);
2260 peer->state = PEER_TTHL;
2261 peer->totalsize = numbytes;
2263 peer->fetchingtthl = 0;
2264 inittigertree(&peer->tth);
2266 } else if(!strcmp(argv[0], "file")) {
2267 if(start != peer->transfer->curpos)
2272 if(start + numbytes != peer->transfer->size)
2274 transfersetsize(peer->transfer, start + numbytes);
2279 if(peer->inbufdata > 0)
2281 sockpushdata(sk, peer->inbuf, peer->inbufdata);
2282 peer->inbufdata = 0;
2283 transread(sk, peer);
2286 /* We certainly didn't request this...*/
2295 static void cmd_sending(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2299 if(peer->transfer == NULL)
2304 numbytes = strtoll(args, NULL, 10);
2305 if(peer->transfer->size - peer->transfer->curpos != numbytes)
2307 transfersetsize(peer->transfer, peer->transfer->curpos + numbytes);
2312 if(peer->inbufdata > 0)
2314 sockpushdata(sk, peer->inbuf, peer->inbufdata);
2315 peer->inbufdata = 0;
2316 transread(sk, peer);
2322 static void cmd_(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
2327 hubhandleaction(sk, fn, cmd, args);
2331 static void cmd_(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2337 static int hubreqconn(struct fnetpeer *peer)
2342 if((peer->fn->state != FNN_EST) || (peer->fn->fnet != &dcnet))
2347 if((hub = peer->fn->data) == NULL)
2352 if((mbsnick = icwcstombs(peer->id, hub->charset)) == NULL)
2353 return(1); /* Shouldn't happen, of course, but who knows... */
2356 sendctm(hub->sk, mbsnick);
2357 expectpeer(mbsnick, peer->fn);
2359 qstrf(hub->sk, "$RevConnectToMe %s %s|", hub->nativenick, mbsnick);
2365 static int hubsendchat(struct fnetnode *fn, int public, wchar_t *to, wchar_t *string)
2368 char *mbsstring, *mbsto;
2371 if((mbsto = icwcstombs(to, hub->charset)) == NULL)
2376 if((mbsstring = icwcstombs(string, hub->charset)) == NULL)
2381 if((strchr(mbsto, '|') != NULL) || (strchr(mbsto, ' ') != NULL))
2388 if(strchr(mbsstring, '|') != NULL)
2399 qstrf(hub->sk, "<%s> %s|", hub->nativenick, mbsstring);
2401 qstrf(hub->sk, "$To: %s From: %s $<%s> %s|", mbsto, hub->nativenick, hub->nativenick, mbsstring);
2404 qstrf(hub->sk, "$To: %s From: %s $<%s> %s|", mbsto, hub->nativenick, hub->nativenick, mbsstring);
2411 static void findsizelimit(struct sexpr *sexpr, int *min, int *max)
2413 int minl, maxl, minr, maxr, retmin, retmax;
2418 findsizelimit(sexpr->l, &minl, &maxl);
2419 findsizelimit(sexpr->r, &minr, &maxr);
2420 retmin = (minl > minr)?minl:minr;
2421 if((maxl != -1) && (maxr != -1))
2422 retmax = (maxl < maxr)?maxl:maxr;
2431 findsizelimit(sexpr->l, &minl, &maxl);
2432 findsizelimit(sexpr->r, &minr, &maxr);
2433 retmin = (minl < minr)?minl:minr;
2434 if((maxl == -1) || (maxr == -1))
2437 retmax = (maxl > maxr)?maxl:maxr;
2440 findsizelimit(sexpr->l, &minl, &maxl);
2441 if((minl == 0) && (maxl == -1)) /* Interval is unspecified */
2445 } else if((minl == 0) && (maxl != -1)) {
2448 } else if((minl != 0) && (maxl == -1)) {
2451 } else { /* This would yield two seperate intervals, which DC cannot handle */
2457 retmax = sexpr->d.n - 1;
2460 retmin = sexpr->d.n;
2461 retmax = sexpr->d.n;
2464 retmin = sexpr->d.n + 1;
2478 static struct hash *findsehash(struct sexpr *sexpr)
2480 struct hash *h1, *h2;
2485 if((h1 = findsehash(sexpr->l)) != NULL)
2487 if((h1 = findsehash(sexpr->r)) != NULL)
2491 if((h1 = findsehash(sexpr->l)) == NULL)
2493 if((h2 = findsehash(sexpr->r)) == NULL)
2499 if(!wcscmp(sexpr->d.hash->algo, L"TTH"))
2500 return(sexpr->d.hash);
2507 static int hubsearch(struct fnetnode *fn, struct search *srch, struct srchfnnlist *ln)
2510 struct wcslist *list, *cur;
2511 char *sstr, *buf, *p;
2512 size_t sstrsize, sstrdata;
2513 struct sockaddr *name;
2515 int minsize, maxsize;
2519 if((fn->state != FNN_EST) || (hub->sk == NULL) || (hub->sk->state != SOCK_EST))
2521 list = findsexprstrs(srch->sexpr);
2522 findsizelimit(srch->sexpr, &minsize, &maxsize);
2523 hash = findsehash(srch->sexpr);
2524 if((minsize != 0) && (maxsize != -1))
2526 /* Choose either minsize or maxsize by trying to determine
2527 * which choice will be most restrictive. The result can be
2528 * approximative at best anyway, so don't try too hard... */
2529 if((50000000 - maxsize) > (minsize - 50000000))
2535 sstrsize = sstrdata = 0;
2536 if((hash != NULL) && (hash->len == 24))
2538 /* Prioritize hash searches above all else */
2539 bufcat(sstr, "F?T?0?9?TTH:", 12);
2540 buf = base32encode(hash->buf, hash->len);
2542 bufcat(sstr, buf, 39);
2547 sizebuf2(sstr, sstrdata + 32, 1);
2548 sstrdata += snprintf(sstr + sstrdata, sstrsize - sstrdata, "T?F?%i?1?", minsize);
2549 } else if(maxsize != -1) {
2550 sizebuf2(sstr, sstrdata + 32, 1);
2551 sstrdata += snprintf(sstr + sstrdata, sstrsize - sstrdata, "T?T?%i?1?", maxsize);
2553 bufcat(sstr, "F?F?0?1?", 8);
2557 for(cur = list; cur != NULL; cur = cur->next)
2559 /* Use DCCHARSET in $Get paths until further researched... */
2560 if((buf = icwcstombs(cur->str, DCCHARSET)) == NULL)
2562 /* Can't find anything anyway if the search expression
2563 * requires characters outside DC's charset. There's
2564 * nothing technically wrong with the search itself,
2565 * however, so return success. This should be
2566 * considered as an optimization. */
2573 addtobuf(sstr, '$');
2575 * It probably doesn't hurt if buf contains any extra
2576 * dollar signs - it will just result in extra search
2577 * terms, and the extraneous results will be filtered by
2578 * the search layer anyway. It hurts if it contains any
2579 * pipes, though, so let's sell them for money.
2581 for(p = buf; *p; p++)
2586 bufcat(sstr, buf, strlen(buf));
2590 /* Will match all files... :-/ */
2591 addtobuf(sstr, '.');
2597 if(sockgetremotename2(udpsock, hub->sk, &name, &namelen) < 0)
2599 flog(LOG_WARNING, "cannot get address of UDP socket");
2601 qstrf(hub->sk, "$Search %s %s|", formataddress(name, namelen), sstr);
2605 qstrf(hub->sk, "$Search Hub:%s %s|", hub->nativenick, sstr);
2609 fn->lastsrch = time(NULL);
2617 #define cc(c) ((void (*)(struct socket *, void *, char *, char *))(c))
2618 static struct command hubcmds[] =
2620 {"$Lock", cc(cmd_lock)},
2621 {"$HubName", cc(cmd_hubname)},
2622 {"$Hello", cc(cmd_hello)},
2623 {"$Quit", cc(cmd_quit)},
2624 {"$NickList", cc(cmd_nicklist)},
2625 {"$OpList", cc(cmd_oplist)},
2626 {"$MyINFO", cc(cmd_myinfo)},
2627 {"$ForceMove", cc(cmd_forcemove)},
2628 {"$Search", cc(cmd_search)},
2629 {"$MultiSearch", cc(cmd_search)},
2630 {"$ConnectToMe", cc(cmd_connecttome)},
2631 {"$RevConnectToMe", cc(cmd_revconnecttome)},
2632 {"$GetNetInfo", cc(cmd_getnetinfo)},
2633 {"$To:", cc(cmd_to)},
2634 {"$SR", cc(cmd_sr)},
2635 {"$UserCommand", cc(cmd_usercommand)},
2636 {"$GetPass", cc(cmd_getpass)},
2637 {"$LogedIn", cc(cmd_logedin)}, /* sic */
2638 {"$Supports", cc(cmd_hubsupports)},
2642 static struct command peercmds[] =
2644 {"$MyNick", cc(cmd_mynick)},
2645 {"$Lock", cc(cmd_peerlock)},
2646 {"$Direction", cc(cmd_direction)},
2647 {"$Key", cc(cmd_key)},
2648 {"$FileLength", cc(cmd_filelength)},
2649 {"$Error", cc(cmd_error)},
2650 {"$MaxedOut", cc(cmd_maxedout)},
2651 {"$Get", cc(cmd_get)},
2652 {"$Send", cc(cmd_send)},
2653 {"$Supports", cc(cmd_supports)},
2654 {"$GetBlock", cc(cmd_getblock)},
2655 {"$UGetBlock", cc(cmd_getblock)},
2656 {"$GetZBlock", cc(cmd_getblock)},
2657 {"$UGetZBlock", cc(cmd_getblock)},
2658 {"$ADCGET", cc(cmd_adcget)},
2659 {"$ADCSND", cc(cmd_adcsnd), 1},
2660 {"$Sending", cc(cmd_sending), 1},
2665 static void dctransdetach(struct transfer *transfer, struct dcpeer *peer)
2667 CBUNREG(transfer, trans_filterout, peer);
2670 peer->transfer = NULL;
2674 static void dctransgotdata(struct transfer *transfer, struct dcpeer *peer)
2678 unsigned char outbuf[1024];
2682 if((peer->state == PEER_TRNS) || (peer->state == PEER_SYNC))
2684 if(sockqueuesize(peer->sk) < 65536)
2686 if((buf = transfergetdata(transfer, &bufsize)) != NULL)
2688 if(peer->compress == CPRS_NONE)
2690 sockqueue(peer->sk, buf, bufsize);
2691 } else if(peer->compress == CPRS_ZLIB) {
2692 cstr = peer->cprsdata;
2693 cstr->next_in = buf;
2694 cstr->avail_in = bufsize;
2695 while(cstr->avail_in > 0)
2697 cstr->next_out = outbuf;
2698 cstr->avail_out = sizeof(outbuf);
2699 if((ret = deflate(cstr, 0)) != Z_OK)
2701 flog(LOG_WARNING, "bug? deflate() did not return Z_OK (but rather %i)", ret);
2705 sockqueue(peer->sk, outbuf, sizeof(outbuf) - cstr->avail_out);
2710 if(peer->state == PEER_SYNC)
2712 if(peer->compress == CPRS_ZLIB)
2714 cstr = peer->cprsdata;
2715 cstr->next_in = NULL;
2719 cstr->next_out = outbuf;
2720 cstr->avail_out = sizeof(outbuf);
2721 ret = deflate(cstr, Z_FINISH);
2722 if((ret != Z_OK) && (ret != Z_STREAM_END))
2724 flog(LOG_WARNING, "bug? deflate(Z_FINISH) did not return Z_OK (but rather %i)", ret);
2728 sockqueue(peer->sk, outbuf, sizeof(outbuf) - cstr->avail_out);
2729 } while(ret != Z_STREAM_END);
2735 if(peer->timeout == NULL)
2736 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
2737 peer->state = PEER_CMD;
2739 transfersetstate(transfer, TRNS_HS);
2740 socksettos(peer->sk, confgetint("fnet", "fnptos"));
2741 transfer->flags.b.minislot = 0;
2742 peer->sk->writecb = NULL;
2749 static void dctransendofdata(struct transfer *transfer, struct dcpeer *peer)
2751 peer->state = PEER_SYNC;
2752 dctransgotdata(transfer, peer);
2755 static void dcwantdata(struct transfer *transfer, struct dcpeer *peer)
2757 if(transferdatasize(transfer) < 65536)
2758 peer->sk->ignread = 0;
2761 static void transread(struct socket *sk, struct dcpeer *peer)
2765 struct transfer *transfer;
2767 if((buf = sockgetinbuf(sk, &bufsize)) == NULL)
2769 if(peer->transfer == NULL)
2775 transferputdata(peer->transfer, buf, bufsize);
2777 if(peer->transfer->curpos >= peer->transfer->size)
2779 transfer = peer->transfer;
2780 transferdetach(transfer);
2781 transferendofdata(transfer);
2784 if(transferdatasize(peer->transfer) > 65535)
2788 static void transerr(struct socket *sk, int err, struct dcpeer *peer)
2790 struct transfer *transfer;
2792 if((transfer = peer->transfer) == NULL)
2797 transferdetach(transfer);
2798 transferendofdata(transfer);
2801 static void transwrite(struct socket *sk, struct dcpeer *peer)
2803 if((peer->state != PEER_TRNS) && (peer->state != PEER_SYNC))
2805 if(peer->transfer == NULL)
2810 dctransgotdata(peer->transfer, peer);
2813 static void udpread(struct socket *sk, void *data)
2815 char *buf, *p, *p2, *hashbuf;
2816 size_t buflen, hashlen;
2817 char *nick, *filename, *hubname;
2818 struct sockaddr_in hubaddr;
2821 struct fnetnode *fn, *myfn;
2824 wchar_t *wnick, *wfile;
2827 if((buf = sockgetinbuf(sk, &buflen)) == NULL)
2829 buf = srealloc(buf, buflen + 1);
2831 if(!strncmp(buf, "$SR ", 4))
2835 if((p2 = strchr(p, ' ')) == NULL)
2843 if((p2 = strchr(p, 5)) == NULL)
2850 if((p2 = strchr(p, ' ')) == NULL)
2856 size = strtoll(p, NULL, 10);
2858 if((p2 = strchr(p, '/')) == NULL)
2866 if((p2 = strchr(p, 5)) == NULL)
2873 if((p2 = strstr(p, " (")) == NULL)
2880 if((p2 = strchr(p, ':')) == NULL)
2886 hubaddr.sin_family = AF_INET;
2887 if(!inet_aton(p, &hubaddr.sin_addr))
2893 if((p2 = strchr(p, ')')) == NULL)
2899 hubaddr.sin_port = htons(atoi(p));
2900 /* Use DCCHARSET in $Get paths until further researched... */
2901 if((wfile = icmbstowcs(filename, DCCHARSET)) == NULL)
2908 if(!strncmp(hubname, "TTH:", 4))
2910 if((hashbuf = base32decode(hubname + 4, &hashlen)) != NULL)
2913 hash = newhash(L"TTH", 24, hashbuf);
2917 for(fn = fnetnodes; fn != NULL; fn = fn->next)
2919 if((fn->fnet == &dcnet) && ((hub = fn->data) != NULL))
2921 if((hub->nativename != NULL) && !strcmp(hub->nativename, hubname))
2936 for(fn = fnetnodes; fn != NULL; fn = fn->next)
2938 if((fn->fnet == &dcnet) && ((hub = fn->data) != NULL))
2940 if((hub->sk != NULL) && addreq(hub->sk->remote, (struct sockaddr *)&hubaddr))
2951 if((wnick = icmbstowcs(nick, (hub == NULL)?DCCHARSET:(hub->charset))) == NULL)
2956 sr = newsrchres(&dcnet, wfile, wnick);
2957 if(sr->peernick != NULL)
2959 sr->peernick = swcsdup(wnick);
2965 getfnetnode(sr->fn = myfn);
2974 static void hubread(struct socket *sk, struct fnetnode *fn)
2981 hub = (struct dchub *)fn->data;
2982 if((newbuf = sockgetinbuf(sk, &datalen)) == NULL)
2984 if(hub->inbufdata > 500000) /* Discard possible malicious data */
2986 sizebuf2(hub->inbuf, hub->inbufdata + datalen, 1);
2987 memcpy(hub->inbuf + hub->inbufdata, newbuf, datalen);
2989 p = hub->inbuf + hub->inbufdata;
2990 hub->inbufdata += datalen;
2991 while((datalen > 0) && ((p = memchr(p, '|', datalen)) != NULL))
2994 newqcmd(&hub->queue, hub->inbuf);
2995 memmove(hub->inbuf, p, hub->inbufdata -= p - hub->inbuf);
2996 datalen = hub->inbufdata;
3001 static void huberr(struct socket *sk, int err, struct fnetnode *fn)
3006 static int hubsetnick(struct fnetnode *fn, wchar_t *newnick)
3012 if((buf = icwcstombs(newnick, (hub == NULL)?DCCHARSET:(hub->charset))) == NULL)
3014 if((strchr(buf, ' ') != NULL) || (strchr(buf, '|') != NULL) || (strchr(buf, '$') != NULL))
3019 if(hub == NULL) /* Not yet connected */
3024 if(hub->nativenick != NULL)
3025 free(hub->nativenick);
3026 hub->nativenick = buf;
3030 static struct dchub *newdchub(struct fnetnode *fn)
3037 new = smalloc(sizeof(*new));
3038 memset(new, 0, sizeof(*new));
3040 if(confgetint("dc", "dcppemu"))
3042 if((emu = wpfind(fn->args, L"dcppemu")) != NULL)
3050 if((wcharset = wpfind(fn->args, L"charset")) != NULL)
3052 if((charset = icwcstombs(wcharset, "US-ASCII")) != NULL)
3054 if(!havecharset(charset))
3062 new->charset = charset;
3064 new->charset = sstrdup(DCCHARSET);
3065 if(hubsetnick(fn, fn->mynick))
3066 fnetsetnick(fn, L"DoldaConnectUser-IN");
3067 /* IN as in Invalid Nick */
3071 static struct dcpeer *newdcpeer(struct socket *sk)
3075 new = smalloc(sizeof(*new));
3076 memset(new, 0, sizeof(*new));
3077 new->transfer = NULL;
3080 if(confgetint("dc", "dcppemu"))
3091 static void freedcpeer(struct dcpeer *peer)
3094 struct qcommand *qcmd;
3099 if(peer->next != NULL)
3100 peer->next->prev = peer->prev;
3101 if(peer->prev != NULL)
3102 peer->prev->next = peer->next;
3103 if(peer->transfer != NULL)
3105 if(peer->transfer->dir == TRNSD_UP)
3106 peer->transfer->close = 1;
3107 if(peer->transfer->dir == TRNSD_DOWN)
3108 resettransfer(peer->transfer);
3109 transferdetach(peer->transfer);
3111 if(peer->timeout != NULL)
3112 canceltimer(peer->timeout);
3113 if(peer->sk->data == peer)
3114 peer->sk->data = NULL;
3115 peer->sk->readcb = NULL;
3116 peer->sk->writecb = NULL;
3117 peer->sk->errcb = NULL;
3120 if(peer->supports != NULL)
3122 for(i = 0; peer->supports[i] != NULL; i++)
3123 free(peer->supports[i]);
3124 free(peer->supports);
3126 if(peer->inbuf != NULL)
3128 if(peer->key != NULL)
3130 if(peer->wcsname != NULL)
3131 free(peer->wcsname);
3132 if(peer->nativename != NULL)
3133 free(peer->nativename);
3134 if(peer->charset != NULL)
3135 free(peer->charset);
3136 if(peer->fn != NULL)
3137 putfnetnode(peer->fn);
3138 while((qcmd = ulqcmd(&peer->queue)) != NULL)
3144 static void hubconnect(struct fnetnode *fn, struct socket *sk)
3148 sk->readcb = (void (*)(struct socket *, void *))hubread;
3149 sk->errcb = (void (*)(struct socket *, int, void *))huberr;
3150 fn->data = hub = newdchub(fn);
3152 getsock(hub->sk = sk);
3156 static void hubdestroy(struct fnetnode *fn)
3160 struct qcommand *qcmd;
3162 hub = (struct dchub *)fn->data;
3164 while((qcmd = ulqcmd(&hub->queue)) != NULL)
3166 if(hub->supports != NULL)
3168 for(i = 0; hub->supports[i] != NULL; i++)
3169 free(hub->supports[i]);
3170 free(hub->supports);
3172 if(hub->nativename != NULL)
3173 free(hub->nativename);
3174 if(hub->nativenick != NULL)
3175 free(hub->nativenick);
3176 if(hub->charset != NULL)
3178 if(hub->inbuf != NULL)
3183 static void hubkill(struct fnetnode *fn)
3187 hub = (struct dchub *)fn->data;
3191 static wchar_t *dcbasename(wchar_t *filename)
3195 if((ret = wcsrchr(filename, L'\\')) != NULL)
3200 static struct transferiface dctransfer =
3202 .detach = (void (*)(struct transfer *, void *))dctransdetach,
3203 .gotdata = (void (*)(struct transfer *, void *))dctransgotdata,
3204 .endofdata = (void (*)(struct transfer *, void *))dctransendofdata,
3205 .wantdata = (void (*)(struct transfer *, void *))dcwantdata
3208 static struct fnet dcnet =
3211 .connect = hubconnect,
3212 .destroy = hubdestroy,
3214 .setnick = hubsetnick,
3215 .reqconn = hubreqconn,
3216 .sendchat = hubsendchat,
3217 .search = hubsearch,
3218 .filebasename = dcbasename
3221 static void peerread(struct socket *sk, struct dcpeer *peer)
3225 struct command *cmd;
3227 if((newbuf = sockgetinbuf(sk, &datalen)) == NULL)
3229 sizebuf2(peer->inbuf, peer->inbufdata + datalen, 1);
3230 memcpy(peer->inbuf + peer->inbufdata, newbuf, datalen);
3232 peer->inbufdata += datalen;
3233 if(peer->state == PEER_CMD)
3236 while((peer->inbufdata > 0) && (p = memchr(peer->inbuf, '|', peer->inbufdata)) != NULL)
3239 newqcmd(&peer->queue, peer->inbuf);
3240 for(cmd = peercmds; cmd->handler != NULL; cmd++)
3242 if(!memcmp(peer->inbuf, cmd->name, strlen(cmd->name)) && ((peer->inbuf[strlen(cmd->name)] == ' ') || (peer->inbuf[strlen(cmd->name)] == '|')))
3245 memmove(peer->inbuf, p, peer->inbufdata -= p - peer->inbuf);
3248 peer->state = PEER_STOP;
3252 } else if(peer->state == PEER_TTHL) {
3257 static void peererror(struct socket *sk, int err, struct dcpeer *peer)
3262 static void peerconnect(struct socket *sk, int err, struct fnetnode *fn)
3264 struct dcpeer *peer;
3274 peer = newdcpeer(sk);
3277 peer->dcppemu = hub->dcppemu;
3278 sk->readcb = (void (*)(struct socket *, void *))peerread;
3279 sk->errcb = (void (*)(struct socket *, int, void *))peererror;
3281 socksettos(sk, confgetint("fnet", "fnptos"));
3283 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
3288 static void peeraccept(struct socket *sk, struct socket *newsk, void *data)
3290 struct dcpeer *peer;
3292 peer = newdcpeer(newsk);
3294 newsk->readcb = (void (*)(struct socket *, void *))peerread;
3295 newsk->errcb = (void (*)(struct socket *, int, void *))peererror;
3297 socksettos(newsk, confgetint("fnet", "fnptos"));
3298 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
3301 static void updatehmlist(void)
3303 int i, lev, ic, ret;
3304 struct sharecache *node;
3305 char *buf, *buf2, numbuf[32];
3306 size_t bufsize, bufdata;
3310 buf = smalloc(bufsize = 65536);
3311 node = shareroot->child;
3316 /* Use DCCHARSET in $Get paths until further researched... */
3317 if((buf2 = icwcstombs(node->name, DCCHARSET)) != NULL)
3319 for(i = 0; i < lev; i++)
3321 bufcat(buf, buf2, strlen(buf2));
3323 if(node->f.b.type == FILE_REG)
3326 sprintf(numbuf, "%ji", (intmax_t)node->size);
3327 bufcat(buf, numbuf, strlen(numbuf));
3334 if((node->child != NULL) && !ic)
3338 } else if(node->next != NULL) {
3341 while(node->next == NULL)
3344 node = node->parent;
3345 if(node == shareroot)
3348 if(node == shareroot)
3353 if(hmlistname != NULL)
3358 hmlistname = sstrdup("/tmp/dc-filelist-hm-XXXXXX");
3359 if((fd = mkstemp(hmlistname)) < 0)
3361 flog(LOG_WARNING, "could not create HM file list tempfile: %s", strerror(errno));
3366 * I do not want to implement a good Huffman encoder, and it's not
3367 * like Huffman encoding actually yields any impressive results
3368 * for DC file lists anyway, so I'll just output a bogus
3369 * tree. Implement a good encoder if you want to.
3371 write(fd, "HE3\r\0", 5);
3372 write(fd, &bufdata, 4);
3374 write(fd, &ibuf, 2);
3376 for(i = 0; i < 256; i++)
3379 write(fd, &ibuf, 1);
3381 for(i = 0; i < 256; i++)
3383 for(buf2 = buf; bufdata > 0;)
3385 if((ret = write(fd, buf2, bufdata)) < 0)
3387 flog(LOG_WARNING, "could not write file list: %s", strerror(errno));
3398 static struct xmlent
3405 /* {L'\'', L"""}, Emulate DC++ escaping by omitting this. */
3409 static wchar_t *escapexml(wchar_t *src)
3411 static wchar_t *buf = NULL;;
3414 size_t bufsize, bufdata;
3420 bufsize = bufdata = 0;
3421 for(; *src != L'\0'; src++)
3424 if((c > 0) && (c < 32))
3426 bufcat(buf, L"&#", 2);
3427 ret = swprintf(nbuf, (sizeof(nbuf) / sizeof(*nbuf)), L"%i", c);
3428 bufcat(buf, nbuf, ret);
3429 addtobuf(buf, L';');
3431 for(ent = entities; ent->ent != NULL; ent++)
3435 bufcat(buf, ent->ent, wcslen(ent->ent));
3439 if(ent->ent == NULL)
3440 addtobuf(buf, *src);
3443 addtobuf(buf, L'\0');
3447 static void updatexmllist(void)
3451 char cidbuf[14], *namebuf;
3453 struct sharecache *node;
3455 if(xmllistname != NULL)
3457 unlink(xmllistname);
3460 xmllistname = sstrdup("/tmp/dc-filelist-dcxml-XXXXXX");
3461 if((fd = mkstemp(xmllistname)) < 0)
3463 flog(LOG_WARNING, "could not create XML file list tempfile: %s", strerror(errno));
3468 if((fs = fdopen(fd, "w")) == NULL)
3470 flog(LOG_WARNING, "could not fdopen XML list fd %i: %s", fd, strerror(errno));
3471 unlink(xmllistname);
3477 fprintf(fs, "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>\r\n");
3478 for(i = 0; i < sizeof(cidbuf) - 1; i++)
3479 cidbuf[i] = (rand() % ('Z' - 'A' + 1)) + 'A';
3481 if(confgetint("dc", "dcppemu"))
3482 fprintf(fs, "<FileListing Version=\"1\" CID=\"%s\" Base=\"/\" Generator=\"DC++ 0.674\">\r\n", cidbuf);
3484 fprintf(fs, "<FileListing Version=\"1\" CID=\"%s\" Base=\"/\" Generator=\"%s\">\r\n", cidbuf, "DoldaConnect" VERSION);
3486 node = shareroot->child;
3490 if((namebuf = icswcstombs(escapexml(node->name), "UTF-8", NULL)) != NULL)
3492 for(i = 0; i < lev; i++)
3494 if(node->child != NULL)
3496 fprintf(fs, "<Directory Name=\"%s\">\r\n", namebuf);
3501 fprintf(fs, "<File Name=\"%s\" Size=\"%ji\"", namebuf, (intmax_t)node->size);
3502 if(node->f.b.hastth)
3504 hashbuf = base32encode(node->hashtth, 24);
3505 fprintf(fs, " TTH=\"%.39s\"", hashbuf);
3508 fprintf(fs, "/>\r\n");
3510 while(node->next == NULL)
3512 node = node->parent;
3513 if(node == shareroot)
3518 for(i = 0; i < lev; i++)
3520 fprintf(fs, "</Directory>\r\n");
3523 if(node == shareroot)
3529 if(confgetint("dc", "dcppemu"))
3530 fprintf(fs, "</FileListing>");
3532 fprintf(fs, "</FileListing>\r\n");
3536 static void updatexmlbz2list(void)
3545 if(xmllistname == NULL)
3547 if((in = fopen(xmllistname, "r")) == NULL)
3549 flog(LOG_WARNING, "could not open XML file list for bzipping: %s", strerror(errno));
3552 if(xmlbz2listname != NULL)
3554 unlink(xmlbz2listname);
3555 free(xmlbz2listname);
3557 xmlbz2listname = sstrdup("/tmp/dc-filelist-dcxmlbz2-XXXXXX");
3558 if((fd = mkstemp(xmlbz2listname)) < 0)
3560 flog(LOG_WARNING, "could not create bzipped XML file list tempfile: %s", strerror(errno));
3561 free(xmlbz2listname);
3562 xmlbz2listname = NULL;
3566 if((real = fdopen(fd, "w")) == NULL)
3568 flog(LOG_WARNING, "could not fdopen bzipped XML list fd %i: %s", fd, strerror(errno));
3570 unlink(xmlbz2listname);
3571 free(xmlbz2listname);
3572 xmlbz2listname = NULL;
3576 out = BZ2_bzWriteOpen(&err, real, 9, 0, 0);
3579 flog(LOG_WARNING, "could not open bzip2 stream from XML list");
3581 unlink(xmlbz2listname);
3582 free(xmlbz2listname);
3583 xmlbz2listname = NULL;
3589 bufdata = fread(buf, 1, sizeof(buf), in);
3590 BZ2_bzWrite(&err, out, buf, bufdata);
3593 BZ2_bzWriteClose(&err, out, 0, NULL, NULL);
3597 static void listtimercb(int cancelled, void *uudata)
3599 listwritetimer = NULL;
3604 static void updatelists(int now)
3606 if((hmlistname == NULL) || (xmllistname == NULL) || (xmlbz2listname == NULL))
3610 if(listwritetimer == NULL)
3611 listwritetimer = timercallback(ntime() + confgetint("cli", "hashwritedelay"), listtimercb, NULL);
3614 if(listwritetimer != NULL)
3615 canceltimer(listwritetimer);
3621 static int shareupdate(unsigned long long uusharesize, void *data)
3627 static char *quotestr(char *str)
3631 size_t bufsize, bufdata;
3633 static char *enc = NULL;
3634 size_t encsize, encdata;
3637 bufsize = bufdata = 0;
3638 for(p = (unsigned char *)str; *p; p++)
3641 bufcat(buf, "\\b", 2);
3643 bufcat(buf, "\\t", 2);
3645 bufcat(buf, "\\n", 2);
3647 bufcat(buf, "\\r", 2);
3649 bufcat(buf, "\\\\", 2);
3653 bprintf(buf, "\\x%02x", *p);
3659 if((wbuf = icmbstowcs((char *)buf, DCCHARSET)) != NULL)
3661 enc = icwcstombs(wbuf, NULL);
3666 encsize = encdata = 0;
3667 for(p = buf; *p; p++) {
3671 bprintf(buf, "\\x%x", *p);
3678 static void logunimpl(char *list, char *cmd, char *args)
3682 if((log = fopen("/tmp/dc-unimpl", "a")) == NULL)
3684 flog(LOG_WARNING, "could not open unimpl log: %s", strerror(errno));
3689 fputs(quotestr(cmd), log);
3693 fputs(quotestr(args), log);
3699 static void dispatchcommand(struct qcommand *qcmd, struct command *cmdlist, struct socket *sk, void *data)
3702 struct command *cmd;
3704 if((p = strchr(qcmd->string, ' ')) != NULL)
3706 for(cmd = cmdlist; cmd->handler != NULL; cmd++)
3708 if(!strcmp(cmd->name, qcmd->string))
3711 if(cmd->handler != NULL)
3713 cmd->handler(sk, data, qcmd->string, p);
3714 } else if(confgetint("dc", "logunimpl")) {
3715 if(cmdlist == hubcmds)
3716 logunimpl("hub", qcmd->string, p);
3717 else if(cmdlist == peercmds)
3718 logunimpl("peer", qcmd->string, p);
3720 logunimpl("other?!", qcmd->string, p);
3724 static int run(void)
3726 struct fnetnode *fn, *nextfn;
3728 struct dcpeer *peer, *nextpeer;
3729 struct qcommand *qcmd;
3733 for(fn = fnetnodes; fn != NULL; fn = nextfn)
3736 if(fn->fnet != &dcnet)
3738 if(fn->data == NULL)
3740 hub = (struct dchub *)fn->data;
3741 if((qcmd = ulqcmd(&hub->queue)) != NULL)
3743 if(*qcmd->string == '$')
3745 if((hub->sk != NULL) && (hub->sk->state == SOCK_EST))
3746 dispatchcommand(qcmd, hubcmds, hub->sk, fn);
3747 } else if(*qcmd->string != 0) {
3748 hubrecvchat(hub->sk, fn, NULL, qcmd->string);
3755 for(peer = peers; peer != NULL; peer = nextpeer)
3757 nextpeer = peer->next;
3758 if((qcmd = ulqcmd(&peer->queue)) != NULL)
3760 if(peer->timeout != NULL)
3761 canceltimer(peer->timeout);
3762 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
3763 if(*qcmd->string == '$')
3764 dispatchcommand(qcmd, peercmds, peer->sk, peer);
3773 static void preinit(int hup)
3780 static int updateudpport(struct configvar *var, void *uudata)
3782 struct sockaddr_in addr;
3783 struct socket *newsock;
3785 memset(&addr, 0, sizeof(addr));
3786 addr.sin_family = AF_INET;
3787 addr.sin_port = htons(var->val.num);
3788 if((newsock = netcsdgram((struct sockaddr *)&addr, sizeof(addr))) == NULL)
3790 flog(LOG_WARNING, "could not create new DC UDP socket, reverting to old: %s", strerror(errno));
3793 newsock->readcb = udpread;
3800 static int updatetcpport(struct configvar *var, void *uudata)
3802 struct sockaddr_in addr;
3803 struct socket *newsock;
3805 memset(&addr, 0, sizeof(addr));
3806 addr.sin_family = AF_INET;
3807 addr.sin_port = htons(var->val.num);
3808 if((newsock = netcslisten(SOCK_STREAM, (struct sockaddr *)&addr, sizeof(addr), peeraccept, NULL)) == NULL)
3809 flog(LOG_INFO, "could not listen to a remote address, going into passive mode");
3816 static int init(int hup)
3818 struct sockaddr_in addr;
3822 GCBREG(sharechangecb, shareupdate, NULL);
3827 addr.sin_family = AF_INET;
3828 memset(&addr.sin_addr, 0, sizeof(addr.sin_addr));
3829 addr.sin_port = htons(confgetint("dc", "udpport"));
3830 if((udpsock = netcsdgram((struct sockaddr *)&addr, sizeof(addr))) == NULL)
3832 flog(LOG_CRIT, "could not create DC UDP socket: %s", strerror(errno));
3835 udpsock->readcb = udpread;
3836 addr.sin_port = htons(confgetint("dc", "tcpport"));
3837 if((tcpsock = netcslisten(SOCK_STREAM, (struct sockaddr *)&addr, sizeof(addr), peeraccept, NULL)) == NULL)
3838 flog(LOG_INFO, "could not listen to a remote address, going into passive mode");
3839 CBREG(confgetvar("dc", "udpport"), conf_update, updateudpport, NULL, NULL);
3840 CBREG(confgetvar("dc", "tcpport"), conf_update, updatetcpport, NULL, NULL);
3841 CBREG(confgetvar("net", "mode"), conf_update, updatetcpport, NULL, NULL);
3846 static void terminate(void)
3848 if(hmlistname != NULL)
3853 if(xmllistname != NULL)
3855 unlink(xmllistname);
3858 if(xmlbz2listname != NULL)
3860 unlink(xmlbz2listname);
3861 free(xmlbz2listname);
3865 static struct configvar myvars[] =
3867 /** Specifies the share description reported to other DC users. */
3868 {CONF_VAR_STRING, "desc", {.str = L""}},
3869 /** Specifies the speed reported to other DC users. Normal values
3870 * are 28.8Kbps, 33.6Kbps, 56Kbps, Satellite, ISDN, DSL, Cable,
3871 * LAN(T1) or LAN(T3)*/
3872 {CONF_VAR_STRING, "speedstring", {.str = L"LAN(T1)"}},
3873 /** The e-mail address to report to other DC users. */
3874 {CONF_VAR_STRING, "email", {.str = L"spam@spam.org"}},
3875 /** Specifies a specific UDP port to use for DC search results. If
3876 * left unspecified, a port is allocated dynamically. Useful for
3877 * NAT routers (see also the net.visibleipv4 address for those
3879 {CONF_VAR_INT, "udpport", {.num = 0}},
3880 /** Specifies a specific TCP port to use for DC peer
3881 * connections. If left unspecified, a port is allocated
3882 * dynamically. Useful for NAT routers (see also the
3883 * net.visibleipv4 address for those cases). */
3884 {CONF_VAR_INT, "tcpport", {.num = 0}},
3885 /** If set to true, doldacond will do its best to emulate DC++
3886 * (currently v0.674). This should be left off if at all possible,
3887 * since turning it on will violate the rules of most hubs and
3888 * thus give hub owners an actual reason to kick you if it is
3889 * detected. It might be needed for some of the more bone-headed
3890 * hub owners, though. Note that DC++ emulation can also be turned
3891 * on or off for individual hubs, overriding this setting. */
3892 {CONF_VAR_BOOL, "dcppemu", {.num = 0}},
3893 /** Use for debugging. If set to true, doldacond will log all
3894 * unknown commands it receives, and their arguments, to
3895 * /tmp/dc-unimpl. */
3896 {CONF_VAR_BOOL, "logunimpl", {.num = 0}},
3897 /** If set to true, doldacond will hide its support for deflate
3898 * compression of transfers from other clients, so that they will
3899 * not request compressed uploads. Compressed transfers may
3900 * consume a non-trivial amount of CPU time on slower machines. */
3901 {CONF_VAR_BOOL, "hidedeflate", {.num = 0}},
3905 static struct module me =
3914 .terminate = terminate,