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 size_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 static void sendadcf(struct socket *sk, char *arg, ...)
511 buf = vsprintf2(arg, args);
519 static char **parseadc(char *args)
522 size_t retbufsize, retbufdata;
524 size_t bufsize, bufdata;
529 retbufsize = retbufdata = bufsize = bufdata = 0;
538 else if(*args != ' ')
542 if((*args == ' ') || (*args == 0))
545 addtobuf(retbuf, buf);
547 bufsize = bufdata = 0;
550 } else if(*args == '\\') {
553 addtobuf(buf, *args);
562 addtobuf(retbuf, NULL);
565 } else if((*args == 's') || (*args == ' ')) {
567 } else if(*args == 'n') {
569 } else if(*args == '\\') {
579 addtobuf(retbuf, NULL);
583 /* Macros useful in command handlers */
584 #define skipspace(s) ({if(((s) = strchr((s), ' ')) == NULL) return; else (s)++;})
585 #define qstr(sk, str) sockqueue(sk, str, strlen(str))
586 #define qstrf(sk, strandargs...) \
589 if((__buf__ = sprintf2(strandargs)) != NULL) { \
590 sockqueue(sk, __buf__, strlen(__buf__)); \
595 static char *tr(char *str, char *trans)
599 for(; *trans; trans += 2)
601 for(p = strchr(str, trans[0]); p != NULL; p = strchr(p, trans[0]))
607 static char *getadcid(struct dcpeer *peer)
614 if(!wcscmp(peer->transfer->path, L"files.xml") || !wcscmp(peer->transfer->path, L"files.xml.bz2") || !wcscmp(peer->transfer->path, L"MyList.DcLst"))
616 if(!isfilelist && (peer->transfer->hash != NULL) && isdchash(peer->transfer->hash) && supports(peer, "tthf"))
618 buf = base32encode(peer->transfer->hash->buf, 24);
619 ret = sprintf2("TTH/%.39s", buf);
622 if((buf = icwcstombs(peer->transfer->path, "UTF-8")) == NULL)
624 ret = pathnmdc2adc(buf);
631 static int trresumecb(struct transfer *transfer, wchar_t *cmd, wchar_t *arg, struct dcpeer *peer)
633 if(!wcscmp(cmd, L"resume"))
637 flog(LOG_WARNING, "filter returned no position for \"resume\" on transfer %i", transfer->id);
640 transfer->curpos = wcstol(arg, NULL, 10);
649 static void sendmynick(struct dcpeer *peer)
655 qstrf(peer->sk, "$MyNick %s|", icswcstombs(confgetstr("cli", "defnick"), peer->charset, "DoldaConnectUser-IN"));
657 qstrf(peer->sk, "$MyNick %s|", icswcstombs(fn->mynick, peer->charset, "DoldaConnectUser-IN"));
660 static void sendpeerlock(struct dcpeer *peer)
663 qstrf(peer->sk, "$Lock EXTENDEDPROTOCOLABCABCABCABCABCABC Pk=DCPLUSPLUS0.674ABCABC|");
665 qstrf(peer->sk, "$Lock EXTENDEDPROTOCOLABCABCABCABCABCABC Pk=DOLDA%sABCABCABC|", VERSION);
668 static void sendsupports(struct dcpeer *peer)
671 qstr(peer->sk, "$Supports MiniSlots XmlBZList ADCGet TTHL TTHF GetZBlock ZLIG |");
673 qstr(peer->sk, "$Supports MiniSlots XmlBZList ADCGet TTHL TTHF");
674 if(!confgetint("dc", "hidedeflate"))
675 qstr(peer->sk, " GetZBlock ZLIG");
680 static void requestfile(struct dcpeer *peer)
684 if(peer->transfer->size == -1)
686 /* Use DCCHARSET for $Get paths until further researched... */
687 if((buf = icswcstombs(peer->transfer->path, DCCHARSET, NULL)) == NULL)
689 transferseterror(peer->transfer, TRNSE_NOTFOUND);
693 /* The transfer will be restarted later from
694 * cmd_filelength when it detects that the sizes
696 qstrf(peer->sk, "$Get %s$1|", buf);
699 if((peer->transfer->hash == NULL) && !peer->notthl)
701 if(supports(peer, "adcget") && supports(peer, "tthl"))
703 qstr(peer->sk, "$ADCGET");
704 sendadc(peer->sk, "tthl");
705 if((buf = getadcid(peer)) == NULL)
707 transferseterror(peer->transfer, TRNSE_NOTFOUND);
711 sendadc(peer->sk, buf);
713 sendadc(peer->sk, "0");
714 sendadc(peer->sk, "-1");
716 peer->fetchingtthl = 1;
722 if(forkfilter(peer->transfer))
724 flog(LOG_WARNING, "could not fork filter for transfer %i: %s", peer->transfer->id, strerror(errno));
728 CBREG(peer->transfer, trans_filterout, (int (*)(struct transfer *, wchar_t *, wchar_t *, void *))trresumecb, NULL, peer);
731 if(supports(peer, "adcget"))
733 qstr(peer->sk, "$ADCGET");
734 sendadc(peer->sk, "file");
735 if((buf = getadcid(peer)) == NULL)
737 transferseterror(peer->transfer, TRNSE_NOTFOUND);
741 sendadc(peer->sk, buf);
743 sendadcf(peer->sk, "%i", peer->transfer->curpos);
744 sendadcf(peer->sk, "%i", peer->transfer->size - peer->transfer->curpos);
746 } else if(supports(peer, "xmlbzlist")) {
747 if((buf = icswcstombs(peer->transfer->path, "UTF-8", NULL)) == NULL)
749 transferseterror(peer->transfer, TRNSE_NOTFOUND);
753 qstrf(peer->sk, "$UGetBlock %zi %zi %s|", peer->transfer->curpos, peer->transfer->size - peer->transfer->curpos, buf);
755 /* Use DCCHARSET for $Get paths until further researched... */
756 if((buf = icswcstombs(peer->transfer->path, DCCHARSET, NULL)) == NULL)
758 transferseterror(peer->transfer, TRNSE_NOTFOUND);
762 qstrf(peer->sk, "$Get %s$%zi|", buf, peer->transfer->curpos + 1);
766 static void sendmyinfo(struct socket *sk, struct fnetnode *fn)
770 struct fnetnode *cfn;
774 qstrf(sk, "$MyINFO $ALL %s ", hub->nativenick);
775 buf = tr(icswcstombs(confgetstr("dc", "desc"), hub->charset, "Charset_conv_failure"), "$_|_");
776 qstrf(sk, "%s", buf);
778 for(cfn = fnetnodes; cfn != NULL; cfn = cfn->next)
780 if((cfn->state == FNN_EST) || (cfn->state == FNN_HS))
782 if(cfn->regstatus == FNNS_OP)
784 else if(cfn->regstatus == FNNS_REG)
790 qstrf(sk, "<%s V:%s,M:%c,H:%i/%i/%i,S:%i>",
791 (hub->dcppemu)?"++":"Dolda",
792 (hub->dcppemu)?"0.674":VERSION,
793 (tcpsock == NULL)?'P':'A',
795 confgetint("transfer", "slots")
798 buf = tr(icswcstombs(confgetstr("dc", "speedstring"), hub->charset, "Charset_conv_failure"), "$_|_");
799 qstrf(sk, "%s\x01$", buf);
800 buf = tr(icswcstombs(confgetstr("dc", "email"), hub->charset, "Charset_conv_failure"), "$_|_");
801 qstrf(sk, "%s$", buf);
802 qstrf(sk, "%llu$|", sharesize);
805 static void hubhandleaction(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
810 if(!strcmp(cmd, "$Lock"))
812 qstrf(sk, "$ValidateNick %s|", hub->nativenick);
813 } else if(!strcmp(cmd, "$Hello")) {
814 if(fn->state == FNN_HS)
816 qstrf(sk, "$Version 1,0091|");
817 qstrf(sk, "$GetNickList|");
819 fnetsetstate(fn, FNN_EST);
821 qstrf(sk, "$GetINFO %s %s|", args, hub->nativenick);
826 static void cmd_lock(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
833 if(!strncmp(args, "EXTENDEDPROTOCOL", 16))
835 if((p = strchr(args, ' ')) != NULL)
840 qstrf(sk, "$Supports UserCommand NoGetINFO NoHello UserIP2 TTHSearch GetZBlock |");
842 qstrf(sk, "$Supports UserCommand NoGetINFO NoHello UserIP2 TTHSearch");
843 if(!confgetint("dc", "hidedeflate"))
844 qstr(sk, " GetZBlock");
848 key = dcmakekey(args);
849 qstrf(sk, "$Key %s|", key);
851 hubhandleaction(sk, fn, cmd, args);
854 static void cmd_hubname(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
860 if(hub->nativename == NULL)
861 free(hub->nativename);
862 hub->nativename = sstrdup(args);
863 buf = icmbstowcs(args, hub->charset);
864 fnetsetname(fn, (buf == NULL)?L"Hubname conv error":buf);
867 hubhandleaction(sk, fn, cmd, args);
870 static void cmd_hello(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
876 if((nick = icmbstowcs(args, hub->charset)) == NULL)
878 if(strcmp(args, hub->nativenick) && (fnetfindpeer(fn, nick) == NULL))
879 fnetaddpeer(fn, nick, nick);
881 hubhandleaction(sk, fn, cmd, args);
884 static void cmd_quit(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
887 struct fnetpeer *peer;
891 if((nick = icmbstowcs(args, hub->charset)) == NULL)
893 if((peer = fnetfindpeer(fn, nick)) != NULL)
896 hubhandleaction(sk, fn, cmd, args);
899 static void cmd_nicklist(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
904 struct fnetpeer *peer, *npeer;
907 for(peer = fn->peers; peer != NULL; peer = peer->next)
908 peer->flags.b.delete = 1;
909 while((p = strstr(args, "$$")) != NULL)
912 if((buf = icmbstowcs(args, hub->charset)) != NULL)
914 if((peer = fnetfindpeer(fn, buf)) == NULL)
915 peer = fnetaddpeer(fn, buf, buf);
917 peer->flags.b.delete = 0;
919 qstrf(sk, "$GetINFO %s %s|", args, hub->nativenick);
923 for(peer = fn->peers; peer != NULL; peer = npeer)
926 if(peer->flags.b.delete)
929 hubhandleaction(sk, fn, cmd, args);
932 static void cmd_oplist(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
937 struct fnetpeer *peer;
940 for(peer = fn->peers; peer != NULL; peer = peer->next)
941 peer->flags.b.op = 0;
942 while((p = strstr(args, "$$")) != NULL)
945 if((buf = icmbstowcs(args, hub->charset)) != NULL)
947 if((peer = fnetfindpeer(fn, buf)) != NULL)
948 peer->flags.b.op = 1;
953 hubhandleaction(sk, fn, cmd, args);
956 static void cmd_myinfo(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
959 wchar_t *buf, *wp, *wp2;
961 struct fnetpeer *peer;
966 if(strncmp(p, "$ALL ", 5))
969 if((p2 = strchr(p, ' ')) == NULL)
972 if((buf = icmbstowcs(p, hub->charset)) == NULL)
974 if((peer = fnetfindpeer(fn, buf)) == NULL)
975 peer = fnetaddpeer(fn, buf, buf);
978 if((p2 = strstr(p, "$ $")) == NULL)
981 if((buf = icmbstowcs(p, hub->charset)) == NULL)
983 if((wcslen(buf) > 0) && (buf[wcslen(buf) - 1] == L'>') && ((wp = wcsrchr(buf, L'<')) != NULL))
985 buf[wcslen(buf) - 1] = L'\0';
987 if((wp2 = wcschr(wp, L' ')) != NULL)
990 fnetpeersetstr(peer, L"dc-client", wp);
994 if((wp2 = wcschr(wp, L',')) != NULL)
998 swprintf(abuf, 10, L"dc-tag-%lc", wp[0]);
999 fnetpeersetstr(peer, abuf, wp + 2);
1001 } while(wp2 != NULL);
1004 fnetpeersetstr(peer, L"descr", buf);
1007 if((p2 = strchr(p, '$')) == NULL)
1010 if((buf = icmbstowcs(p, hub->charset)) == NULL)
1012 fnetpeersetstr(peer, L"dc-speed", buf);
1015 if((p2 = strchr(p, '$')) == NULL)
1018 if((buf = icmbstowcs(p, hub->charset)) == NULL)
1020 fnetpeersetstr(peer, L"email", buf);
1025 fnetpeersetlnum(peer, L"share", strtoll(p, NULL, 10));
1026 hubhandleaction(sk, fn, cmd, args);
1029 /* I do not implement the fully in that I do not disconnect from the
1030 * old hub. I do this since I believe that if the hub owner really
1031 * wants to get rid of us, then it is his responsibility to disconnect
1033 static void cmd_forcemove(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1036 struct fnetnode *newfn;
1040 if(strchr(args, ':') == NULL)
1042 args = strcpy(smalloc(strlen(args) + 5), args);
1043 strcat(args, ":411");
1048 if((newfn = fnetinitconnect(L"dc", fn->owner, args, NULL)) != NULL)
1050 linkfnetnode(newfn);
1053 hubhandleaction(sk, fn, cmd, args);
1058 static char *getdcpath(struct sharecache *node, size_t *retlen, char *charset)
1063 if(node->parent == NULL)
1065 if(node->parent == shareroot)
1067 if((buf = icwcstombs(node->name, charset)) == NULL)
1070 *retlen = strlen(buf);
1073 if((buf2 = icwcstombs(node->name, charset)) == NULL)
1075 if((buf = getdcpath(node->parent, &len, charset)) == NULL)
1080 len2 = strlen(buf2);
1081 buf = srealloc(buf, len + 1 + len2 + 1);
1083 strcpy(buf + len, buf2);
1084 buf[len + len2] = 0;
1087 *retlen = len + len2;
1093 * This is the main share searching function for Direct Connect
1094 * peers. Feel free to optimize it if you feel the need for it. I
1095 * haven't ever seen it take any noticable CPU time anyway, so I
1096 * haven't felt that need.
1098 * It may feel dubious to just return the directory when all terms are
1099 * satisfied rather than all the files in it, but it really benefits
1100 * everyone: Less cycles used for us, less UDP squelching for active
1101 * searchers, and less bandwidth waste for hubs when serving passive
1104 static void cmd_search(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1109 char *prefix, *infix, *postfix, *buf, *buf2;
1111 struct sockaddr_in addr;
1112 struct sharecache *node;
1113 int minsize, maxsize;
1116 int termnum, satisfied, skipcheck;
1117 int level, tersat[32];
1122 if((p = strchr(args, ' ')) == NULL)
1126 memset(terms, 0, sizeof(terms));
1127 prefix = infix = postfix = NULL;
1131 if(!strncmp(args, "Hub:", 4))
1133 if(!strcmp(cmd, "$MultiSearch"))
1135 if(!strcmp(args + 4, hub->nativenick))
1137 prefix = sprintf2("$SR %s ", hub->nativenick);
1138 infix = sprintf2(" %i/%i\005", slotsleft(), confgetint("transfer", "slots"));
1139 postfix = sprintf2(" (%s)\005%s|", formataddress(hub->sk->remote, hub->sk->remotelen), args + 4);
1143 if((p2 = strchr(args, ':')) == NULL)
1146 addr.sin_family = AF_INET;
1147 if(!inet_aton(args, &addr.sin_addr))
1149 addr.sin_port = htons(atoi(p2));
1150 prefix = sprintf2("$SR %s ", hub->nativenick);
1151 infix = sprintf2(" %i/%i\005", slotsleft(), confgetint("transfer", "slots"));
1152 postfix = sprintf2(" (%s)|", formataddress(hub->sk->remote, hub->sk->remotelen));
1153 netdgramconn(dsk = netdupsock(udpsock), (struct sockaddr *)&addr, sizeof(addr));
1156 minsize = maxsize = -1;
1165 if((*(p++) == 'T') && (minsize == 0))
1172 if((p2 = strchr(p, '?')) == NULL)
1187 if((*p2 == 0) || (*p2 == '$'))
1195 if(!dotth && !strncmp(p, "TTH:", 4))
1198 if(((buf = base32decode(p + 4, &buflen)) == NULL) || (buflen != 24))
1203 memcpy(hashtth, buf, 24);
1206 if((terms[termnum] = icmbstowcs(p, hub->charset)) != NULL)
1217 node = shareroot->child;
1219 for(i = 0; i < termnum; i++)
1225 if(node->f.b.type == FILE_REG)
1227 if((minsize >= 0) && (node->size < minsize))
1229 if((maxsize >= 0) && (node->size > maxsize))
1232 if(!skipcheck && dotth)
1234 if((node->f.b.type != FILE_REG) || (node->f.b.hastth && memcmp(hashtth, node->hashtth, 24)))
1239 for(i = 0; i < termnum; i++)
1243 if(wcsexists(node->name, terms[i]))
1247 } else if(node->child == NULL) {
1252 if(!skipcheck && (satisfied == termnum))
1254 /* Use DCCHARSET in $Get paths until further researched... */
1255 if((buf = getdcpath(node, NULL, DCCHARSET)) != NULL)
1257 if(node->f.b.hastth)
1259 buf2 = base32encode(node->hashtth, 24);
1260 qstrf(dsk, "%s%s\005%zi%sTTH:%.39s%s", prefix, buf, node->size, infix, buf2, postfix);
1263 qstrf(dsk, "%s%s\005%zi%s%s%s", prefix, buf, node->size, infix, hub->nativename, postfix);
1268 if((!skipcheck && (satisfied == termnum)) || (node->child == NULL))
1270 while(node->next == NULL)
1272 if((node = node->parent) == shareroot)
1276 if(node == shareroot)
1278 for(i = 0; i < termnum; i++)
1280 if(tersat[i] >= level)
1293 hubhandleaction(sk, fn, cmd, args);
1304 for(i = 0; (i < 32) && (terms[i] != NULL); i++)
1308 static void cmd_connecttome(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1312 struct socket *newsk;
1313 struct sockaddr_in addr;
1316 if((p = strchr(args, ' ')) == NULL)
1319 if(strcmp(args, hub->nativenick))
1321 addr.sin_family = AF_INET;
1323 if((p = strchr(args, ':')) == NULL)
1326 addr.sin_port = htons(atoi(p));
1327 if(!inet_aton(args, &addr.sin_addr))
1329 newsk = netcsconn((struct sockaddr *)&addr, sizeof(addr), (void (*)(struct socket *, int, void *))peerconnect, fn);
1331 hubhandleaction(sk, fn, cmd, args);
1334 static void sendctm(struct socket *sk, char *nick)
1336 struct sockaddr *addr;
1341 if(sockgetremotename2(tcpsock, sk, &addr, &addrlen) < 0)
1343 if(addr->sa_family == AF_INET)
1344 qstrf(sk, "$ConnectToMe %s %s|", nick, formataddress(addr, addrlen));
1346 flog(LOG_WARNING, "Direct Connect TCP socket is suddenly not AF_INET, but %i", addr->sa_family);
1350 static void cmd_revconnecttome(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1356 if((p = strchr(args, ' ')) == NULL)
1359 if(strcmp(p, hub->nativenick))
1362 expectpeer(args, fn);
1363 hubhandleaction(sk, fn, cmd, args);
1366 static void cmd_getnetinfo(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1369 struct fnetnode *node;
1374 for(node = fnetnodes; node != NULL; node = node->next)
1376 if(node->state == FNN_EST)
1379 qstrf(sk, "$NetInfo %i$%i$%c$0|", confgetint("transfer", "slots"), numhubs, (tcpsock == NULL)?'P':'A');
1380 hubhandleaction(sk, fn, cmd, args);
1383 static void cmd_to(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1390 if((p2 = strchr(p, ' ')) == NULL)
1394 if((p2 = strchr(p, ' ')) == NULL)
1397 if(strcmp(p, "From:"))
1400 if((p2 = strstr(p, " $")) == NULL)
1404 hubrecvchat(hub->sk, fn, p, p2);
1405 hubhandleaction(sk, fn, cmd, args);
1408 static void cmd_sr(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1412 char *nick, *filename, *hubname;
1416 wchar_t *wnick, *wfile;
1420 if((p2 = strchr(p, ' ')) == NULL)
1425 if((p2 = strchr(p, 5)) == NULL)
1429 if((p2 = strchr(p, ' ')) == NULL)
1434 if((p2 = strchr(p, '/')) == NULL)
1439 if((p2 = strchr(p, 5)) == NULL)
1443 if((p2 = strstr(p, " (")) == NULL)
1446 if((wnick = icmbstowcs(nick, hub->charset)) == NULL)
1448 /* Use DCCHARSET in $Get paths until further researched... */
1449 if((wfile = icmbstowcs(filename, DCCHARSET)) == NULL)
1454 sr = newsrchres(&dcnet, wfile, wnick);
1455 if(sr->peernick != NULL)
1457 sr->peernick = swcsdup(wnick);
1462 if(!strncmp(hubname, "TTH:", 4))
1464 if((buf = base32decode(hubname + 4, &buflen)) != NULL)
1467 sr->hash = newhash(L"TTH", 24, buf);
1471 getfnetnode(sr->fn = fn);
1474 hubhandleaction(sk, fn, cmd, args);
1477 static void cmd_usercommand(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1479 /* Do nothing for now. */
1482 static void cmd_getpass(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1489 pw = wpfind(fn->args, L"password");
1490 if((pw == NULL) || ((mbspw = icwcstombs(pw, hub->charset)) == NULL))
1495 qstrf(sk, "$MyPass %s|", mbspw);
1497 fn->regstatus = FNNS_REG;
1498 hubhandleaction(sk, fn, cmd, args);
1501 static void cmd_logedin(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1506 fn->regstatus = FNNS_OP;
1507 hubhandleaction(sk, fn, cmd, args);
1510 static void cmd_hubsupports(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1516 size_t arrsize, arrdata;
1519 if(hub->supports != NULL)
1521 for(i = 0; hub->supports[i] != NULL; i++)
1522 free(hub->supports[i]);
1523 free(hub->supports);
1526 arrsize = arrdata = 0;
1530 if((p2 = strchr(p, ' ')) != NULL)
1534 addtobuf(arr, sstrdup(p));
1535 } while((p = p2) != NULL);
1536 addtobuf(arr, NULL);
1537 hub->supports = arr;
1540 static void cmd_mynick(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1542 struct dcexppeer *expect;
1545 if(peer->nativename != NULL)
1546 free(peer->nativename);
1547 peer->nativename = sstrdup(args);
1548 if(peer->wcsname != NULL)
1549 free(peer->wcsname);
1550 if((peer->wcsname = icmbstowcs(peer->nativename, peer->charset)) == NULL)
1557 for(expect = expected; expect != NULL; expect = expect->next)
1559 if(!strcmp(expect->nick, args))
1566 hub = expect->fn->data;
1567 peer->fn = expect->fn;
1568 getfnetnode(peer->fn);
1569 peer->dcppemu = hub->dcppemu;
1570 freeexppeer(expect);
1575 static void cmd_direction(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1579 struct transfer *transfer;
1581 if((p = strchr(args, ' ')) == NULL)
1584 if(!strcmp(args, "Upload"))
1586 if(!strcmp(args, "Download"))
1590 if((peer->transfer == NULL) || (mydir != peer->direction))
1595 if(peer->direction == TRNSD_DOWN)
1598 if(peer->wcsname == NULL)
1603 peer->direction = mydir;
1604 if(peer->direction == TRNSD_UP)
1606 if(confgetint("transfer", "ulquota") && hasupload(&dcnet, peer->wcsname))
1611 transfer = newupload(peer->fn, &dcnet, peer->wcsname, &dctransfer, peer);
1613 if((transfer = finddownload(peer->wcsname)) == NULL)
1618 transferattach(transfer, &dctransfer, peer);
1619 transfersetstate(transfer, TRNS_HS);
1621 transfersetnick(transfer, peer->wcsname);
1622 peer->transfer = transfer;
1625 qstrf(sk, "$Direction %s %i|", (peer->direction == TRNSD_UP)?"Upload":"Download", rand() % 10000);
1626 if(peer->key != NULL)
1627 qstrf(sk, "$Key %s|", peer->key);
1628 if(peer->direction == TRNSD_DOWN)
1633 static void cmd_peerlock(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1636 struct transfer *transfer;
1638 if((p = strchr(args, ' ')) == NULL)
1641 if(!strncmp(args, "EXTENDEDPROTOCOL", 16))
1643 key = dcmakekey(args);
1646 if(peer->wcsname == NULL)
1655 if((transfer = finddownload(peer->wcsname)) == NULL)
1657 if(confgetint("transfer", "ulquota") && hasupload(&dcnet, peer->wcsname))
1662 peer->direction = TRNSD_UP;
1663 transfer = newupload(peer->fn, &dcnet, peer->wcsname, &dctransfer, peer);
1665 peer->direction = TRNSD_DOWN;
1666 transferattach(transfer, &dctransfer, peer);
1667 transfersetstate(transfer, TRNS_HS);
1669 transfersetnick(transfer, peer->wcsname);
1670 peer->transfer = transfer;
1671 qstrf(sk, "$Direction %s %i|", (peer->direction == TRNSD_UP)?"Upload":"Download", rand() % 10000);
1672 qstrf(sk, "$Key %s|", key);
1675 if(peer->key != NULL)
1681 static void cmd_key(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1686 static void startdl(struct dcpeer *peer)
1688 if(peer->timeout != NULL)
1689 canceltimer(peer->timeout);
1690 peer->state = PEER_TRNS;
1691 transferstartdl(peer->transfer, peer->sk);
1692 peer->sk->readcb = (void (*)(struct socket *, void *))transread;
1693 peer->sk->errcb = (void (*)(struct socket *, int, void *))transerr;
1696 static void startul(struct dcpeer *peer)
1698 if(peer->timeout != NULL)
1699 canceltimer(peer->timeout);
1700 peer->state = PEER_TRNS;
1701 transferstartul(peer->transfer, peer->sk);
1702 peer->sk->writecb = (void (*)(struct socket *, void *))transwrite;
1705 static void cmd_filelength(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1708 struct transfer *transfer;
1710 if(peer->transfer == NULL)
1716 if(peer->transfer->size != size)
1718 transfersetsize(peer->transfer, size);
1719 transfer = peer->transfer;
1721 trytransferbypeer(transfer->fnet, transfer->peerid);
1725 qstr(peer->sk, "$Send|");
1728 static void cmd_error(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1730 if(peer->fetchingtthl)
1732 peer->fetchingtthl = 0;
1737 if((peer->transfer != NULL) && (peer->transfer->dir == TRNSD_DOWN))
1739 transferseterror(peer->transfer, TRNSE_NOTFOUND);
1740 resettransfer(peer->transfer);
1746 static void cmd_maxedout(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1748 if((peer->transfer != NULL) && (peer->transfer->dir == TRNSD_DOWN))
1750 transferseterror(peer->transfer, TRNSE_NOSLOTS);
1751 resettransfer(peer->transfer);
1764 {"MyList.DcLst", &hmlistname, updatehmlist},
1765 {"files.xml", &xmllistname, updatexmllist},
1766 {"files.xml.bz2", &xmlbz2listname, updatexmlbz2list},
1770 static int openfilelist(char *name)
1775 for(i = 0; lists[i].name != NULL; i++)
1777 if(!strcmp(name, lists[i].name))
1781 if(lists[i].name == NULL)
1784 if((*lists[i].file == NULL) || ((fd = open(*lists[i].file, O_RDONLY)) < 0))
1786 if((fd < 0) && ((*lists[i].file == NULL) || ((fd = open(*lists[i].file, O_RDONLY)) < 0)))
1789 flog(LOG_ERR, "could not open filelist tempfile: %s", strerror(errno));
1796 static struct sharecache *findbytth(char *tth32)
1800 struct sharecache *node;
1802 if((buf = base32decode(tth32, &buflen)) == NULL)
1809 for(node = shareroot->child; node != NULL; node = nextscnode(node))
1811 if(node->f.b.hastth && !memcmp(node->hashtth, buf, 24))
1818 static struct sharecache *resdcpath(char *path, char *charset, char sep)
1820 struct sharecache *node;
1827 if((p2 = strchr(p, sep)) != NULL)
1829 if((node = findcache(node, icsmbstowcs(p, charset, L""))) == NULL)
1836 static void cmd_get(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1841 struct sharecache *node;
1842 struct socket *lesk;
1846 if(peer->transfer == NULL)
1851 if((p = strchr(args, '$')) == NULL)
1857 if((offset = (atoi(p) - 1)) < 0)
1862 if(((fd = openfilelist(args)) < 0) && (errno != 0))
1864 qstr(sk, "$Error Could not send file list|");
1867 } else if(fd >= 0) {
1868 if((buf2 = icsmbstowcs(args, DCCHARSET, NULL)) != NULL)
1869 transfersetpath(peer->transfer, buf2);
1870 peer->transfer->flags.b.minislot = 1;
1874 /* Use DCCHARSET in $Get paths until further researched... */
1875 if((node = resdcpath(args, DCCHARSET, '\\')) == NULL)
1877 qstrf(sk, "$Error File not in share|");
1881 if((fd = opensharecache(node)) < 0)
1883 qstrf(sk, "$Error %s|", strerror(errno));
1887 buf = getfspath(node);
1888 if((buf2 = icsmbstowcs(buf, NULL, NULL)) == NULL)
1889 flog(LOG_WARNING, "could not convert native path into a wcs (%s): %s", buf, strerror(errno));
1891 transfersetpath(peer->transfer, buf2);
1894 if(fstat(fd, &sb) < 0)
1897 flog(LOG_WARNING, "could not stat file %ls: %s", node->name, strerror(errno));
1898 qstrf(sk, "$Error|");
1902 if(sb.st_size < 65536)
1903 peer->transfer->flags.b.minislot = 1;
1904 if(!peer->transfer->flags.b.minislot && (slotsleft() < 1)) {
1906 qstr(sk, "$MaxedOut|");
1910 if((offset != 0) && (lseek(fd, offset, SEEK_SET) < 0))
1913 qstrf(sk, "$Error Offset out of range|");
1917 lesk = wrapsock(fd);
1918 transferprepul(peer->transfer, sb.st_size, offset, -1, lesk);
1920 qstrf(sk, "$FileLength %zi|", peer->transfer->size);
1923 static void cmd_send(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1925 if(peer->transfer == NULL)
1930 if(peer->transfer->localend == NULL)
1939 static void cmd_supports(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1944 size_t arrsize, arrdata;
1946 if(peer->supports != NULL)
1948 for(i = 0; peer->supports[i] != NULL; i++)
1949 free(peer->supports[i]);
1950 free(peer->supports);
1953 arrsize = arrdata = 0;
1957 if((p2 = strchr(p, ' ')) != NULL)
1961 addtobuf(arr, sstrdup(p));
1962 } while((p = p2) != NULL);
1963 addtobuf(arr, NULL);
1964 peer->supports = arr;
1967 static void cmd_getblock(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1971 int start, numbytes;
1972 char *charset, *buf;
1974 struct sharecache *node;
1976 struct socket *lesk;
1978 if(peer->transfer == NULL)
1984 if((p2 = strchr(p, ' ')) == NULL)
1992 if((p2 = strchr(p, ' ')) == NULL)
2000 if(!strcmp(cmd, "$UGetBlock") || !strcmp(cmd, "$UGetZBlock"))
2003 /* Use DCCHARSET in $Get paths until further researched... */
2004 charset = DCCHARSET;
2005 if(!strcmp(cmd, "$GetZBlock") || !strcmp(cmd, "$UGetZBlock"))
2006 initcompress(peer, CPRS_ZLIB);
2007 if(((fd = openfilelist(p)) < 0) && (errno != 0))
2009 qstr(sk, "$Error Could not send file list|");
2011 } else if(fd >= 0) {
2012 if((buf2 = icsmbstowcs(args, charset, NULL)) != NULL)
2013 transfersetpath(peer->transfer, buf2);
2014 peer->transfer->flags.b.minislot = 1;
2018 if((node = resdcpath(p, charset, '\\')) == NULL)
2020 qstr(sk, "$Error File not in cache|");
2023 if((fd = opensharecache(node)) < 0)
2025 qstrf(sk, "$Error %s|", strerror(errno));
2028 buf = getfspath(node);
2029 if((buf2 = icsmbstowcs(buf, NULL, NULL)) == NULL)
2030 flog(LOG_WARNING, "could not convert native path into a wcs (%s): %s", buf, strerror(errno));
2032 transfersetpath(peer->transfer, buf2);
2035 if(fstat(fd, &sb) < 0)
2038 flog(LOG_WARNING, "could not stat file %ls: %s", node->name, strerror(errno));
2039 qstr(sk, "$Error|");
2042 if(sb.st_size < 65536)
2043 peer->transfer->flags.b.minislot = 1;
2044 if(!peer->transfer->flags.b.minislot && (slotsleft() < 1)) {
2046 qstr(sk, "$MaxedOut|");
2049 if((start != 0) && ((start >= sb.st_size) || (lseek(fd, start, SEEK_SET) < 0)))
2052 qstr(sk, "$Error Offset out of range|");
2055 if((numbytes < 0) || (start + numbytes > sb.st_size))
2056 numbytes = sb.st_size - start;
2057 lesk = wrapsock(fd);
2058 transferprepul(peer->transfer, sb.st_size, start, start + numbytes, lesk);
2060 qstrf(sk, "$Sending %i|", numbytes);
2064 static void cmd_adcget(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2068 int start, numbytes;
2069 struct sharecache *node;
2071 struct socket *lesk;
2075 if(peer->transfer == NULL)
2080 if((argv = parseadc(args)) == NULL)
2085 if(parrlen(argv) < 4)
2090 start = atoi(argv[2]);
2091 numbytes = atoi(argv[3]);
2094 if(((fd = openfilelist(argv[1])) < 0) && (errno != 0))
2096 qstr(sk, "$Error Could not send file list|");
2098 } else if(fd >= 0) {
2099 if((wbuf = icsmbstowcs(argv[1], "UTF-8", NULL)) != NULL)
2100 transfersetpath(peer->transfer, wbuf);
2101 peer->transfer->flags.b.minislot = 1;
2105 if(!strncmp(argv[1], "TTH/", 4))
2107 if((node = findbytth(argv[1] + 4)) == NULL)
2109 qstr(sk, "$Error File not in cache|");
2113 if((node = resdcpath((argv[1][0] == '/')?(argv[1] + 1):(argv[1]), "UTF-8", '/')) == NULL)
2115 qstr(sk, "$Error File not in cache|");
2119 if((fd = opensharecache(node)) < 0)
2121 qstrf(sk, "$Error %s|", strerror(errno));
2124 buf = getfspath(node);
2125 if((wbuf = icsmbstowcs(buf, NULL, NULL)) == NULL)
2126 flog(LOG_WARNING, "could not convert native path into a wcs (%s): %s", buf, strerror(errno));
2128 transfersetpath(peer->transfer, wbuf);
2131 if(!strcmp(argv[0], "file"))
2133 for(i = 4; argv[i] != NULL; i++)
2135 if(!strcmp(argv[i], "ZL1"))
2136 initcompress(peer, CPRS_ZLIB);
2138 if(fstat(fd, &sb) < 0)
2140 flog(LOG_WARNING, "could not stat file %ls: %s", node->name, strerror(errno));
2141 qstr(sk, "$Error|");
2144 if(sb.st_size < 65536)
2145 peer->transfer->flags.b.minislot = 1;
2146 if(!peer->transfer->flags.b.minislot && (slotsleft() < 1)) {
2147 qstr(sk, "$MaxedOut|");
2150 if((start != 0) && ((start >= sb.st_size) || (lseek(fd, start, SEEK_SET) < 0)))
2152 qstr(sk, "$Error Offset out of range|");
2155 if((numbytes < 0) || (start + numbytes > sb.st_size))
2156 numbytes = sb.st_size - start;
2157 lesk = wrapsock(fd);
2158 transferprepul(peer->transfer, sb.st_size, start, start + numbytes, lesk);
2161 qstr(sk, "$ADCSND");
2162 sendadc(sk, "file");
2163 sendadc(sk, argv[1]);
2164 sendadcf(sk, "%i", start);
2165 sendadcf(sk, "%i", numbytes);
2166 if(peer->compress == CPRS_ZLIB)
2170 } else if(!strcmp(argv[0], "tthl")) {
2172 * XXX: Implement full TTHL support.
2174 * In the meantime, this is better than nothing, since it at
2175 * least allows fetching of the TTH root if it isn't already
2180 qstr(sk, "$Error no TTHL data for virtual files|");
2183 qstr(sk, "$ADCSND");
2184 sendadc(sk, "tthl");
2185 sendadc(sk, argv[1]);
2189 sockqueue(sk, node->hashtth, 24);
2191 qstr(sk, "$Error Namespace not implemented|");
2201 static void handletthl(struct dcpeer *peer)
2205 while(peer->inbufdata >= 24)
2207 pushtigertree(&peer->tth, peer->inbuf);
2208 memmove(peer->inbuf, peer->inbuf + 24, peer->inbufdata -= 24);
2209 peer->curread += 24;
2211 if(peer->curread >= peer->totalsize)
2213 if(peer->timeout == NULL)
2214 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
2215 peer->state = PEER_CMD;
2216 synctigertree(&peer->tth);
2217 restigertree(&peer->tth, buf);
2218 transfersethash(peer->transfer, newhash(L"TTH", 24, buf));
2223 static void cmd_adcsnd(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2226 int start, numbytes;
2228 if(peer->transfer == NULL)
2233 if((argv = parseadc(args)) == NULL)
2238 if(parrlen(argv) < 4)
2243 start = atoi(argv[2]);
2244 numbytes = atoi(argv[3]);
2245 if(!strcmp(argv[0], "tthl"))
2247 if((start != 0) || (numbytes % 24 != 0))
2249 /* Weird. Bail out. */
2253 if(peer->timeout != NULL)
2254 canceltimer(peer->timeout);
2255 peer->state = PEER_TTHL;
2256 peer->totalsize = numbytes;
2258 peer->fetchingtthl = 0;
2259 inittigertree(&peer->tth);
2261 } else if(!strcmp(argv[0], "file")) {
2262 if(start != peer->transfer->curpos)
2267 if(start + numbytes != peer->transfer->size)
2269 transfersetsize(peer->transfer, start + numbytes);
2274 if(peer->inbufdata > 0)
2276 sockpushdata(sk, peer->inbuf, peer->inbufdata);
2277 peer->inbufdata = 0;
2278 transread(sk, peer);
2281 /* We certainly didn't request this...*/
2290 static void cmd_sending(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2294 if(peer->transfer == NULL)
2299 numbytes = atoi(args);
2300 if(peer->transfer->size - peer->transfer->curpos != numbytes)
2302 transfersetsize(peer->transfer, peer->transfer->curpos + numbytes);
2307 if(peer->inbufdata > 0)
2309 sockpushdata(sk, peer->inbuf, peer->inbufdata);
2310 peer->inbufdata = 0;
2311 transread(sk, peer);
2317 static void cmd_(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
2322 hubhandleaction(sk, fn, cmd, args);
2326 static void cmd_(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2332 static int hubreqconn(struct fnetpeer *peer)
2337 if((peer->fn->state != FNN_EST) || (peer->fn->fnet != &dcnet))
2342 if((hub = peer->fn->data) == NULL)
2347 if((mbsnick = icwcstombs(peer->id, hub->charset)) == NULL)
2348 return(1); /* Shouldn't happen, of course, but who knows... */
2351 sendctm(hub->sk, mbsnick);
2352 expectpeer(mbsnick, peer->fn);
2354 qstrf(hub->sk, "$RevConnectToMe %s %s|", hub->nativenick, mbsnick);
2360 static int hubsendchat(struct fnetnode *fn, int public, wchar_t *to, wchar_t *string)
2363 char *mbsstring, *mbsto;
2366 if((mbsto = icwcstombs(to, hub->charset)) == NULL)
2371 if((mbsstring = icwcstombs(string, hub->charset)) == NULL)
2376 if((strchr(mbsto, '|') != NULL) || (strchr(mbsto, ' ') != NULL))
2383 if(strchr(mbsstring, '|') != NULL)
2394 qstrf(hub->sk, "<%s> %s|", hub->nativenick, mbsstring);
2396 qstrf(hub->sk, "$To: %s From: %s $<%s> %s|", mbsto, hub->nativenick, hub->nativenick, mbsstring);
2399 qstrf(hub->sk, "$To: %s From: %s $<%s> %s|", mbsto, hub->nativenick, hub->nativenick, mbsstring);
2406 static void findsizelimit(struct sexpr *sexpr, int *min, int *max)
2408 int minl, maxl, minr, maxr, retmin, retmax;
2413 findsizelimit(sexpr->l, &minl, &maxl);
2414 findsizelimit(sexpr->r, &minr, &maxr);
2415 retmin = (minl > minr)?minl:minr;
2416 if((maxl != -1) && (maxr != -1))
2417 retmax = (maxl < maxr)?maxl:maxr;
2426 findsizelimit(sexpr->l, &minl, &maxl);
2427 findsizelimit(sexpr->r, &minr, &maxr);
2428 retmin = (minl < minr)?minl:minr;
2429 if((maxl == -1) || (maxr == -1))
2432 retmax = (maxl > maxr)?maxl:maxr;
2435 findsizelimit(sexpr->l, &minl, &maxl);
2436 if((minl == 0) && (maxl == -1)) /* Interval is unspecified */
2440 } else if((minl == 0) && (maxl != -1)) {
2443 } else if((minl != 0) && (maxl == -1)) {
2446 } else { /* This would yield two seperate intervals, which DC cannot handle */
2452 retmax = sexpr->d.n - 1;
2455 retmin = sexpr->d.n;
2456 retmax = sexpr->d.n;
2459 retmin = sexpr->d.n + 1;
2473 static struct hash *findsehash(struct sexpr *sexpr)
2475 struct hash *h1, *h2;
2480 if((h1 = findsehash(sexpr->l)) != NULL)
2482 if((h1 = findsehash(sexpr->r)) != NULL)
2486 if((h1 = findsehash(sexpr->l)) == NULL)
2488 if((h2 = findsehash(sexpr->r)) == NULL)
2494 if(!wcscmp(sexpr->d.hash->algo, L"TTH"))
2495 return(sexpr->d.hash);
2502 static int hubsearch(struct fnetnode *fn, struct search *srch, struct srchfnnlist *ln)
2505 struct wcslist *list, *cur;
2506 char *sstr, *buf, *p;
2507 size_t sstrsize, sstrdata;
2508 struct sockaddr *name;
2510 int minsize, maxsize;
2514 if((fn->state != FNN_EST) || (hub->sk == NULL) || (hub->sk->state != SOCK_EST))
2516 list = findsexprstrs(srch->sexpr);
2517 findsizelimit(srch->sexpr, &minsize, &maxsize);
2518 hash = findsehash(srch->sexpr);
2519 if((minsize != 0) && (maxsize != -1))
2521 /* Choose either minsize or maxsize by trying to determine
2522 * which choice will be most restrictive. The result can be
2523 * approximative at best anyway, so don't try too hard... */
2524 if((50000000 - maxsize) > (minsize - 50000000))
2530 sstrsize = sstrdata = 0;
2531 if((hash != NULL) && (hash->len == 24))
2533 /* Prioritize hash searches above all else */
2534 bufcat(sstr, "F?T?0?9?TTH:", 12);
2535 buf = base32encode(hash->buf, hash->len);
2537 bufcat(sstr, buf, 39);
2542 sizebuf2(sstr, sstrdata + 32, 1);
2543 sstrdata += snprintf(sstr + sstrdata, sstrsize - sstrdata, "T?F?%i?1?", minsize);
2544 } else if(maxsize != -1) {
2545 sizebuf2(sstr, sstrdata + 32, 1);
2546 sstrdata += snprintf(sstr + sstrdata, sstrsize - sstrdata, "T?T?%i?1?", maxsize);
2548 bufcat(sstr, "F?F?0?1?", 8);
2552 for(cur = list; cur != NULL; cur = cur->next)
2554 /* Use DCCHARSET in $Get paths until further researched... */
2555 if((buf = icwcstombs(cur->str, DCCHARSET)) == NULL)
2557 /* Can't find anything anyway if the search expression
2558 * requires characters outside DC's charset. There's
2559 * nothing technically wrong with the search itself,
2560 * however, so return success. This should be
2561 * considered as an optimization. */
2568 addtobuf(sstr, '$');
2570 * It probably doesn't hurt if buf contains any extra
2571 * dollar signs - it will just result in extra search
2572 * terms, and the extraneous results will be filtered by
2573 * the search layer anyway. It hurts if it contains any
2574 * pipes, though, so let's sell them for money.
2576 for(p = buf; *p; p++)
2581 bufcat(sstr, buf, strlen(buf));
2585 /* Will match all files... :-/ */
2586 addtobuf(sstr, '.');
2592 if(sockgetremotename2(udpsock, hub->sk, &name, &namelen) < 0)
2594 flog(LOG_WARNING, "cannot get address of UDP socket");
2596 qstrf(hub->sk, "$Search %s %s|", formataddress(name, namelen), sstr);
2600 qstrf(hub->sk, "$Search Hub:%s %s|", hub->nativenick, sstr);
2604 fn->lastsrch = time(NULL);
2612 #define cc(c) ((void (*)(struct socket *, void *, char *, char *))(c))
2613 static struct command hubcmds[] =
2615 {"$Lock", cc(cmd_lock)},
2616 {"$HubName", cc(cmd_hubname)},
2617 {"$Hello", cc(cmd_hello)},
2618 {"$Quit", cc(cmd_quit)},
2619 {"$NickList", cc(cmd_nicklist)},
2620 {"$OpList", cc(cmd_oplist)},
2621 {"$MyINFO", cc(cmd_myinfo)},
2622 {"$ForceMove", cc(cmd_forcemove)},
2623 {"$Search", cc(cmd_search)},
2624 {"$MultiSearch", cc(cmd_search)},
2625 {"$ConnectToMe", cc(cmd_connecttome)},
2626 {"$RevConnectToMe", cc(cmd_revconnecttome)},
2627 {"$GetNetInfo", cc(cmd_getnetinfo)},
2628 {"$To:", cc(cmd_to)},
2629 {"$SR", cc(cmd_sr)},
2630 {"$UserCommand", cc(cmd_usercommand)},
2631 {"$GetPass", cc(cmd_getpass)},
2632 {"$LogedIn", cc(cmd_logedin)}, /* sic */
2633 {"$Supports", cc(cmd_hubsupports)},
2637 static struct command peercmds[] =
2639 {"$MyNick", cc(cmd_mynick)},
2640 {"$Lock", cc(cmd_peerlock)},
2641 {"$Direction", cc(cmd_direction)},
2642 {"$Key", cc(cmd_key)},
2643 {"$FileLength", cc(cmd_filelength)},
2644 {"$Error", cc(cmd_error)},
2645 {"$MaxedOut", cc(cmd_maxedout)},
2646 {"$Get", cc(cmd_get)},
2647 {"$Send", cc(cmd_send)},
2648 {"$Supports", cc(cmd_supports)},
2649 {"$GetBlock", cc(cmd_getblock)},
2650 {"$UGetBlock", cc(cmd_getblock)},
2651 {"$GetZBlock", cc(cmd_getblock)},
2652 {"$UGetZBlock", cc(cmd_getblock)},
2653 {"$ADCGET", cc(cmd_adcget)},
2654 {"$ADCSND", cc(cmd_adcsnd), 1},
2655 {"$Sending", cc(cmd_sending), 1},
2660 static void dctransdetach(struct transfer *transfer, struct dcpeer *peer)
2662 CBUNREG(transfer, trans_filterout, peer);
2665 peer->transfer = NULL;
2669 static void dctransgotdata(struct transfer *transfer, struct dcpeer *peer)
2673 unsigned char outbuf[1024];
2677 if((peer->state == PEER_TRNS) || (peer->state == PEER_SYNC))
2679 if(sockqueuesize(peer->sk) < 65536)
2681 if((buf = transfergetdata(transfer, &bufsize)) != NULL)
2683 if(peer->compress == CPRS_NONE)
2685 sockqueue(peer->sk, buf, bufsize);
2686 } else if(peer->compress == CPRS_ZLIB) {
2687 cstr = peer->cprsdata;
2688 cstr->next_in = buf;
2689 cstr->avail_in = bufsize;
2690 while(cstr->avail_in > 0)
2692 cstr->next_out = outbuf;
2693 cstr->avail_out = sizeof(outbuf);
2694 if((ret = deflate(cstr, 0)) != Z_OK)
2696 flog(LOG_WARNING, "bug? deflate() did not return Z_OK (but rather %i)", ret);
2700 sockqueue(peer->sk, outbuf, sizeof(outbuf) - cstr->avail_out);
2705 if(peer->state == PEER_SYNC)
2707 if(peer->compress == CPRS_ZLIB)
2709 cstr = peer->cprsdata;
2710 cstr->next_in = NULL;
2714 cstr->next_out = outbuf;
2715 cstr->avail_out = sizeof(outbuf);
2716 ret = deflate(cstr, Z_FINISH);
2717 if((ret != Z_OK) && (ret != Z_STREAM_END))
2719 flog(LOG_WARNING, "bug? deflate(Z_FINISH) did not return Z_OK (but rather %i)", ret);
2723 sockqueue(peer->sk, outbuf, sizeof(outbuf) - cstr->avail_out);
2724 } while(ret != Z_STREAM_END);
2730 if(peer->timeout == NULL)
2731 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
2732 peer->state = PEER_CMD;
2734 transfersetstate(transfer, TRNS_HS);
2735 socksettos(peer->sk, confgetint("fnet", "fnptos"));
2736 transfer->flags.b.minislot = 0;
2737 peer->sk->writecb = NULL;
2744 static void dctransendofdata(struct transfer *transfer, struct dcpeer *peer)
2746 peer->state = PEER_SYNC;
2747 dctransgotdata(transfer, peer);
2750 static void dcwantdata(struct transfer *transfer, struct dcpeer *peer)
2752 if(transferdatasize(transfer) < 65536)
2753 peer->sk->ignread = 0;
2756 static void transread(struct socket *sk, struct dcpeer *peer)
2760 struct transfer *transfer;
2762 if((buf = sockgetinbuf(sk, &bufsize)) == NULL)
2764 if(peer->transfer == NULL)
2770 transferputdata(peer->transfer, buf, bufsize);
2772 if(peer->transfer->curpos >= peer->transfer->size)
2774 transfer = peer->transfer;
2775 transferdetach(transfer);
2776 transferendofdata(transfer);
2779 if(transferdatasize(peer->transfer) > 65535)
2783 static void transerr(struct socket *sk, int err, struct dcpeer *peer)
2785 struct transfer *transfer;
2787 if((transfer = peer->transfer) == NULL)
2792 transferdetach(transfer);
2793 transferendofdata(transfer);
2796 static void transwrite(struct socket *sk, struct dcpeer *peer)
2798 if((peer->state != PEER_TRNS) && (peer->state != PEER_SYNC))
2800 if(peer->transfer == NULL)
2805 dctransgotdata(peer->transfer, peer);
2808 static void udpread(struct socket *sk, void *data)
2810 char *buf, *p, *p2, *hashbuf;
2811 size_t buflen, hashlen;
2812 char *nick, *filename, *hubname;
2813 struct sockaddr_in hubaddr;
2815 struct fnetnode *fn, *myfn;
2818 wchar_t *wnick, *wfile;
2821 if((buf = sockgetinbuf(sk, &buflen)) == NULL)
2823 buf = srealloc(buf, buflen + 1);
2825 if(!strncmp(buf, "$SR ", 4))
2829 if((p2 = strchr(p, ' ')) == NULL)
2837 if((p2 = strchr(p, 5)) == NULL)
2844 if((p2 = strchr(p, ' ')) == NULL)
2852 if((p2 = strchr(p, '/')) == NULL)
2860 if((p2 = strchr(p, 5)) == NULL)
2867 if((p2 = strstr(p, " (")) == NULL)
2874 if((p2 = strchr(p, ':')) == NULL)
2880 hubaddr.sin_family = AF_INET;
2881 if(!inet_aton(p, &hubaddr.sin_addr))
2887 if((p2 = strchr(p, ')')) == NULL)
2893 hubaddr.sin_port = htons(atoi(p));
2894 /* Use DCCHARSET in $Get paths until further researched... */
2895 if((wfile = icmbstowcs(filename, DCCHARSET)) == NULL)
2902 if(!strncmp(hubname, "TTH:", 4))
2904 if((hashbuf = base32decode(hubname + 4, &hashlen)) != NULL)
2907 hash = newhash(L"TTH", 24, hashbuf);
2911 for(fn = fnetnodes; fn != NULL; fn = fn->next)
2913 if((fn->fnet == &dcnet) && ((hub = fn->data) != NULL))
2915 if((hub->nativename != NULL) && !strcmp(hub->nativename, hubname))
2930 for(fn = fnetnodes; fn != NULL; fn = fn->next)
2932 if((fn->fnet == &dcnet) && ((hub = fn->data) != NULL))
2934 if((hub->sk != NULL) && addreq(hub->sk->remote, (struct sockaddr *)&hubaddr))
2945 if((wnick = icmbstowcs(nick, (hub == NULL)?DCCHARSET:(hub->charset))) == NULL)
2950 sr = newsrchres(&dcnet, wfile, wnick);
2951 if(sr->peernick != NULL)
2953 sr->peernick = swcsdup(wnick);
2959 getfnetnode(sr->fn = myfn);
2968 static void hubread(struct socket *sk, struct fnetnode *fn)
2975 hub = (struct dchub *)fn->data;
2976 if((newbuf = sockgetinbuf(sk, &datalen)) == NULL)
2978 if(hub->inbufdata > 500000) /* Discard possible malicious data */
2980 sizebuf2(hub->inbuf, hub->inbufdata + datalen, 1);
2981 memcpy(hub->inbuf + hub->inbufdata, newbuf, datalen);
2983 p = hub->inbuf + hub->inbufdata;
2984 hub->inbufdata += datalen;
2985 while((datalen > 0) && ((p = memchr(p, '|', datalen)) != NULL))
2988 newqcmd(&hub->queue, hub->inbuf);
2989 memmove(hub->inbuf, p, hub->inbufdata -= p - hub->inbuf);
2990 datalen = hub->inbufdata;
2995 static void huberr(struct socket *sk, int err, struct fnetnode *fn)
3000 static int hubsetnick(struct fnetnode *fn, wchar_t *newnick)
3006 if((buf = icwcstombs(newnick, (hub == NULL)?DCCHARSET:(hub->charset))) == NULL)
3008 if((strchr(buf, ' ') != NULL) || (strchr(buf, '|') != NULL) || (strchr(buf, '$') != NULL))
3013 if(hub == NULL) /* Not yet connected */
3018 if(hub->nativenick != NULL)
3019 free(hub->nativenick);
3020 hub->nativenick = buf;
3024 static struct dchub *newdchub(struct fnetnode *fn)
3031 new = smalloc(sizeof(*new));
3032 memset(new, 0, sizeof(*new));
3034 if(confgetint("dc", "dcppemu"))
3036 if((emu = wpfind(fn->args, L"dcppemu")) != NULL)
3044 if((wcharset = wpfind(fn->args, L"charset")) != NULL)
3046 if((charset = icwcstombs(wcharset, "US-ASCII")) != NULL)
3048 if(!havecharset(charset))
3056 new->charset = charset;
3058 new->charset = sstrdup(DCCHARSET);
3059 if(hubsetnick(fn, fn->mynick))
3060 fnetsetnick(fn, L"DoldaConnectUser-IN");
3061 /* IN as in Invalid Nick */
3065 static struct dcpeer *newdcpeer(struct socket *sk)
3069 new = smalloc(sizeof(*new));
3070 memset(new, 0, sizeof(*new));
3071 new->transfer = NULL;
3074 if(confgetint("dc", "dcppemu"))
3085 static void freedcpeer(struct dcpeer *peer)
3088 struct qcommand *qcmd;
3093 if(peer->next != NULL)
3094 peer->next->prev = peer->prev;
3095 if(peer->prev != NULL)
3096 peer->prev->next = peer->next;
3097 if(peer->transfer != NULL)
3099 if(peer->transfer->dir == TRNSD_UP)
3100 peer->transfer->close = 1;
3101 if(peer->transfer->dir == TRNSD_DOWN)
3102 resettransfer(peer->transfer);
3103 transferdetach(peer->transfer);
3105 if(peer->timeout != NULL)
3106 canceltimer(peer->timeout);
3107 if(peer->sk->data == peer)
3108 peer->sk->data = NULL;
3109 peer->sk->readcb = NULL;
3110 peer->sk->writecb = NULL;
3111 peer->sk->errcb = NULL;
3114 if(peer->supports != NULL)
3116 for(i = 0; peer->supports[i] != NULL; i++)
3117 free(peer->supports[i]);
3118 free(peer->supports);
3120 if(peer->inbuf != NULL)
3122 if(peer->key != NULL)
3124 if(peer->wcsname != NULL)
3125 free(peer->wcsname);
3126 if(peer->nativename != NULL)
3127 free(peer->nativename);
3128 if(peer->charset != NULL)
3129 free(peer->charset);
3130 if(peer->fn != NULL)
3131 putfnetnode(peer->fn);
3132 while((qcmd = ulqcmd(&peer->queue)) != NULL)
3138 static void hubconnect(struct fnetnode *fn, struct socket *sk)
3142 sk->readcb = (void (*)(struct socket *, void *))hubread;
3143 sk->errcb = (void (*)(struct socket *, int, void *))huberr;
3144 fn->data = hub = newdchub(fn);
3146 getsock(hub->sk = sk);
3150 static void hubdestroy(struct fnetnode *fn)
3154 struct qcommand *qcmd;
3156 hub = (struct dchub *)fn->data;
3158 while((qcmd = ulqcmd(&hub->queue)) != NULL)
3160 if(hub->supports != NULL)
3162 for(i = 0; hub->supports[i] != NULL; i++)
3163 free(hub->supports[i]);
3164 free(hub->supports);
3166 if(hub->nativename != NULL)
3167 free(hub->nativename);
3168 if(hub->nativenick != NULL)
3169 free(hub->nativenick);
3170 if(hub->charset != NULL)
3172 if(hub->inbuf != NULL)
3177 static void hubkill(struct fnetnode *fn)
3181 hub = (struct dchub *)fn->data;
3185 static wchar_t *dcbasename(wchar_t *filename)
3189 if((ret = wcsrchr(filename, L'\\')) != NULL)
3194 static struct transferiface dctransfer =
3196 .detach = (void (*)(struct transfer *, void *))dctransdetach,
3197 .gotdata = (void (*)(struct transfer *, void *))dctransgotdata,
3198 .endofdata = (void (*)(struct transfer *, void *))dctransendofdata,
3199 .wantdata = (void (*)(struct transfer *, void *))dcwantdata
3202 static struct fnet dcnet =
3205 .connect = hubconnect,
3206 .destroy = hubdestroy,
3208 .setnick = hubsetnick,
3209 .reqconn = hubreqconn,
3210 .sendchat = hubsendchat,
3211 .search = hubsearch,
3212 .filebasename = dcbasename
3215 static void peerread(struct socket *sk, struct dcpeer *peer)
3219 struct command *cmd;
3221 if((newbuf = sockgetinbuf(sk, &datalen)) == NULL)
3223 sizebuf2(peer->inbuf, peer->inbufdata + datalen, 1);
3224 memcpy(peer->inbuf + peer->inbufdata, newbuf, datalen);
3226 peer->inbufdata += datalen;
3227 if(peer->state == PEER_CMD)
3230 while((peer->inbufdata > 0) && (p = memchr(peer->inbuf, '|', peer->inbufdata)) != NULL)
3233 newqcmd(&peer->queue, peer->inbuf);
3234 for(cmd = peercmds; cmd->handler != NULL; cmd++)
3236 if(!memcmp(peer->inbuf, cmd->name, strlen(cmd->name)) && ((peer->inbuf[strlen(cmd->name)] == ' ') || (peer->inbuf[strlen(cmd->name)] == '|')))
3239 memmove(peer->inbuf, p, peer->inbufdata -= p - peer->inbuf);
3242 peer->state = PEER_STOP;
3246 } else if(peer->state == PEER_TTHL) {
3251 static void peererror(struct socket *sk, int err, struct dcpeer *peer)
3256 static void peerconnect(struct socket *sk, int err, struct fnetnode *fn)
3258 struct dcpeer *peer;
3268 peer = newdcpeer(sk);
3271 peer->dcppemu = hub->dcppemu;
3272 sk->readcb = (void (*)(struct socket *, void *))peerread;
3273 sk->errcb = (void (*)(struct socket *, int, void *))peererror;
3275 socksettos(sk, confgetint("fnet", "fnptos"));
3277 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
3282 static void peeraccept(struct socket *sk, struct socket *newsk, void *data)
3284 struct dcpeer *peer;
3286 peer = newdcpeer(newsk);
3288 newsk->readcb = (void (*)(struct socket *, void *))peerread;
3289 newsk->errcb = (void (*)(struct socket *, int, void *))peererror;
3291 socksettos(newsk, confgetint("fnet", "fnptos"));
3292 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
3295 static void updatehmlist(void)
3297 int i, lev, ic, ret;
3298 struct sharecache *node;
3299 char *buf, *buf2, numbuf[32];
3300 size_t bufsize, bufdata;
3304 buf = smalloc(bufsize = 65536);
3305 node = shareroot->child;
3310 /* Use DCCHARSET in $Get paths until further researched... */
3311 if((buf2 = icwcstombs(node->name, DCCHARSET)) != NULL)
3313 for(i = 0; i < lev; i++)
3315 bufcat(buf, buf2, strlen(buf2));
3317 if(node->f.b.type == FILE_REG)
3320 sprintf(numbuf, "%zi", node->size);
3321 bufcat(buf, numbuf, strlen(numbuf));
3328 if((node->child != NULL) && !ic)
3332 } else if(node->next != NULL) {
3335 while(node->next == NULL)
3338 node = node->parent;
3339 if(node == shareroot)
3342 if(node == shareroot)
3347 if(hmlistname != NULL)
3352 hmlistname = sstrdup("/tmp/dc-filelist-hm-XXXXXX");
3353 if((fd = mkstemp(hmlistname)) < 0)
3355 flog(LOG_WARNING, "could not create HM file list tempfile: %s", strerror(errno));
3360 * I do not want to implement a good Huffman encoder, and it's not
3361 * like Huffman encoding actually yields any impressive results
3362 * for DC file lists anyway, so I'll just output a bogus
3363 * tree. Implement a good encoder if you want to.
3365 write(fd, "HE3\r\0", 5);
3366 write(fd, &bufdata, 4);
3368 write(fd, &ibuf, 2);
3370 for(i = 0; i < 256; i++)
3373 write(fd, &ibuf, 1);
3375 for(i = 0; i < 256; i++)
3377 for(buf2 = buf; bufdata > 0;)
3379 if((ret = write(fd, buf2, bufdata)) < 0)
3381 flog(LOG_WARNING, "could not write file list: %s", strerror(errno));
3392 static struct xmlent
3399 /* {L'\'', L"""}, Emulate DC++ escaping by omitting this. */
3403 static wchar_t *escapexml(wchar_t *src)
3405 static wchar_t *buf = NULL;;
3408 size_t bufsize, bufdata;
3414 bufsize = bufdata = 0;
3415 for(; *src != L'\0'; src++)
3418 if((c > 0) && (c < 32))
3420 bufcat(buf, L"&#", 2);
3421 ret = swprintf(nbuf, (sizeof(nbuf) / sizeof(*nbuf)), L"%i", c);
3422 bufcat(buf, nbuf, ret);
3423 addtobuf(buf, L';');
3425 for(ent = entities; ent->ent != NULL; ent++)
3429 bufcat(buf, ent->ent, wcslen(ent->ent));
3433 if(ent->ent == NULL)
3434 addtobuf(buf, *src);
3437 addtobuf(buf, L'\0');
3441 static void updatexmllist(void)
3445 char cidbuf[14], *namebuf;
3447 struct sharecache *node;
3449 if(xmllistname != NULL)
3451 unlink(xmllistname);
3454 xmllistname = sstrdup("/tmp/dc-filelist-dcxml-XXXXXX");
3455 if((fd = mkstemp(xmllistname)) < 0)
3457 flog(LOG_WARNING, "could not create XML file list tempfile: %s", strerror(errno));
3462 if((fs = fdopen(fd, "w")) == NULL)
3464 flog(LOG_WARNING, "could not fdopen XML list fd %i: %s", fd, strerror(errno));
3465 unlink(xmllistname);
3471 fprintf(fs, "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>\r\n");
3472 for(i = 0; i < sizeof(cidbuf) - 1; i++)
3473 cidbuf[i] = (rand() % ('Z' - 'A' + 1)) + 'A';
3475 if(confgetint("dc", "dcppemu"))
3476 fprintf(fs, "<FileListing Version=\"1\" CID=\"%s\" Base=\"/\" Generator=\"DC++ 0.674\">\r\n", cidbuf);
3478 fprintf(fs, "<FileListing Version=\"1\" CID=\"%s\" Base=\"/\" Generator=\"%s\">\r\n", cidbuf, "DoldaConnect" VERSION);
3480 node = shareroot->child;
3484 if((namebuf = icswcstombs(escapexml(node->name), "UTF-8", NULL)) != NULL)
3486 for(i = 0; i < lev; i++)
3488 if(node->child != NULL)
3490 fprintf(fs, "<Directory Name=\"%s\">\r\n", namebuf);
3495 fprintf(fs, "<File Name=\"%s\" Size=\"%zi\"", namebuf, node->size);
3496 if(node->f.b.hastth)
3498 hashbuf = base32encode(node->hashtth, 24);
3499 fprintf(fs, " TTH=\"%.39s\"", hashbuf);
3502 fprintf(fs, "/>\r\n");
3504 while(node->next == NULL)
3506 node = node->parent;
3507 if(node == shareroot)
3512 for(i = 0; i < lev; i++)
3514 fprintf(fs, "</Directory>\r\n");
3517 if(node == shareroot)
3523 if(confgetint("dc", "dcppemu"))
3524 fprintf(fs, "</FileListing>");
3526 fprintf(fs, "</FileListing>\r\n");
3530 static void updatexmlbz2list(void)
3539 if(xmllistname == NULL)
3541 if((in = fopen(xmllistname, "r")) == NULL)
3543 flog(LOG_WARNING, "could not open XML file list for bzipping: %s", strerror(errno));
3546 if(xmlbz2listname != NULL)
3548 unlink(xmlbz2listname);
3549 free(xmlbz2listname);
3551 xmlbz2listname = sstrdup("/tmp/dc-filelist-dcxmlbz2-XXXXXX");
3552 if((fd = mkstemp(xmlbz2listname)) < 0)
3554 flog(LOG_WARNING, "could not create bzipped XML file list tempfile: %s", strerror(errno));
3555 free(xmlbz2listname);
3556 xmlbz2listname = NULL;
3560 if((real = fdopen(fd, "w")) == NULL)
3562 flog(LOG_WARNING, "could not fdopen bzipped XML list fd %i: %s", fd, strerror(errno));
3564 unlink(xmlbz2listname);
3565 free(xmlbz2listname);
3566 xmlbz2listname = NULL;
3570 out = BZ2_bzWriteOpen(&err, real, 9, 0, 0);
3573 flog(LOG_WARNING, "could not open bzip2 stream from XML list");
3575 unlink(xmlbz2listname);
3576 free(xmlbz2listname);
3577 xmlbz2listname = NULL;
3583 bufdata = fread(buf, 1, sizeof(buf), in);
3584 BZ2_bzWrite(&err, out, buf, bufdata);
3587 BZ2_bzWriteClose(&err, out, 0, NULL, NULL);
3591 static void listtimercb(int cancelled, void *uudata)
3593 listwritetimer = NULL;
3598 static void updatelists(int now)
3600 if((hmlistname == NULL) || (xmllistname == NULL) || (xmlbz2listname == NULL))
3604 if(listwritetimer == NULL)
3605 listwritetimer = timercallback(ntime() + confgetint("cli", "hashwritedelay"), listtimercb, NULL);
3608 if(listwritetimer != NULL)
3609 canceltimer(listwritetimer);
3615 static int shareupdate(unsigned long long uusharesize, void *data)
3621 static char *quotestr(char *str)
3625 size_t bufsize, bufdata;
3627 static char *enc = NULL;
3628 size_t encsize, encdata;
3631 bufsize = bufdata = 0;
3632 for(p = (unsigned char *)str; *p; p++)
3635 bufcat(buf, "\\b", 2);
3637 bufcat(buf, "\\t", 2);
3639 bufcat(buf, "\\n", 2);
3641 bufcat(buf, "\\r", 2);
3643 bufcat(buf, "\\\\", 2);
3647 bprintf(buf, "\\x%02x", *p);
3653 if((wbuf = icmbstowcs((char *)buf, DCCHARSET)) != NULL)
3655 enc = icwcstombs(wbuf, NULL);
3660 encsize = encdata = 0;
3661 for(p = buf; *p; p++) {
3665 bprintf(buf, "\\x%x", *p);
3672 static void logunimpl(char *list, char *cmd, char *args)
3676 if((log = fopen("/tmp/dc-unimpl", "a")) == NULL)
3678 flog(LOG_WARNING, "could not open unimpl log: %s", strerror(errno));
3683 fputs(quotestr(cmd), log);
3687 fputs(quotestr(args), log);
3693 static void dispatchcommand(struct qcommand *qcmd, struct command *cmdlist, struct socket *sk, void *data)
3696 struct command *cmd;
3698 if((p = strchr(qcmd->string, ' ')) != NULL)
3700 for(cmd = cmdlist; cmd->handler != NULL; cmd++)
3702 if(!strcmp(cmd->name, qcmd->string))
3705 if(cmd->handler != NULL)
3707 cmd->handler(sk, data, qcmd->string, p);
3708 } else if(confgetint("dc", "logunimpl")) {
3709 if(cmdlist == hubcmds)
3710 logunimpl("hub", qcmd->string, p);
3711 else if(cmdlist == peercmds)
3712 logunimpl("peer", qcmd->string, p);
3714 logunimpl("other?!", qcmd->string, p);
3718 static int run(void)
3720 struct fnetnode *fn, *nextfn;
3722 struct dcpeer *peer, *nextpeer;
3723 struct qcommand *qcmd;
3727 for(fn = fnetnodes; fn != NULL; fn = nextfn)
3730 if(fn->fnet != &dcnet)
3732 if(fn->data == NULL)
3734 hub = (struct dchub *)fn->data;
3735 if((qcmd = ulqcmd(&hub->queue)) != NULL)
3737 if(*qcmd->string == '$')
3739 if((hub->sk != NULL) && (hub->sk->state == SOCK_EST))
3740 dispatchcommand(qcmd, hubcmds, hub->sk, fn);
3741 } else if(*qcmd->string != 0) {
3742 hubrecvchat(hub->sk, fn, NULL, qcmd->string);
3749 for(peer = peers; peer != NULL; peer = nextpeer)
3751 nextpeer = peer->next;
3752 if((qcmd = ulqcmd(&peer->queue)) != NULL)
3754 if(peer->timeout != NULL)
3755 canceltimer(peer->timeout);
3756 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
3757 if(*qcmd->string == '$')
3758 dispatchcommand(qcmd, peercmds, peer->sk, peer);
3767 static void preinit(int hup)
3774 static int updateudpport(struct configvar *var, void *uudata)
3776 struct sockaddr_in addr;
3777 struct socket *newsock;
3779 memset(&addr, 0, sizeof(addr));
3780 addr.sin_family = AF_INET;
3781 addr.sin_port = htons(var->val.num);
3782 if((newsock = netcsdgram((struct sockaddr *)&addr, sizeof(addr))) == NULL)
3784 flog(LOG_WARNING, "could not create new DC UDP socket, reverting to old: %s", strerror(errno));
3787 newsock->readcb = udpread;
3794 static int updatetcpport(struct configvar *var, void *uudata)
3796 struct sockaddr_in addr;
3797 struct socket *newsock;
3799 memset(&addr, 0, sizeof(addr));
3800 addr.sin_family = AF_INET;
3801 addr.sin_port = htons(var->val.num);
3802 if((newsock = netcslisten(SOCK_STREAM, (struct sockaddr *)&addr, sizeof(addr), peeraccept, NULL)) == NULL)
3803 flog(LOG_INFO, "could not listen to a remote address, going into passive mode");
3810 static int init(int hup)
3812 struct sockaddr_in addr;
3816 GCBREG(sharechangecb, shareupdate, NULL);
3821 addr.sin_family = AF_INET;
3822 memset(&addr.sin_addr, 0, sizeof(addr.sin_addr));
3823 addr.sin_port = htons(confgetint("dc", "udpport"));
3824 if((udpsock = netcsdgram((struct sockaddr *)&addr, sizeof(addr))) == NULL)
3826 flog(LOG_CRIT, "could not create DC UDP socket: %s", strerror(errno));
3829 udpsock->readcb = udpread;
3830 addr.sin_port = htons(confgetint("dc", "tcpport"));
3831 if((tcpsock = netcslisten(SOCK_STREAM, (struct sockaddr *)&addr, sizeof(addr), peeraccept, NULL)) == NULL)
3832 flog(LOG_INFO, "could not listen to a remote address, going into passive mode");
3833 CBREG(confgetvar("dc", "udpport"), conf_update, updateudpport, NULL, NULL);
3834 CBREG(confgetvar("dc", "tcpport"), conf_update, updatetcpport, NULL, NULL);
3835 CBREG(confgetvar("net", "mode"), conf_update, updatetcpport, NULL, NULL);
3840 static void terminate(void)
3842 if(hmlistname != NULL)
3847 if(xmllistname != NULL)
3849 unlink(xmllistname);
3852 if(xmlbz2listname != NULL)
3854 unlink(xmlbz2listname);
3855 free(xmlbz2listname);
3859 static struct configvar myvars[] =
3861 /** Specifies the share description reported to other DC users. */
3862 {CONF_VAR_STRING, "desc", {.str = L""}},
3863 /** Specifies the speed reported to other DC users. Normal values
3864 * are 28.8Kbps, 33.6Kbps, 56Kbps, Satellite, ISDN, DSL, Cable,
3865 * LAN(T1) or LAN(T3)*/
3866 {CONF_VAR_STRING, "speedstring", {.str = L"LAN(T1)"}},
3867 /** The e-mail address to report to other DC users. */
3868 {CONF_VAR_STRING, "email", {.str = L"spam@spam.org"}},
3869 /** Specifies a specific UDP port to use for DC search results. If
3870 * left unspecified, a port is allocated dynamically. Useful for
3871 * NAT routers (see also the net.visibleipv4 address for those
3873 {CONF_VAR_INT, "udpport", {.num = 0}},
3874 /** Specifies a specific TCP port to use for DC peer
3875 * connections. If left unspecified, a port is allocated
3876 * dynamically. Useful for NAT routers (see also the
3877 * net.visibleipv4 address for those cases). */
3878 {CONF_VAR_INT, "tcpport", {.num = 0}},
3879 /** If set to true, doldacond will do its best to emulate DC++
3880 * (currently v0.674). This should be left off if at all possible,
3881 * since turning it on will violate the rules of most hubs and
3882 * thus give hub owners an actual reason to kick you if it is
3883 * detected. It might be needed for some of the more bone-headed
3884 * hub owners, though. Note that DC++ emulation can also be turned
3885 * on or off for individual hubs, overriding this setting. */
3886 {CONF_VAR_BOOL, "dcppemu", {.num = 0}},
3887 /** Use for debugging. If set to true, doldacond will log all
3888 * unknown commands it receives, and their arguments, to
3889 * /tmp/dc-unimpl. */
3890 {CONF_VAR_BOOL, "logunimpl", {.num = 0}},
3891 /** If set to true, doldacond will hide its support for deflate
3892 * compression of transfers from other clients, so that they will
3893 * not request compressed uploads. Compressed transfers may
3894 * consume a non-trivial amount of CPU time on slower machines. */
3895 {CONF_VAR_BOOL, "hidedeflate", {.num = 0}},
3899 static struct module me =
3908 .terminate = terminate,