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);
99 struct qcommand *next;
105 struct qcommand *f, *l;
113 size_t inbufdata, inbufsize;
114 struct qcmdqueue queue;
115 int extended, dcppemu;
124 struct dcexppeer *next, *prev;
127 struct timer *expire;
132 struct dcpeer *next, *prev;
136 size_t inbufdata, inbufsize;
137 off_t curread, totalsize;
139 struct timer *timeout;
140 struct qcmdqueue queue;
141 struct transfer *transfer;
143 int ptclose; /* Close after transfer is complete */
144 int accepted; /* If false, we connected, otherwise, we accepted */
145 int extended, dcppemu;
146 int direction; /* Using the constants from transfer.h */
148 int hascurpos, fetchingtthl, notthl;
149 struct tigertreehash tth;
158 static struct fnet dcnet;
159 static struct transferiface dctransfer;
160 static struct socket *udpsock = NULL;
161 static struct socket *tcpsock = NULL;
162 static struct dcpeer *peers = NULL;
164 static struct dcexppeer *expected = NULL;
165 static char *hmlistname = NULL;
166 static char *xmllistname = NULL;
167 static char *xmlbz2listname = NULL;
168 static struct timer *listwritetimer = NULL;
170 static void peerconnect(struct socket *sk, int err, struct fnetnode *fn);
171 static void freedcpeer(struct dcpeer *peer);
172 static void transread(struct socket *sk, struct dcpeer *peer);
173 static void transerr(struct socket *sk, int err, struct dcpeer *peer);
174 static void transwrite(struct socket *sk, struct dcpeer *peer);
175 static void updatehmlist(void);
176 static void updatexmllist(void);
177 static void updatexmlbz2list(void);
178 static void requestfile(struct dcpeer *peer);
179 static void updatelists(int now);
181 static int reservedchar(unsigned char c)
183 return((c == 0) || (c == 5) || (c == 124) || (c == 96) || (c == 126) || (c == 36));
186 /* Oh, how I despise having to do this... */
187 static char *dcmakekey(char *lock)
193 buf = smalloc(strlen(lock));
196 for(i = 0; lock[i]; i++)
198 buf[i] = lock[i] ^ save;
199 buf[i] = ((buf[i] & 0x0F) << 4) | ((buf[i] & 0xF0) >> 4);
201 if((i != 0) && reservedchar(buf[i]))
206 buf[0] ^= buf[i - 1];
207 if(reservedchar(buf[0]))
211 key = smalloc(len + 1);
213 for(i = 0; lock[i] != 0; i++)
215 if(reservedchar(buf[i]))
216 offset += sprintf(key + offset, "/%%DCN%03i%%/", buf[i]);
218 key[offset++] = buf[i];
225 static wchar_t *nmdc2path(char *nmdc, char *charset)
229 if((ret = icmbstowcs(nmdc, charset)) == NULL)
231 for(p = ret; *p != L'\0'; p++) {
238 static char *path2nmdc(wchar_t *path, char *charset)
242 if((ret = icwcstombs(path, charset)) == NULL)
244 for(p = ret; *p; p++) {
251 static wchar_t *adc2path(char *adc)
253 return(icmbstowcs(adc, "UTF-8"));
256 static char *path2adc(wchar_t *path)
258 return(icwcstombs(path, "UTF-8"));
261 static int isdchash(struct hash *hash)
263 if(wcscmp(hash->algo, L"TTH"))
271 * Uncomment when used!
273 static int hubsupports(struct dchub *hub, char *cap)
277 if(hub->supports == NULL)
279 for(p = hub->supports; *p != NULL; p++)
281 if(!strcasecmp(*p, cap))
288 static int supports(struct dcpeer *peer, char *cap)
292 if(peer->supports == NULL)
294 for(p = peer->supports; *p != NULL; p++)
296 if(!strcasecmp(*p, cap))
302 static void endcompress(struct dcpeer *peer)
304 if(peer->compress == CPRS_ZLIB)
306 deflateEnd(peer->cprsdata);
307 free(peer->cprsdata);
309 peer->compress = CPRS_NONE;
312 static void initcompress(struct dcpeer *peer, int algo)
317 peer->compress = algo;
318 if(algo == CPRS_ZLIB)
320 peer->cprsdata = smalloc(sizeof(z_stream));
321 memset(peer->cprsdata, 0, sizeof(z_stream));
322 if((ret = deflateInit(peer->cprsdata, 3)) != Z_OK)
324 flog(LOG_CRIT, "Aiya! zlib refuses to init (%i)!", ret);
330 static void unquote(wchar_t *in)
334 for(p = in; *p != L'\0'; p++)
338 for(p2 = p + 1; (*p2 != L'\0') && (*p2 != L';') && (*p2 != L'&'); p2++);
345 if(!wcscmp(p + 1, L"amp"))
348 } else if(p[1] == L'#') {
349 nc = ucptowc(wcstol(p + 2, NULL, 10));
358 memmove(p + 1, p2 + 1, (wcslen(p2 + 1) + 1) * sizeof(wchar_t));
363 static void freeexppeer(struct dcexppeer *ep)
366 ep->next->prev = ep->prev;
368 ep->prev->next = ep->next;
373 if(ep->expire != NULL)
374 canceltimer(ep->expire);
378 static void exppeerexpire(int cancelled, struct dcexppeer *ep)
385 static struct dcexppeer *expectpeer(char *nick, struct fnetnode *fn)
387 struct dcexppeer *ep;
389 ep = smalloc(sizeof(*ep));
390 ep->nick = sstrdup(nick);
391 getfnetnode(ep->fn = fn);
392 ep->expire = timercallback(ntime() + 300, (void (*)(int, void *))exppeerexpire, ep);
401 static struct qcommand *newqcmd(struct qcmdqueue *queue, char *string)
403 struct qcommand *new;
405 new = smalloc(sizeof(*new));
406 new->string = sstrdup(string);
411 queue->l->next = new;
417 static struct qcommand *ulqcmd(struct qcmdqueue *queue)
419 struct qcommand *qcmd;
421 if((qcmd = queue->f) == NULL)
423 if((queue->f = qcmd->next) == NULL)
429 static void freeqcmd(struct qcommand *qcmd)
435 static void hubrecvchat(struct socket *sk, struct fnetnode *fn, char *from, char *string)
437 wchar_t *chat, *wfrom, *wpeer;
439 struct fnetpeer *peer;
443 end = string + strlen(string);
444 while((p = strchr(string, 13)) != NULL)
445 memmove(p, p + 1, (end-- - p));
448 if((strlen(string) > strlen(from) + 2) && (*string == '<') && !memcmp(string + 1, from, strlen(from)) && (*(string + strlen(from) + 1) == '>'))
449 string += strlen(from) + 2;
450 if((wfrom = icmbstowcs(from, hub->charset)) == NULL)
452 wpeer = swcsdup(wfrom);
458 for(p = string + 1; *p; p++)
460 if((*p == ' ') || (*p == '>'))
468 if((wpeer = icmbstowcs(string + 1, hub->charset)) == NULL)
474 wpeer = swcsdup(L"");
476 if((chat = icmbstowcs(string, hub->charset)) == NULL)
486 if((peer = fnetfindpeer(fn, wfrom)) == NULL) /* Assume public chat */
487 fnethandlechat(fn, 1, wfrom, wpeer, chat);
489 fnethandlechat(fn, 0, wfrom, wpeer, chat);
491 fnethandlechat(fn, 1, L"", wpeer, chat);
499 static void peertimeout(int cancelled, struct dcpeer *peer)
501 peer->timeout = NULL;
507 static void sendadc(struct socket *sk, char *arg)
510 size_t bufsize, bufdata;
513 bufsize = bufdata = 0;
519 bufcat(buf, "\\s", 2);
520 } else if(*arg == '\n') {
521 bufcat(buf, "\\n", 2);
522 } else if(*arg == '\\') {
523 bufcat(buf, "\\\\", 2);
528 sockqueue(sk, buf, bufdata);
532 #if defined(__GNUC__)
533 static void __attribute__ ((format (printf, 2, 3))) sendadcf(struct socket *sk, char *arg, ...)
535 static void sendadcf(struct socket *sk, char *arg, ...)
542 buf = vsprintf2(arg, args);
550 static char **parseadc(char *args)
553 size_t retbufsize, retbufdata;
555 size_t bufsize, bufdata;
560 retbufsize = retbufdata = bufsize = bufdata = 0;
569 else if(*args != ' ')
573 if((*args == ' ') || (*args == 0))
576 addtobuf(retbuf, buf);
578 bufsize = bufdata = 0;
581 } else if(*args == '\\') {
584 addtobuf(buf, *args);
593 addtobuf(retbuf, NULL);
596 } else if((*args == 's') || (*args == ' ')) {
598 } else if(*args == 'n') {
600 } else if(*args == '\\') {
610 addtobuf(retbuf, NULL);
614 /* Macros useful in command handlers */
615 #define skipspace(s) ({if(((s) = strchr((s), ' ')) == NULL) return; else (s)++;})
616 #define qstr(sk, str) sockqueue(sk, str, strlen(str))
617 #define qstrf(sk, strandargs...) \
620 if((__buf__ = sprintf2(strandargs)) != NULL) { \
621 sockqueue(sk, __buf__, strlen(__buf__)); \
626 static char *tr(char *str, char *trans)
630 for(; *trans; trans += 2)
632 for(p = strchr(str, trans[0]); p != NULL; p = strchr(p, trans[0]))
638 static char *getadcid(struct dcpeer *peer)
645 if(!wcscmp(peer->transfer->path, L"files.xml") || !wcscmp(peer->transfer->path, L"files.xml.bz2") || !wcscmp(peer->transfer->path, L"MyList.DcLst"))
647 if(!isfilelist && (peer->transfer->hash != NULL) && isdchash(peer->transfer->hash) && supports(peer, "tthf"))
649 buf = base32encode(peer->transfer->hash->buf, 24);
650 ret = sprintf2("TTH/%.39s", buf);
653 ret = path2adc(peer->transfer->path);
659 static int trresumecb(struct transfer *transfer, wchar_t *cmd, wchar_t *arg, struct dcpeer *peer)
661 if(!wcscmp(cmd, L"resume"))
665 flog(LOG_WARNING, "filter returned no position for \"resume\" on transfer %i", transfer->id);
668 transfer->curpos = wcstoll(arg, NULL, 10);
677 static void sendmynick(struct dcpeer *peer)
683 qstrf(peer->sk, "$MyNick %s|", icswcstombs(confgetstr("cli", "defnick"), peer->charset, "DoldaConnectUser-IN"));
685 qstrf(peer->sk, "$MyNick %s|", icswcstombs(fn->mynick, peer->charset, "DoldaConnectUser-IN"));
688 static void sendpeerlock(struct dcpeer *peer)
691 qstrf(peer->sk, "$Lock EXTENDEDPROTOCOLABCABCABCABCABCABC Pk=DCPLUSPLUS0.674ABCABC|");
693 qstrf(peer->sk, "$Lock EXTENDEDPROTOCOLABCABCABCABCABCABC Pk=DOLDA%sABCABCABC|", VERSION);
696 static void sendsupports(struct dcpeer *peer)
699 qstr(peer->sk, "$Supports MiniSlots XmlBZList ADCGet TTHL TTHF GetZBlock ZLIG |");
701 qstr(peer->sk, "$Supports MiniSlots XmlBZList ADCGet TTHL TTHF");
702 if(!confgetint("dc", "hidedeflate"))
703 qstr(peer->sk, " GetZBlock ZLIG");
708 static void requestfile(struct dcpeer *peer)
712 if(peer->transfer->size == -1)
714 /* Use DCCHARSET for $Get paths until further researched... */
715 if((buf = path2nmdc(peer->transfer->path, DCCHARSET)) == NULL)
717 transferseterror(peer->transfer, TRNSE_NOTFOUND);
721 /* The transfer will be restarted later from
722 * cmd_filelength when it detects that the sizes
724 qstrf(peer->sk, "$Get %s$1|", buf);
728 if((peer->transfer->hash == NULL) && !peer->notthl)
730 if(supports(peer, "adcget") && supports(peer, "tthl"))
732 qstr(peer->sk, "$ADCGET");
733 sendadc(peer->sk, "tthl");
734 if((buf = getadcid(peer)) == NULL)
736 transferseterror(peer->transfer, TRNSE_NOTFOUND);
740 sendadc(peer->sk, buf);
742 sendadc(peer->sk, "0");
743 sendadc(peer->sk, "-1");
745 peer->fetchingtthl = 1;
751 if(forkfilter(peer->transfer))
753 flog(LOG_WARNING, "could not fork filter for transfer %i: %s", peer->transfer->id, strerror(errno));
757 CBREG(peer->transfer, trans_filterout, (int (*)(struct transfer *, wchar_t *, wchar_t *, void *))trresumecb, NULL, peer);
760 if(supports(peer, "adcget"))
762 qstr(peer->sk, "$ADCGET");
763 sendadc(peer->sk, "file");
764 if((buf = getadcid(peer)) == NULL)
766 transferseterror(peer->transfer, TRNSE_NOTFOUND);
770 sendadc(peer->sk, buf);
772 sendadcf(peer->sk, "%ji", (intmax_t)peer->transfer->curpos);
773 sendadcf(peer->sk, "%ji", (intmax_t)(peer->transfer->size - peer->transfer->curpos));
775 } else if(supports(peer, "xmlbzlist")) {
776 if((buf = path2nmdc(peer->transfer->path, "UTF-8")) == NULL)
778 transferseterror(peer->transfer, TRNSE_NOTFOUND);
782 qstrf(peer->sk, "$UGetBlock %ji %ji %s|", (intmax_t)peer->transfer->curpos, (intmax_t)(peer->transfer->size - peer->transfer->curpos), buf);
785 /* Use DCCHARSET for $Get paths until further researched... */
786 if((buf = path2nmdc(peer->transfer->path, DCCHARSET)) == NULL)
788 transferseterror(peer->transfer, TRNSE_NOTFOUND);
792 qstrf(peer->sk, "$Get %s$%ji|", buf, (intmax_t)peer->transfer->curpos + 1);
797 static void sendmyinfo(struct socket *sk, struct fnetnode *fn)
801 struct fnetnode *cfn;
805 qstrf(sk, "$MyINFO $ALL %s ", hub->nativenick);
806 buf = tr(icswcstombs(confgetstr("dc", "desc"), hub->charset, "Charset_conv_failure"), "$_|_");
807 qstrf(sk, "%s", buf);
809 for(cfn = fnetnodes; cfn != NULL; cfn = cfn->next)
811 if((cfn->state == FNN_EST) || (cfn->state == FNN_HS))
813 if(cfn->regstatus == FNNS_OP)
815 else if(cfn->regstatus == FNNS_REG)
821 qstrf(sk, "<%s V:%s,M:%c,H:%i/%i/%i,S:%i>",
822 (hub->dcppemu)?"++":"Dolda",
823 (hub->dcppemu)?"0.674":VERSION,
824 (tcpsock == NULL)?'P':'A',
826 confgetint("transfer", "slots")
829 buf = tr(icswcstombs(confgetstr("dc", "speedstring"), hub->charset, "Charset_conv_failure"), "$_|_");
830 qstrf(sk, "%s\x01$", buf);
831 buf = tr(icswcstombs(confgetstr("dc", "email"), hub->charset, "Charset_conv_failure"), "$_|_");
832 qstrf(sk, "%s$", buf);
833 qstrf(sk, "%llu$|", sharesize);
836 static void hubhandleaction(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
841 if(!strcmp(cmd, "$Lock"))
843 qstrf(sk, "$ValidateNick %s|", hub->nativenick);
844 } else if(!strcmp(cmd, "$Hello")) {
845 if(fn->state == FNN_HS)
847 qstrf(sk, "$Version 1,0091|");
848 qstrf(sk, "$GetNickList|");
850 fnetsetstate(fn, FNN_EST);
852 qstrf(sk, "$GetINFO %s %s|", args, hub->nativenick);
857 static void cmd_lock(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
864 if(!strncmp(args, "EXTENDEDPROTOCOL", 16))
866 if((p = strchr(args, ' ')) != NULL)
871 qstrf(sk, "$Supports UserCommand NoGetINFO NoHello UserIP2 TTHSearch GetZBlock |");
873 qstrf(sk, "$Supports UserCommand NoGetINFO NoHello UserIP2 TTHSearch");
874 if(!confgetint("dc", "hidedeflate"))
875 qstr(sk, " GetZBlock");
879 key = dcmakekey(args);
880 qstrf(sk, "$Key %s|", key);
882 hubhandleaction(sk, fn, cmd, args);
885 static void cmd_hubname(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
891 if(hub->nativename == NULL)
892 free(hub->nativename);
893 hub->nativename = sstrdup(args);
894 buf = icmbstowcs(args, hub->charset);
895 fnetsetname(fn, (buf == NULL)?L"Hubname conv error":buf);
898 hubhandleaction(sk, fn, cmd, args);
901 static void cmd_hello(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
907 if((nick = icmbstowcs(args, hub->charset)) == NULL)
909 if(strcmp(args, hub->nativenick) && (fnetfindpeer(fn, nick) == NULL))
910 fnetaddpeer(fn, nick, nick);
912 hubhandleaction(sk, fn, cmd, args);
915 static void cmd_quit(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
918 struct fnetpeer *peer;
922 if((nick = icmbstowcs(args, hub->charset)) == NULL)
924 if((peer = fnetfindpeer(fn, nick)) != NULL)
927 hubhandleaction(sk, fn, cmd, args);
930 static void cmd_nicklist(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
935 struct fnetpeer *peer;
938 for(peer = btreeiter(fn->peers); peer != NULL; peer = btreeiter(NULL))
939 peer->flags.b.delete = 1;
940 while((p = strstr(args, "$$")) != NULL)
943 if((buf = icmbstowcs(args, hub->charset)) != NULL)
945 if((peer = fnetfindpeer(fn, buf)) == NULL)
946 peer = fnetaddpeer(fn, buf, buf);
948 peer->flags.b.delete = 0;
950 qstrf(sk, "$GetINFO %s %s|", args, hub->nativenick);
955 hubhandleaction(sk, fn, cmd, args);
958 static void cmd_oplist(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
963 struct fnetpeer *peer;
966 for(peer = btreeiter(fn->peers); peer != NULL; peer = btreeiter(NULL))
967 peer->flags.b.op = 0;
968 while((p = strstr(args, "$$")) != NULL)
971 if((buf = icmbstowcs(args, hub->charset)) != NULL)
973 if((peer = fnetfindpeer(fn, buf)) != NULL)
974 peer->flags.b.op = 1;
979 hubhandleaction(sk, fn, cmd, args);
982 static void cmd_myinfo(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
985 wchar_t *buf, *wp, *wp2;
987 struct fnetpeer *peer;
992 if(strncmp(p, "$ALL ", 5))
995 if((p2 = strchr(p, ' ')) == NULL)
998 if((buf = icmbstowcs(p, hub->charset)) == NULL)
1000 if((peer = fnetfindpeer(fn, buf)) == NULL)
1001 peer = fnetaddpeer(fn, buf, buf);
1004 if((p2 = strstr(p, "$ $")) == NULL)
1007 if((buf = icmbstowcs(p, hub->charset)) == NULL)
1009 if((wcslen(buf) > 0) && (buf[wcslen(buf) - 1] == L'>') && ((wp = wcsrchr(buf, L'<')) != NULL))
1011 buf[wcslen(buf) - 1] = L'\0';
1013 if((wp2 = wcschr(wp, L' ')) != NULL)
1016 fnetpeersetstr(peer, L"dc-client", wp);
1020 if((wp2 = wcschr(wp, L',')) != NULL)
1024 swprintf(abuf, 10, L"dc-tag-%lc", wp[0]);
1025 fnetpeersetstr(peer, abuf, wp + 2);
1027 } while(wp2 != NULL);
1030 fnetpeersetstr(peer, L"descr", buf);
1033 if((p2 = strchr(p, '$')) == NULL)
1036 if((buf = icmbstowcs(p, hub->charset)) == NULL)
1038 fnetpeersetstr(peer, L"dc-speed", buf);
1041 if((p2 = strchr(p, '$')) == NULL)
1044 if((buf = icmbstowcs(p, hub->charset)) == NULL)
1046 fnetpeersetstr(peer, L"email", buf);
1051 fnetpeersetlnum(peer, L"share", strtoll(p, NULL, 10));
1052 hubhandleaction(sk, fn, cmd, args);
1055 /* I do not implement the fully in that I do not disconnect from the
1056 * old hub. I do this since I believe that if the hub owner really
1057 * wants to get rid of us, then it is his responsibility to disconnect
1059 static void cmd_forcemove(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1062 struct fnetnode *newfn;
1066 if(strchr(args, ':') == NULL)
1068 args = strcpy(smalloc(strlen(args) + 5), args);
1069 strcat(args, ":411");
1074 if((newfn = fnetinitconnect(L"dc", fn->owner, args, NULL)) != NULL)
1076 linkfnetnode(newfn);
1079 hubhandleaction(sk, fn, cmd, args);
1084 static char *getdcpath(struct sharecache *node, size_t *retlen, char *charset)
1089 if(node->parent == NULL)
1091 if(node->parent == shareroot)
1093 if((buf = icwcstombs(node->name, charset)) == NULL)
1096 *retlen = strlen(buf);
1099 if((buf2 = icwcstombs(node->name, charset)) == NULL)
1101 if((buf = getdcpath(node->parent, &len, charset)) == NULL)
1106 len2 = strlen(buf2);
1107 buf = srealloc(buf, len + 1 + len2 + 1);
1109 strcpy(buf + len, buf2);
1110 buf[len + len2] = 0;
1113 *retlen = len + len2;
1119 * This is the main share searching function for Direct Connect
1120 * peers. Feel free to optimize it if you feel the need for it. I
1121 * haven't ever seen it take any noticable CPU time anyway, so I
1122 * haven't felt that need.
1124 * It may feel dubious to just return the directory when all terms are
1125 * satisfied rather than all the files in it, but it really benefits
1126 * everyone: Less cycles used for us, less UDP squelching for active
1127 * searchers, and less bandwidth waste for hubs when serving passive
1130 static void cmd_search(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1135 char *prefix, *infix, *postfix, *buf, *buf2;
1137 struct sockaddr_in addr;
1138 struct sharecache *node;
1139 int minsize, maxsize;
1142 int termnum, satisfied, skipcheck;
1143 int level, tersat[32];
1148 if((p = strchr(args, ' ')) == NULL)
1152 memset(terms, 0, sizeof(terms));
1153 prefix = infix = postfix = NULL;
1157 if(!strncmp(args, "Hub:", 4))
1159 if(!strcmp(cmd, "$MultiSearch"))
1161 if(!strcmp(args + 4, hub->nativenick))
1163 prefix = sprintf2("$SR %s ", hub->nativenick);
1164 infix = sprintf2(" %i/%i\005", slotsleft(), confgetint("transfer", "slots"));
1165 postfix = sprintf2(" (%s)\005%s|", formataddress(hub->sk->remote, hub->sk->remotelen), args + 4);
1169 if((p2 = strchr(args, ':')) == NULL)
1172 addr.sin_family = AF_INET;
1173 if(!inet_aton(args, &addr.sin_addr))
1175 addr.sin_port = htons(atoi(p2));
1176 prefix = sprintf2("$SR %s ", hub->nativenick);
1177 infix = sprintf2(" %i/%i\005", slotsleft(), confgetint("transfer", "slots"));
1178 postfix = sprintf2(" (%s)|", formataddress(hub->sk->remote, hub->sk->remotelen));
1179 netdgramconn(dsk = netdupsock(udpsock), (struct sockaddr *)&addr, sizeof(addr));
1182 minsize = maxsize = -1;
1191 if((*(p++) == 'T') && (minsize == 0))
1198 if((p2 = strchr(p, '?')) == NULL)
1213 if((*p2 == 0) || (*p2 == '$'))
1221 if(!dotth && !strncmp(p, "TTH:", 4))
1224 if(((buf = base32decode(p + 4, &buflen)) == NULL) || (buflen != 24))
1229 memcpy(hashtth, buf, 24);
1232 if((terms[termnum] = icmbstowcs(p, hub->charset)) != NULL)
1243 node = shareroot->child;
1245 for(i = 0; i < termnum; i++)
1251 if(node->f.b.type == FILE_REG)
1253 if((minsize >= 0) && (node->size < minsize))
1255 if((maxsize >= 0) && (node->size > maxsize))
1258 if(!skipcheck && dotth)
1260 if((node->f.b.type != FILE_REG) || (node->f.b.hastth && memcmp(hashtth, node->hashtth, 24)))
1265 for(i = 0; i < termnum; i++)
1269 if(wcsexists(node->name, terms[i]))
1273 } else if(node->child == NULL) {
1278 if(!skipcheck && (satisfied == termnum))
1280 /* Use DCCHARSET in $Get paths until further researched... */
1281 if((buf = getdcpath(node, NULL, DCCHARSET)) != NULL)
1283 if(node->f.b.hastth)
1285 buf2 = base32encode(node->hashtth, 24);
1286 qstrf(dsk, "%s%s\005%ji%sTTH:%.39s%s", prefix, buf, (intmax_t)node->size, infix, buf2, postfix);
1289 qstrf(dsk, "%s%s\005%ji%s%s%s", prefix, buf, (intmax_t)node->size, infix, hub->nativename, postfix);
1294 if((!skipcheck && (satisfied == termnum)) || (node->child == NULL))
1296 while(node->next == NULL)
1298 if((node = node->parent) == shareroot)
1302 if(node == shareroot)
1304 for(i = 0; i < termnum; i++)
1306 if(tersat[i] >= level)
1319 hubhandleaction(sk, fn, cmd, args);
1330 for(i = 0; (i < 32) && (terms[i] != NULL); i++)
1334 static void cmd_connecttome(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1338 struct socket *newsk;
1339 struct sockaddr_in addr;
1342 if((p = strchr(args, ' ')) == NULL)
1345 if(strcmp(args, hub->nativenick))
1347 addr.sin_family = AF_INET;
1349 if((p = strchr(args, ':')) == NULL)
1352 addr.sin_port = htons(atoi(p));
1353 if(!inet_aton(args, &addr.sin_addr))
1355 newsk = netcsconn((struct sockaddr *)&addr, sizeof(addr), (void (*)(struct socket *, int, void *))peerconnect, fn);
1357 hubhandleaction(sk, fn, cmd, args);
1360 static void sendctm(struct socket *sk, char *nick)
1362 struct sockaddr *addr;
1367 if(sockgetremotename2(tcpsock, sk, &addr, &addrlen) < 0)
1369 if(addr->sa_family == AF_INET)
1370 qstrf(sk, "$ConnectToMe %s %s|", nick, formataddress(addr, addrlen));
1372 flog(LOG_WARNING, "Direct Connect TCP socket is suddenly not AF_INET, but %i", addr->sa_family);
1376 static void cmd_revconnecttome(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1382 if((p = strchr(args, ' ')) == NULL)
1385 if(strcmp(p, hub->nativenick))
1388 expectpeer(args, fn);
1389 hubhandleaction(sk, fn, cmd, args);
1392 static void cmd_getnetinfo(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1395 struct fnetnode *node;
1400 for(node = fnetnodes; node != NULL; node = node->next)
1402 if(node->state == FNN_EST)
1405 qstrf(sk, "$NetInfo %i$%i$%c$0|", confgetint("transfer", "slots"), numhubs, (tcpsock == NULL)?'P':'A');
1406 hubhandleaction(sk, fn, cmd, args);
1409 static void cmd_to(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1416 if((p2 = strchr(p, ' ')) == NULL)
1420 if((p2 = strchr(p, ' ')) == NULL)
1423 if(strcmp(p, "From:"))
1426 if((p2 = strstr(p, " $")) == NULL)
1430 hubrecvchat(hub->sk, fn, p, p2);
1431 hubhandleaction(sk, fn, cmd, args);
1434 static void cmd_sr(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1438 char *nick, *filename, *hubname;
1443 wchar_t *wnick, *wfile;
1447 if((p2 = strchr(p, ' ')) == NULL)
1452 if((p2 = strchr(p, 5)) == NULL)
1456 if((p2 = strchr(p, ' ')) == NULL)
1459 size = strtoll(p, NULL, 10);
1461 if((p2 = strchr(p, '/')) == NULL)
1466 if((p2 = strchr(p, 5)) == NULL)
1470 if((p2 = strstr(p, " (")) == NULL)
1473 if((wnick = icmbstowcs(nick, hub->charset)) == NULL)
1475 /* Use DCCHARSET in $Get paths until further researched... */
1476 if((wfile = nmdc2path(filename, DCCHARSET)) == NULL)
1481 sr = newsrchres(&dcnet, wfile, wnick);
1482 if(sr->peernick != NULL)
1484 sr->peernick = swcsdup(wnick);
1489 if(!strncmp(hubname, "TTH:", 4))
1491 if((buf = base32decode(hubname + 4, &buflen)) != NULL)
1494 sr->hash = newhash(L"TTH", 24, buf);
1498 getfnetnode(sr->fn = fn);
1501 hubhandleaction(sk, fn, cmd, args);
1504 static void cmd_usercommand(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1506 /* Do nothing for now. */
1509 static void cmd_getpass(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1516 pw = wpfind(fn->args, L"password");
1517 if((pw == NULL) || ((mbspw = icwcstombs(pw, hub->charset)) == NULL))
1522 qstrf(sk, "$MyPass %s|", mbspw);
1524 fn->regstatus = FNNS_REG;
1525 hubhandleaction(sk, fn, cmd, args);
1528 static void cmd_logedin(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1533 fn->regstatus = FNNS_OP;
1534 hubhandleaction(sk, fn, cmd, args);
1537 static void cmd_hubsupports(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1543 size_t arrsize, arrdata;
1546 if(hub->supports != NULL)
1548 for(i = 0; hub->supports[i] != NULL; i++)
1549 free(hub->supports[i]);
1550 free(hub->supports);
1553 arrsize = arrdata = 0;
1557 if((p2 = strchr(p, ' ')) != NULL)
1561 addtobuf(arr, sstrdup(p));
1562 } while((p = p2) != NULL);
1563 addtobuf(arr, NULL);
1564 hub->supports = arr;
1567 static void cmd_mynick(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1569 struct dcexppeer *expect;
1572 if(peer->nativename != NULL)
1573 free(peer->nativename);
1574 peer->nativename = sstrdup(args);
1575 if(peer->wcsname != NULL)
1576 free(peer->wcsname);
1577 if((peer->wcsname = icmbstowcs(peer->nativename, peer->charset)) == NULL)
1584 for(expect = expected; expect != NULL; expect = expect->next)
1586 if(!strcmp(expect->nick, args))
1593 hub = expect->fn->data;
1594 peer->fn = expect->fn;
1595 getfnetnode(peer->fn);
1596 peer->dcppemu = hub->dcppemu;
1597 freeexppeer(expect);
1602 static void cmd_direction(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1606 struct transfer *transfer;
1608 if((p = strchr(args, ' ')) == NULL)
1611 if(!strcmp(args, "Upload"))
1613 if(!strcmp(args, "Download"))
1617 if((peer->transfer == NULL) || (mydir != peer->direction))
1622 if(peer->direction == TRNSD_DOWN)
1625 if(peer->wcsname == NULL)
1630 peer->direction = mydir;
1631 if(peer->direction == TRNSD_UP)
1633 if(confgetint("transfer", "ulquota") && hasupload(&dcnet, peer->wcsname))
1638 transfer = newupload(peer->fn, &dcnet, peer->wcsname, &dctransfer, peer);
1640 if((transfer = finddownload(peer->wcsname)) == NULL)
1645 transferattach(transfer, &dctransfer, peer);
1646 transfersetstate(transfer, TRNS_HS);
1648 transfersetnick(transfer, peer->wcsname);
1649 peer->transfer = transfer;
1652 qstrf(sk, "$Direction %s %i|", (peer->direction == TRNSD_UP)?"Upload":"Download", rand() % 10000);
1653 if(peer->key != NULL)
1654 qstrf(sk, "$Key %s|", peer->key);
1655 if(peer->direction == TRNSD_DOWN)
1660 static void cmd_peerlock(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1663 struct transfer *transfer;
1665 if((p = strchr(args, ' ')) == NULL)
1668 if(!strncmp(args, "EXTENDEDPROTOCOL", 16))
1670 key = dcmakekey(args);
1673 if(peer->wcsname == NULL)
1682 if((transfer = finddownload(peer->wcsname)) == NULL)
1684 if(confgetint("transfer", "ulquota") && hasupload(&dcnet, peer->wcsname))
1689 peer->direction = TRNSD_UP;
1690 transfer = newupload(peer->fn, &dcnet, peer->wcsname, &dctransfer, peer);
1692 peer->direction = TRNSD_DOWN;
1693 transferattach(transfer, &dctransfer, peer);
1694 transfersetstate(transfer, TRNS_HS);
1696 transfersetnick(transfer, peer->wcsname);
1697 peer->transfer = transfer;
1698 qstrf(sk, "$Direction %s %i|", (peer->direction == TRNSD_UP)?"Upload":"Download", rand() % 10000);
1699 qstrf(sk, "$Key %s|", key);
1702 if(peer->key != NULL)
1708 static void cmd_key(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1713 static void startdl(struct dcpeer *peer)
1715 if(peer->timeout != NULL)
1716 canceltimer(peer->timeout);
1717 peer->state = PEER_TRNS;
1718 transferstartdl(peer->transfer, peer->sk);
1719 peer->sk->readcb = (void (*)(struct socket *, void *))transread;
1720 peer->sk->errcb = (void (*)(struct socket *, int, void *))transerr;
1723 static void startul(struct dcpeer *peer)
1725 if(peer->timeout != NULL)
1726 canceltimer(peer->timeout);
1727 peer->state = PEER_TRNS;
1728 transferstartul(peer->transfer, peer->sk);
1729 peer->sk->writecb = (void (*)(struct socket *, void *))transwrite;
1732 static void cmd_filelength(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1735 struct transfer *transfer;
1737 if(peer->transfer == NULL)
1742 size = strtoll(args, NULL, 10);
1743 if(peer->transfer->size != size)
1745 transfersetsize(peer->transfer, size);
1746 transfer = peer->transfer;
1748 trytransferbypeer(transfer->fnet, transfer->peerid);
1752 qstr(peer->sk, "$Send|");
1755 static void cmd_error(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1757 if(peer->fetchingtthl)
1759 peer->fetchingtthl = 0;
1764 if((peer->transfer != NULL) && (peer->transfer->dir == TRNSD_DOWN))
1766 transferseterror(peer->transfer, TRNSE_NOTFOUND);
1767 resettransfer(peer->transfer);
1773 static void cmd_maxedout(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1775 if((peer->transfer != NULL) && (peer->transfer->dir == TRNSD_DOWN))
1777 transferseterror(peer->transfer, TRNSE_NOSLOTS);
1778 resettransfer(peer->transfer);
1791 {"MyList.DcLst", &hmlistname, updatehmlist},
1792 {"files.xml", &xmllistname, updatexmllist},
1793 {"files.xml.bz2", &xmlbz2listname, updatexmlbz2list},
1797 static int openfilelist(char *name)
1802 for(i = 0; lists[i].name != NULL; i++)
1804 if(!strcmp(name, lists[i].name))
1808 if(lists[i].name == NULL)
1811 if((*lists[i].file == NULL) || ((fd = open(*lists[i].file, O_RDONLY)) < 0))
1813 if((fd < 0) && ((*lists[i].file == NULL) || ((fd = open(*lists[i].file, O_RDONLY)) < 0)))
1816 flog(LOG_ERR, "could not open filelist tempfile: %s", strerror(errno));
1823 static struct sharecache *findbytth(char *tth32)
1827 struct sharecache *node;
1829 if((buf = base32decode(tth32, &buflen)) == NULL)
1836 for(node = shareroot->child; node != NULL; node = nextscnode(node))
1838 if(node->f.b.hastth && !memcmp(node->hashtth, buf, 24))
1845 static struct sharecache *resdcpath(char *path, char *charset, char sep)
1847 struct sharecache *node;
1854 if((p2 = strchr(p, sep)) != NULL)
1856 if((node = findcache(node, icsmbstowcs(p, charset, L""))) == NULL)
1863 static void cmd_get(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1868 struct sharecache *node;
1869 struct socket *lesk;
1873 if(peer->transfer == NULL)
1878 if((p = strchr(args, '$')) == NULL)
1884 if((offset = (strtoll(p, NULL, 10) - 1)) < 0)
1889 if(((fd = openfilelist(args)) < 0) && (errno != 0))
1891 qstr(sk, "$Error Could not send file list|");
1894 } else if(fd >= 0) {
1895 if((buf2 = nmdc2path(args, DCCHARSET)) != NULL) {
1896 transfersetpath(peer->transfer, buf2);
1899 peer->transfer->flags.b.minislot = 1;
1903 /* Use DCCHARSET in $Get paths until further researched... */
1904 if((node = resdcpath(args, DCCHARSET, '\\')) == NULL)
1906 qstrf(sk, "$Error File not in share|");
1910 if((fd = opensharecache(node)) < 0)
1912 qstrf(sk, "$Error %s|", strerror(errno));
1916 buf = getfspath(node);
1917 if((buf2 = icsmbstowcs(buf, NULL, NULL)) == NULL)
1918 flog(LOG_WARNING, "could not convert native path into a wcs (%s): %s", buf, strerror(errno));
1920 transfersetpath(peer->transfer, buf2);
1923 if(fstat(fd, &sb) < 0)
1926 flog(LOG_WARNING, "could not stat file %ls: %s", node->name, strerror(errno));
1927 qstrf(sk, "$Error|");
1931 if(sb.st_size < 65536)
1932 peer->transfer->flags.b.minislot = 1;
1933 if(!peer->transfer->flags.b.minislot && (slotsleft() < 1)) {
1935 qstr(sk, "$MaxedOut|");
1939 if((offset != 0) && (lseek(fd, offset, SEEK_SET) < 0))
1942 qstrf(sk, "$Error Offset out of range|");
1946 lesk = wrapsock(fd);
1947 transferprepul(peer->transfer, sb.st_size, offset, -1, lesk);
1949 qstrf(sk, "$FileLength %ji|", (intmax_t)peer->transfer->size);
1952 static void cmd_send(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1954 if(peer->transfer == NULL)
1959 if(peer->transfer->localend == NULL)
1968 static void cmd_supports(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1973 size_t arrsize, arrdata;
1975 if(peer->supports != NULL)
1977 for(i = 0; peer->supports[i] != NULL; i++)
1978 free(peer->supports[i]);
1979 free(peer->supports);
1982 arrsize = arrdata = 0;
1986 if((p2 = strchr(p, ' ')) != NULL)
1990 addtobuf(arr, sstrdup(p));
1991 } while((p = p2) != NULL);
1992 addtobuf(arr, NULL);
1993 peer->supports = arr;
1996 static void cmd_getblock(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2000 off_t start, numbytes;
2001 char *charset, *buf;
2003 struct sharecache *node;
2005 struct socket *lesk;
2007 if(peer->transfer == NULL)
2013 if((p2 = strchr(p, ' ')) == NULL)
2019 start = strtoll(p, NULL, 10);
2021 if((p2 = strchr(p, ' ')) == NULL)
2027 numbytes = strtoll(p, NULL, 10);
2029 if(!strcmp(cmd, "$UGetBlock") || !strcmp(cmd, "$UGetZBlock"))
2032 /* Use DCCHARSET in $Get paths until further researched... */
2033 charset = DCCHARSET;
2034 if(!strcmp(cmd, "$GetZBlock") || !strcmp(cmd, "$UGetZBlock"))
2035 initcompress(peer, CPRS_ZLIB);
2036 if(((fd = openfilelist(p)) < 0) && (errno != 0))
2038 qstr(sk, "$Error Could not send file list|");
2040 } else if(fd >= 0) {
2041 if((buf2 = nmdc2path(args, charset)) != NULL) {
2042 transfersetpath(peer->transfer, buf2);
2045 peer->transfer->flags.b.minislot = 1;
2049 if((node = resdcpath(p, charset, '\\')) == NULL)
2051 qstr(sk, "$Error File not in cache|");
2054 if((fd = opensharecache(node)) < 0)
2056 qstrf(sk, "$Error %s|", strerror(errno));
2059 buf = getfspath(node);
2060 if((buf2 = icsmbstowcs(buf, NULL, NULL)) == NULL)
2061 flog(LOG_WARNING, "could not convert native path into a wcs (%s): %s", buf, strerror(errno));
2063 transfersetpath(peer->transfer, buf2);
2066 if(fstat(fd, &sb) < 0)
2069 flog(LOG_WARNING, "could not stat file %ls: %s", node->name, strerror(errno));
2070 qstr(sk, "$Error|");
2073 if(sb.st_size < 65536)
2074 peer->transfer->flags.b.minislot = 1;
2075 if(!peer->transfer->flags.b.minislot && (slotsleft() < 1)) {
2077 qstr(sk, "$MaxedOut|");
2080 if((start != 0) && ((start >= sb.st_size) || (lseek(fd, start, SEEK_SET) < 0)))
2083 qstr(sk, "$Error Offset out of range|");
2086 if((numbytes < 0) || (start + numbytes > sb.st_size))
2087 numbytes = sb.st_size - start;
2088 lesk = wrapsock(fd);
2089 transferprepul(peer->transfer, sb.st_size, start, start + numbytes, lesk);
2091 qstrf(sk, "$Sending %ji|", (intmax_t)numbytes);
2095 static void cmd_adcget(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2099 off_t start, numbytes;
2100 struct sharecache *node;
2102 struct socket *lesk;
2106 if(peer->transfer == NULL)
2111 if((argv = parseadc(args)) == NULL)
2116 if(parrlen(argv) < 4)
2121 start = strtoll(argv[2], NULL, 10);
2122 numbytes = strtoll(argv[3], NULL, 10);
2125 if(((fd = openfilelist(argv[1])) < 0) && (errno != 0))
2127 qstr(sk, "$Error Could not send file list|");
2129 } else if(fd >= 0) {
2130 if((wbuf = adc2path(argv[1])) != NULL)
2131 transfersetpath(peer->transfer, wbuf);
2132 peer->transfer->flags.b.minislot = 1;
2136 if(!strncmp(argv[1], "TTH/", 4))
2138 if((node = findbytth(argv[1] + 4)) == NULL)
2140 qstr(sk, "$Error File not in cache|");
2144 if((node = resdcpath((argv[1][0] == '/')?(argv[1] + 1):(argv[1]), "UTF-8", '/')) == NULL)
2146 qstr(sk, "$Error File not in cache|");
2150 if((fd = opensharecache(node)) < 0)
2152 qstrf(sk, "$Error %s|", strerror(errno));
2155 buf = getfspath(node);
2156 if((wbuf = icsmbstowcs(buf, NULL, NULL)) == NULL)
2157 flog(LOG_WARNING, "could not convert native path into a wcs (%s): %s", buf, strerror(errno));
2159 transfersetpath(peer->transfer, wbuf);
2162 if(!strcmp(argv[0], "file"))
2164 for(i = 4; argv[i] != NULL; i++)
2166 if(!strcmp(argv[i], "ZL1"))
2167 initcompress(peer, CPRS_ZLIB);
2169 if(fstat(fd, &sb) < 0)
2171 flog(LOG_WARNING, "could not stat file %ls: %s", node->name, strerror(errno));
2172 qstr(sk, "$Error|");
2175 if(sb.st_size < 65536)
2176 peer->transfer->flags.b.minislot = 1;
2177 if(!peer->transfer->flags.b.minislot && (slotsleft() < 1)) {
2178 qstr(sk, "$MaxedOut|");
2181 if((start != 0) && ((start >= sb.st_size) || (lseek(fd, start, SEEK_SET) < 0)))
2183 qstr(sk, "$Error Offset out of range|");
2186 if((numbytes < 0) || (start + numbytes > sb.st_size))
2187 numbytes = sb.st_size - start;
2188 lesk = wrapsock(fd);
2189 transferprepul(peer->transfer, sb.st_size, start, start + numbytes, lesk);
2192 qstr(sk, "$ADCSND");
2193 sendadc(sk, "file");
2194 sendadc(sk, argv[1]);
2195 sendadcf(sk, "%ji", (intmax_t)start);
2196 sendadcf(sk, "%ji", (intmax_t)numbytes);
2197 if(peer->compress == CPRS_ZLIB)
2201 } else if(!strcmp(argv[0], "tthl")) {
2203 * XXX: Implement full TTHL support.
2205 * In the meantime, this is better than nothing, since it at
2206 * least allows fetching of the TTH root if it isn't already
2211 qstr(sk, "$Error no TTHL data for virtual files|");
2214 qstr(sk, "$ADCSND");
2215 sendadc(sk, "tthl");
2216 sendadc(sk, argv[1]);
2220 sockqueue(sk, node->hashtth, 24);
2222 qstr(sk, "$Error Namespace not implemented|");
2232 static void handletthl(struct dcpeer *peer)
2236 while(peer->inbufdata >= 24)
2238 pushtigertree(&peer->tth, peer->inbuf);
2239 memmove(peer->inbuf, peer->inbuf + 24, peer->inbufdata -= 24);
2240 peer->curread += 24;
2242 if(peer->curread >= peer->totalsize)
2244 if(peer->timeout == NULL)
2245 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
2246 peer->state = PEER_CMD;
2247 synctigertree(&peer->tth);
2248 restigertree(&peer->tth, buf);
2249 transfersethash(peer->transfer, newhash(L"TTH", 24, buf));
2254 static void cmd_adcsnd(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2257 off_t start, numbytes;
2259 if(peer->transfer == NULL)
2264 if((argv = parseadc(args)) == NULL)
2269 if(parrlen(argv) < 4)
2274 start = strtoll(argv[2], NULL, 10);
2275 numbytes = strtoll(argv[3], NULL, 10);
2276 if(!strcmp(argv[0], "tthl"))
2278 if((start != 0) || (numbytes % 24 != 0))
2280 /* Weird. Bail out. */
2284 if(peer->timeout != NULL)
2285 canceltimer(peer->timeout);
2286 peer->state = PEER_TTHL;
2287 peer->totalsize = numbytes;
2289 peer->fetchingtthl = 0;
2290 inittigertree(&peer->tth);
2292 } else if(!strcmp(argv[0], "file")) {
2293 if(start != peer->transfer->curpos)
2298 if(start + numbytes != peer->transfer->size)
2300 transfersetsize(peer->transfer, start + numbytes);
2305 if(peer->inbufdata > 0)
2307 sockpushdata(sk, peer->inbuf, peer->inbufdata);
2308 peer->inbufdata = 0;
2309 transread(sk, peer);
2312 /* We certainly didn't request this...*/
2321 static void cmd_sending(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2325 if(peer->transfer == NULL)
2330 numbytes = strtoll(args, NULL, 10);
2331 if(peer->transfer->size - peer->transfer->curpos != numbytes)
2333 transfersetsize(peer->transfer, peer->transfer->curpos + numbytes);
2338 if(peer->inbufdata > 0)
2340 sockpushdata(sk, peer->inbuf, peer->inbufdata);
2341 peer->inbufdata = 0;
2342 transread(sk, peer);
2348 static void cmd_(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
2353 hubhandleaction(sk, fn, cmd, args);
2357 static void cmd_(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2363 static int hubreqconn(struct fnetpeer *peer)
2368 if((peer->fn->state != FNN_EST) || (peer->fn->fnet != &dcnet))
2373 if((hub = peer->fn->data) == NULL)
2378 if((mbsnick = icwcstombs(peer->id, hub->charset)) == NULL)
2379 return(1); /* Shouldn't happen, of course, but who knows... */
2382 sendctm(hub->sk, mbsnick);
2383 expectpeer(mbsnick, peer->fn);
2385 qstrf(hub->sk, "$RevConnectToMe %s %s|", hub->nativenick, mbsnick);
2391 static int hubsendchat(struct fnetnode *fn, int public, wchar_t *to, wchar_t *string)
2394 char *mbsstring, *mbsto;
2397 if((mbsto = icwcstombs(to, hub->charset)) == NULL)
2402 if((mbsstring = icwcstombs(string, hub->charset)) == NULL)
2407 if((strchr(mbsto, '|') != NULL) || (strchr(mbsto, ' ') != NULL))
2414 if(strchr(mbsstring, '|') != NULL)
2425 qstrf(hub->sk, "<%s> %s|", hub->nativenick, mbsstring);
2427 qstrf(hub->sk, "$To: %s From: %s $<%s> %s|", mbsto, hub->nativenick, hub->nativenick, mbsstring);
2430 qstrf(hub->sk, "$To: %s From: %s $<%s> %s|", mbsto, hub->nativenick, hub->nativenick, mbsstring);
2437 static void findsizelimit(struct sexpr *sexpr, int *min, int *max)
2439 int minl, maxl, minr, maxr, retmin, retmax;
2444 findsizelimit(sexpr->l, &minl, &maxl);
2445 findsizelimit(sexpr->r, &minr, &maxr);
2446 retmin = (minl > minr)?minl:minr;
2447 if((maxl != -1) && (maxr != -1))
2448 retmax = (maxl < maxr)?maxl:maxr;
2457 findsizelimit(sexpr->l, &minl, &maxl);
2458 findsizelimit(sexpr->r, &minr, &maxr);
2459 retmin = (minl < minr)?minl:minr;
2460 if((maxl == -1) || (maxr == -1))
2463 retmax = (maxl > maxr)?maxl:maxr;
2466 findsizelimit(sexpr->l, &minl, &maxl);
2467 if((minl == 0) && (maxl == -1)) /* Interval is unspecified */
2471 } else if((minl == 0) && (maxl != -1)) {
2474 } else if((minl != 0) && (maxl == -1)) {
2477 } else { /* This would yield two seperate intervals, which DC cannot handle */
2483 retmax = sexpr->d.n - 1;
2486 retmin = sexpr->d.n;
2487 retmax = sexpr->d.n;
2490 retmin = sexpr->d.n + 1;
2504 static struct hash *findsehash(struct sexpr *sexpr)
2506 struct hash *h1, *h2;
2511 if((h1 = findsehash(sexpr->l)) != NULL)
2513 if((h1 = findsehash(sexpr->r)) != NULL)
2517 if((h1 = findsehash(sexpr->l)) == NULL)
2519 if((h2 = findsehash(sexpr->r)) == NULL)
2525 if(!wcscmp(sexpr->d.hash->algo, L"TTH"))
2526 return(sexpr->d.hash);
2533 static int hubsearch(struct fnetnode *fn, struct search *srch, struct srchfnnlist *ln)
2536 struct wcslist *list, *cur;
2537 char *sstr, *buf, *p;
2538 size_t sstrsize, sstrdata;
2539 struct sockaddr *name;
2541 int minsize, maxsize;
2545 if((fn->state != FNN_EST) || (hub->sk == NULL) || (hub->sk->state != SOCK_EST))
2547 list = findsexprstrs(srch->sexpr);
2548 findsizelimit(srch->sexpr, &minsize, &maxsize);
2549 hash = findsehash(srch->sexpr);
2550 if((minsize != 0) && (maxsize != -1))
2552 /* Choose either minsize or maxsize by trying to determine
2553 * which choice will be most restrictive. The result can be
2554 * approximative at best anyway, so don't try too hard... */
2555 if((50000000 - maxsize) > (minsize - 50000000))
2561 sstrsize = sstrdata = 0;
2562 if((hash != NULL) && (hash->len == 24))
2564 /* Prioritize hash searches above all else */
2565 bufcat(sstr, "F?T?0?9?TTH:", 12);
2566 buf = base32encode(hash->buf, hash->len);
2568 bufcat(sstr, buf, 39);
2573 sizebuf2(sstr, sstrdata + 32, 1);
2574 sstrdata += snprintf(sstr + sstrdata, sstrsize - sstrdata, "T?F?%i?1?", minsize);
2575 } else if(maxsize != -1) {
2576 sizebuf2(sstr, sstrdata + 32, 1);
2577 sstrdata += snprintf(sstr + sstrdata, sstrsize - sstrdata, "T?T?%i?1?", maxsize);
2579 bufcat(sstr, "F?F?0?1?", 8);
2583 for(cur = list; cur != NULL; cur = cur->next)
2585 /* Use DCCHARSET in $Get paths until further researched... */
2586 if((buf = icwcstombs(cur->str, DCCHARSET)) == NULL)
2588 /* Can't find anything anyway if the search expression
2589 * requires characters outside DC's charset. There's
2590 * nothing technically wrong with the search itself,
2591 * however, so return success. This should be
2592 * considered as an optimization. */
2599 addtobuf(sstr, '$');
2601 * It probably doesn't hurt if buf contains any extra
2602 * dollar signs - it will just result in extra search
2603 * terms, and the extraneous results will be filtered by
2604 * the search layer anyway. It hurts if it contains any
2605 * pipes, though, so let's sell them for money.
2607 for(p = buf; *p; p++)
2612 bufcat(sstr, buf, strlen(buf));
2616 /* Will match all files... :-/ */
2617 addtobuf(sstr, '.');
2623 if(sockgetremotename2(udpsock, hub->sk, &name, &namelen) < 0)
2625 flog(LOG_WARNING, "cannot get address of UDP socket");
2627 qstrf(hub->sk, "$Search %s %s|", formataddress(name, namelen), sstr);
2631 qstrf(hub->sk, "$Search Hub:%s %s|", hub->nativenick, sstr);
2635 fn->lastsrch = time(NULL);
2643 #define cc(c) ((void (*)(struct socket *, void *, char *, char *))(c))
2644 static struct command hubcmds[] =
2646 {"$Lock", cc(cmd_lock)},
2647 {"$HubName", cc(cmd_hubname)},
2648 {"$Hello", cc(cmd_hello)},
2649 {"$Quit", cc(cmd_quit)},
2650 {"$NickList", cc(cmd_nicklist)},
2651 {"$OpList", cc(cmd_oplist)},
2652 {"$MyINFO", cc(cmd_myinfo)},
2653 {"$ForceMove", cc(cmd_forcemove)},
2654 {"$Search", cc(cmd_search), .limit = 100},
2655 {"$MultiSearch", cc(cmd_search), .limit = 50},
2656 {"$ConnectToMe", cc(cmd_connecttome), .limit = 200},
2657 {"$RevConnectToMe", cc(cmd_revconnecttome), .limit = 500},
2658 {"$GetNetInfo", cc(cmd_getnetinfo)},
2659 {"$To:", cc(cmd_to)},
2660 {"$SR", cc(cmd_sr)},
2661 {"$UserCommand", cc(cmd_usercommand)},
2662 {"$GetPass", cc(cmd_getpass)},
2663 {"$LogedIn", cc(cmd_logedin)}, /* sic */
2664 {"$Supports", cc(cmd_hubsupports)},
2668 static struct command peercmds[] =
2670 {"$MyNick", cc(cmd_mynick)},
2671 {"$Lock", cc(cmd_peerlock)},
2672 {"$Direction", cc(cmd_direction)},
2673 {"$Key", cc(cmd_key)},
2674 {"$FileLength", cc(cmd_filelength)},
2675 {"$Error", cc(cmd_error)},
2676 {"$MaxedOut", cc(cmd_maxedout)},
2677 {"$Get", cc(cmd_get)},
2678 {"$Send", cc(cmd_send)},
2679 {"$Supports", cc(cmd_supports)},
2680 {"$GetBlock", cc(cmd_getblock)},
2681 {"$UGetBlock", cc(cmd_getblock)},
2682 {"$GetZBlock", cc(cmd_getblock)},
2683 {"$UGetZBlock", cc(cmd_getblock)},
2684 {"$ADCGET", cc(cmd_adcget)},
2685 {"$ADCSND", cc(cmd_adcsnd), .stop = 1},
2686 {"$Sending", cc(cmd_sending), .stop = 1},
2691 static void dctransdetach(struct transfer *transfer, struct dcpeer *peer)
2693 CBUNREG(transfer, trans_filterout, peer);
2696 peer->transfer = NULL;
2700 static void dctransgotdata(struct transfer *transfer, struct dcpeer *peer)
2704 unsigned char outbuf[1024];
2708 if((peer->state == PEER_TRNS) || (peer->state == PEER_SYNC))
2710 if(sockqueuesize(peer->sk) < 65536)
2712 if((buf = transfergetdata(transfer, &bufsize)) != NULL)
2714 if(peer->compress == CPRS_NONE)
2716 sockqueue(peer->sk, buf, bufsize);
2717 } else if(peer->compress == CPRS_ZLIB) {
2718 cstr = peer->cprsdata;
2719 cstr->next_in = buf;
2720 cstr->avail_in = bufsize;
2721 while(cstr->avail_in > 0)
2723 cstr->next_out = outbuf;
2724 cstr->avail_out = sizeof(outbuf);
2725 if((ret = deflate(cstr, 0)) != Z_OK)
2727 flog(LOG_WARNING, "bug? deflate() did not return Z_OK (but rather %i)", ret);
2731 sockqueue(peer->sk, outbuf, sizeof(outbuf) - cstr->avail_out);
2736 if(peer->state == PEER_SYNC)
2738 if(peer->compress == CPRS_ZLIB)
2740 cstr = peer->cprsdata;
2741 cstr->next_in = NULL;
2745 cstr->next_out = outbuf;
2746 cstr->avail_out = sizeof(outbuf);
2747 ret = deflate(cstr, Z_FINISH);
2748 if((ret != Z_OK) && (ret != Z_STREAM_END))
2750 flog(LOG_WARNING, "bug? deflate(Z_FINISH) did not return Z_OK (but rather %i)", ret);
2754 sockqueue(peer->sk, outbuf, sizeof(outbuf) - cstr->avail_out);
2755 } while(ret != Z_STREAM_END);
2761 if(peer->timeout == NULL)
2762 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
2763 peer->state = PEER_CMD;
2765 transfersetstate(transfer, TRNS_HS);
2766 socksettos(peer->sk, confgetint("fnet", "fnptos"));
2767 transfer->flags.b.minislot = 0;
2768 peer->sk->writecb = NULL;
2775 static void dctransendofdata(struct transfer *transfer, struct dcpeer *peer)
2777 peer->state = PEER_SYNC;
2778 dctransgotdata(transfer, peer);
2781 static void dcwantdata(struct transfer *transfer, struct dcpeer *peer)
2783 if(transferdatasize(transfer) < 65536)
2784 peer->sk->ignread = 0;
2787 static void transread(struct socket *sk, struct dcpeer *peer)
2791 struct transfer *transfer;
2793 if((buf = sockgetinbuf(sk, &bufsize)) == NULL)
2795 if(peer->transfer == NULL)
2801 transferputdata(peer->transfer, buf, bufsize);
2803 if(peer->transfer->curpos >= peer->transfer->size)
2805 transfer = peer->transfer;
2806 transferdetach(transfer);
2807 transferendofdata(transfer);
2810 if(transferdatasize(peer->transfer) > 65535)
2814 static void transerr(struct socket *sk, int err, struct dcpeer *peer)
2816 struct transfer *transfer;
2818 if((transfer = peer->transfer) == NULL)
2823 transferdetach(transfer);
2824 transferendofdata(transfer);
2827 static void transwrite(struct socket *sk, struct dcpeer *peer)
2829 if((peer->state != PEER_TRNS) && (peer->state != PEER_SYNC))
2831 if(peer->transfer == NULL)
2836 dctransgotdata(peer->transfer, peer);
2839 static void udpread(struct socket *sk, void *data)
2841 char *buf, *p, *p2, *hashbuf;
2842 size_t buflen, hashlen;
2843 char *nick, *filename, *hubname;
2844 struct sockaddr_in hubaddr;
2847 struct fnetnode *fn, *myfn;
2850 wchar_t *wnick, *wfile;
2853 if((buf = sockgetinbuf(sk, &buflen)) == NULL)
2855 buf = srealloc(buf, buflen + 1);
2857 if(!strncmp(buf, "$SR ", 4))
2861 if((p2 = strchr(p, ' ')) == NULL)
2869 if((p2 = strchr(p, 5)) == NULL)
2876 if((p2 = strchr(p, ' ')) == NULL)
2882 size = strtoll(p, NULL, 10);
2884 if((p2 = strchr(p, '/')) == NULL)
2892 if((p2 = strchr(p, 5)) == NULL)
2899 if((p2 = strstr(p, " (")) == NULL)
2906 if((p2 = strchr(p, ':')) == NULL)
2912 hubaddr.sin_family = AF_INET;
2913 if(!inet_aton(p, &hubaddr.sin_addr))
2919 if((p2 = strchr(p, ')')) == NULL)
2925 hubaddr.sin_port = htons(atoi(p));
2926 /* Use DCCHARSET in $Get paths until further researched... */
2927 if((wfile = nmdc2path(filename, DCCHARSET)) == NULL)
2934 if(!strncmp(hubname, "TTH:", 4))
2936 if((hashbuf = base32decode(hubname + 4, &hashlen)) != NULL)
2939 hash = newhash(L"TTH", 24, hashbuf);
2943 for(fn = fnetnodes; fn != NULL; fn = fn->next)
2945 if((fn->fnet == &dcnet) && ((hub = fn->data) != NULL))
2947 if((hub->nativename != NULL) && !strcmp(hub->nativename, hubname))
2962 for(fn = fnetnodes; fn != NULL; fn = fn->next)
2964 if((fn->fnet == &dcnet) && ((hub = fn->data) != NULL))
2966 if((hub->sk != NULL) && addreq(hub->sk->remote, (struct sockaddr *)&hubaddr))
2977 if((wnick = icmbstowcs(nick, (hub == NULL)?DCCHARSET:(hub->charset))) == NULL)
2982 sr = newsrchres(&dcnet, wfile, wnick);
2983 if(sr->peernick != NULL)
2985 sr->peernick = swcsdup(wnick);
2991 getfnetnode(sr->fn = myfn);
3000 static void hubread(struct socket *sk, struct fnetnode *fn)
3003 struct command *cmd;
3005 size_t datalen, cnlen;
3008 hub = (struct dchub *)fn->data;
3009 if((newbuf = sockgetinbuf(sk, &datalen)) == NULL)
3011 if(hub->inbufdata > 500000) /* Discard possible malicious data */
3013 sizebuf2(hub->inbuf, hub->inbufdata + datalen, 1);
3014 memcpy(hub->inbuf + hub->inbufdata, newbuf, datalen);
3016 p = hub->inbuf + hub->inbufdata;
3017 hub->inbufdata += datalen;
3018 while((datalen > 0) && ((p = memchr(p, '|', datalen)) != NULL))
3021 for(cmd = hubcmds; cmd->handler != NULL; cmd++)
3023 cnlen = strlen(cmd->name);
3024 if(!strncmp(hub->inbuf, cmd->name, cnlen) && ((hub->inbuf[cnlen] == ' ') || (hub->inbuf[cnlen] == 0)))
3027 if((cmd->limit == 0) || (hub->queue.size < cmd->limit))
3028 newqcmd(&hub->queue, hub->inbuf);
3029 memmove(hub->inbuf, p, hub->inbufdata -= p - hub->inbuf);
3030 datalen = hub->inbufdata;
3033 if(hub->queue.size > 1000)
3037 static void huberr(struct socket *sk, int err, struct fnetnode *fn)
3042 static int hubsetnick(struct fnetnode *fn, wchar_t *newnick)
3048 if((buf = icwcstombs(newnick, (hub == NULL)?DCCHARSET:(hub->charset))) == NULL)
3050 if((strchr(buf, ' ') != NULL) || (strchr(buf, '|') != NULL) || (strchr(buf, '$') != NULL))
3055 if(hub == NULL) /* Not yet connected */
3060 if(hub->nativenick != NULL)
3061 free(hub->nativenick);
3062 hub->nativenick = buf;
3066 static struct dchub *newdchub(struct fnetnode *fn)
3073 new = smalloc(sizeof(*new));
3074 memset(new, 0, sizeof(*new));
3076 if(confgetint("dc", "dcppemu"))
3078 if((emu = wpfind(fn->args, L"dcppemu")) != NULL)
3086 if((wcharset = wpfind(fn->args, L"charset")) != NULL)
3088 if((charset = icwcstombs(wcharset, "US-ASCII")) != NULL)
3090 if(!havecharset(charset))
3098 new->charset = charset;
3100 new->charset = sstrdup(DCCHARSET);
3101 if(hubsetnick(fn, fn->mynick))
3102 fnetsetnick(fn, L"DoldaConnectUser-IN");
3103 /* IN as in Invalid Nick */
3107 static struct dcpeer *newdcpeer(struct socket *sk)
3111 new = smalloc(sizeof(*new));
3112 memset(new, 0, sizeof(*new));
3113 new->transfer = NULL;
3116 if(confgetint("dc", "dcppemu"))
3127 static void freedcpeer(struct dcpeer *peer)
3130 struct qcommand *qcmd;
3135 if(peer->next != NULL)
3136 peer->next->prev = peer->prev;
3137 if(peer->prev != NULL)
3138 peer->prev->next = peer->next;
3139 if(peer->transfer != NULL)
3141 if(peer->transfer->dir == TRNSD_UP)
3142 peer->transfer->close = 1;
3143 if(peer->transfer->dir == TRNSD_DOWN)
3144 resettransfer(peer->transfer);
3145 transferdetach(peer->transfer);
3147 if(peer->timeout != NULL)
3148 canceltimer(peer->timeout);
3149 if(peer->sk->data == peer)
3150 peer->sk->data = NULL;
3151 peer->sk->readcb = NULL;
3152 peer->sk->writecb = NULL;
3153 peer->sk->errcb = NULL;
3156 if(peer->supports != NULL)
3158 for(i = 0; peer->supports[i] != NULL; i++)
3159 free(peer->supports[i]);
3160 free(peer->supports);
3162 if(peer->inbuf != NULL)
3164 if(peer->key != NULL)
3166 if(peer->wcsname != NULL)
3167 free(peer->wcsname);
3168 if(peer->nativename != NULL)
3169 free(peer->nativename);
3170 if(peer->charset != NULL)
3171 free(peer->charset);
3172 if(peer->fn != NULL)
3173 putfnetnode(peer->fn);
3174 while((qcmd = ulqcmd(&peer->queue)) != NULL)
3180 static void hubconnect(struct fnetnode *fn, struct socket *sk)
3184 sk->readcb = (void (*)(struct socket *, void *))hubread;
3185 sk->errcb = (void (*)(struct socket *, int, void *))huberr;
3186 fn->data = hub = newdchub(fn);
3188 getsock(hub->sk = sk);
3192 static void hubdestroy(struct fnetnode *fn)
3196 struct qcommand *qcmd;
3198 hub = (struct dchub *)fn->data;
3200 while((qcmd = ulqcmd(&hub->queue)) != NULL)
3202 if(hub->supports != NULL)
3204 for(i = 0; hub->supports[i] != NULL; i++)
3205 free(hub->supports[i]);
3206 free(hub->supports);
3208 if(hub->nativename != NULL)
3209 free(hub->nativename);
3210 if(hub->nativenick != NULL)
3211 free(hub->nativenick);
3212 if(hub->charset != NULL)
3214 if(hub->inbuf != NULL)
3219 static void hubkill(struct fnetnode *fn)
3223 hub = (struct dchub *)fn->data;
3227 static wchar_t *dcbasename(wchar_t *filename)
3231 if((ret = wcsrchr(filename, L'/')) != NULL)
3236 static struct transferiface dctransfer =
3238 .detach = (void (*)(struct transfer *, void *))dctransdetach,
3239 .gotdata = (void (*)(struct transfer *, void *))dctransgotdata,
3240 .endofdata = (void (*)(struct transfer *, void *))dctransendofdata,
3241 .wantdata = (void (*)(struct transfer *, void *))dcwantdata
3244 static struct fnet dcnet =
3247 .connect = hubconnect,
3248 .destroy = hubdestroy,
3250 .setnick = hubsetnick,
3251 .reqconn = hubreqconn,
3252 .sendchat = hubsendchat,
3253 .search = hubsearch,
3254 .filebasename = dcbasename
3257 static void peerread(struct socket *sk, struct dcpeer *peer)
3260 size_t datalen, cnlen;
3261 struct command *cmd;
3263 if((newbuf = sockgetinbuf(sk, &datalen)) == NULL)
3265 sizebuf2(peer->inbuf, peer->inbufdata + datalen, 1);
3266 memcpy(peer->inbuf + peer->inbufdata, newbuf, datalen);
3268 peer->inbufdata += datalen;
3269 if(peer->state == PEER_CMD)
3272 while((peer->inbufdata > 0) && (p = memchr(peer->inbuf, '|', peer->inbufdata)) != NULL)
3275 for(cmd = peercmds; cmd->handler != NULL; cmd++)
3277 cnlen = strlen(cmd->name);
3278 if(!strncmp(peer->inbuf, cmd->name, cnlen) && ((peer->inbuf[cnlen] == ' ') || (peer->inbuf[cnlen] == 0)))
3281 if((cmd->limit == 0) || (peer->queue.size < cmd->limit))
3282 newqcmd(&peer->queue, peer->inbuf);
3283 memmove(peer->inbuf, p, peer->inbufdata -= p - peer->inbuf);
3286 peer->state = PEER_STOP;
3289 if(peer->queue.size > 50)
3293 } else if(peer->state == PEER_TTHL) {
3296 if(peer->inbufdata > 500000)
3300 static void peererror(struct socket *sk, int err, struct dcpeer *peer)
3305 static void peerconnect(struct socket *sk, int err, struct fnetnode *fn)
3307 struct dcpeer *peer;
3317 peer = newdcpeer(sk);
3320 peer->dcppemu = hub->dcppemu;
3321 sk->readcb = (void (*)(struct socket *, void *))peerread;
3322 sk->errcb = (void (*)(struct socket *, int, void *))peererror;
3324 socksettos(sk, confgetint("fnet", "fnptos"));
3326 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
3331 static void peeraccept(struct socket *sk, struct socket *newsk, void *data)
3333 struct dcpeer *peer;
3335 peer = newdcpeer(newsk);
3337 newsk->readcb = (void (*)(struct socket *, void *))peerread;
3338 newsk->errcb = (void (*)(struct socket *, int, void *))peererror;
3340 socksettos(newsk, confgetint("fnet", "fnptos"));
3341 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
3344 static void updatehmlist(void)
3346 int i, lev, ic, ret;
3347 struct sharecache *node;
3348 char *buf, *buf2, numbuf[32];
3349 size_t bufsize, bufdata;
3353 buf = smalloc(bufsize = 65536);
3354 node = shareroot->child;
3359 /* Use DCCHARSET in $Get paths until further researched... */
3360 if((buf2 = icwcstombs(node->name, DCCHARSET)) != NULL)
3362 for(i = 0; i < lev; i++)
3364 bufcat(buf, buf2, strlen(buf2));
3366 if(node->f.b.type == FILE_REG)
3369 sprintf(numbuf, "%ji", (intmax_t)node->size);
3370 bufcat(buf, numbuf, strlen(numbuf));
3377 if((node->child != NULL) && !ic)
3381 } else if(node->next != NULL) {
3384 while(node->next == NULL)
3387 node = node->parent;
3388 if(node == shareroot)
3391 if(node == shareroot)
3396 if(hmlistname != NULL)
3401 hmlistname = sstrdup("/tmp/dc-filelist-hm-XXXXXX");
3402 if((fd = mkstemp(hmlistname)) < 0)
3404 flog(LOG_WARNING, "could not create HM file list tempfile: %s", strerror(errno));
3409 * I do not want to implement a good Huffman encoder, and it's not
3410 * like Huffman encoding actually yields any impressive results
3411 * for DC file lists anyway, so I'll just output a bogus
3412 * tree. Implement a good encoder if you want to.
3414 write(fd, "HE3\r\0", 5);
3415 write(fd, &bufdata, 4);
3417 write(fd, &ibuf, 2);
3419 for(i = 0; i < 256; i++)
3422 write(fd, &ibuf, 1);
3424 for(i = 0; i < 256; i++)
3426 for(buf2 = buf; bufdata > 0;)
3428 if((ret = write(fd, buf2, bufdata)) < 0)
3430 flog(LOG_WARNING, "could not write file list: %s", strerror(errno));
3441 static struct xmlent
3448 /* {L'\'', L"""}, Emulate DC++ escaping by omitting this. */
3452 static wchar_t *escapexml(wchar_t *src)
3454 static wchar_t *buf = NULL;;
3457 size_t bufsize, bufdata;
3463 bufsize = bufdata = 0;
3464 for(; *src != L'\0'; src++)
3467 if((c > 0) && (c < 32))
3469 bufcat(buf, L"&#", 2);
3470 ret = swprintf(nbuf, (sizeof(nbuf) / sizeof(*nbuf)), L"%i", c);
3471 bufcat(buf, nbuf, ret);
3472 addtobuf(buf, L';');
3474 for(ent = entities; ent->ent != NULL; ent++)
3478 bufcat(buf, ent->ent, wcslen(ent->ent));
3482 if(ent->ent == NULL)
3483 addtobuf(buf, *src);
3486 addtobuf(buf, L'\0');
3490 static void updatexmllist(void)
3494 char cidbuf[14], *namebuf;
3496 struct sharecache *node;
3498 if(xmllistname != NULL)
3500 unlink(xmllistname);
3503 xmllistname = sstrdup("/tmp/dc-filelist-dcxml-XXXXXX");
3504 if((fd = mkstemp(xmllistname)) < 0)
3506 flog(LOG_WARNING, "could not create XML file list tempfile: %s", strerror(errno));
3511 if((fs = fdopen(fd, "w")) == NULL)
3513 flog(LOG_WARNING, "could not fdopen XML list fd %i: %s", fd, strerror(errno));
3514 unlink(xmllistname);
3520 fprintf(fs, "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>\r\n");
3521 for(i = 0; i < sizeof(cidbuf) - 1; i++)
3522 cidbuf[i] = (rand() % ('Z' - 'A' + 1)) + 'A';
3524 if(confgetint("dc", "dcppemu"))
3525 fprintf(fs, "<FileListing Version=\"1\" CID=\"%s\" Base=\"/\" Generator=\"DC++ 0.674\">\r\n", cidbuf);
3527 fprintf(fs, "<FileListing Version=\"1\" CID=\"%s\" Base=\"/\" Generator=\"%s\">\r\n", cidbuf, "DoldaConnect" VERSION);
3529 node = shareroot->child;
3533 if((namebuf = icswcstombs(escapexml(node->name), "UTF-8", NULL)) != NULL)
3535 for(i = 0; i < lev; i++)
3537 if(node->child != NULL)
3539 fprintf(fs, "<Directory Name=\"%s\">\r\n", namebuf);
3544 fprintf(fs, "<File Name=\"%s\" Size=\"%ji\"", namebuf, (intmax_t)node->size);
3545 if(node->f.b.hastth)
3547 hashbuf = base32encode(node->hashtth, 24);
3548 fprintf(fs, " TTH=\"%.39s\"", hashbuf);
3551 fprintf(fs, "/>\r\n");
3553 while(node->next == NULL)
3555 node = node->parent;
3556 if(node == shareroot)
3561 for(i = 0; i < lev; i++)
3563 fprintf(fs, "</Directory>\r\n");
3566 if(node == shareroot)
3572 if(confgetint("dc", "dcppemu"))
3573 fprintf(fs, "</FileListing>");
3575 fprintf(fs, "</FileListing>\r\n");
3579 static void updatexmlbz2list(void)
3588 if(xmllistname == NULL)
3590 if((in = fopen(xmllistname, "r")) == NULL)
3592 flog(LOG_WARNING, "could not open XML file list for bzipping: %s", strerror(errno));
3595 if(xmlbz2listname != NULL)
3597 unlink(xmlbz2listname);
3598 free(xmlbz2listname);
3600 xmlbz2listname = sstrdup("/tmp/dc-filelist-dcxmlbz2-XXXXXX");
3601 if((fd = mkstemp(xmlbz2listname)) < 0)
3603 flog(LOG_WARNING, "could not create bzipped XML file list tempfile: %s", strerror(errno));
3604 free(xmlbz2listname);
3605 xmlbz2listname = NULL;
3609 if((real = fdopen(fd, "w")) == NULL)
3611 flog(LOG_WARNING, "could not fdopen bzipped XML list fd %i: %s", fd, strerror(errno));
3613 unlink(xmlbz2listname);
3614 free(xmlbz2listname);
3615 xmlbz2listname = NULL;
3619 out = BZ2_bzWriteOpen(&err, real, 9, 0, 0);
3622 flog(LOG_WARNING, "could not open bzip2 stream from XML list");
3624 unlink(xmlbz2listname);
3625 free(xmlbz2listname);
3626 xmlbz2listname = NULL;
3632 bufdata = fread(buf, 1, sizeof(buf), in);
3633 BZ2_bzWrite(&err, out, buf, bufdata);
3636 BZ2_bzWriteClose(&err, out, 0, NULL, NULL);
3640 static void listtimercb(int cancelled, void *uudata)
3642 listwritetimer = NULL;
3647 static void updatelists(int now)
3649 if((hmlistname == NULL) || (xmllistname == NULL) || (xmlbz2listname == NULL))
3653 if(listwritetimer == NULL)
3654 listwritetimer = timercallback(ntime() + confgetint("cli", "hashwritedelay"), listtimercb, NULL);
3657 if(listwritetimer != NULL)
3658 canceltimer(listwritetimer);
3664 static int shareupdate(unsigned long long uusharesize, void *data)
3670 static char *quotestr(char *str)
3674 size_t bufsize, bufdata;
3676 static char *enc = NULL;
3677 size_t encsize, encdata;
3680 bufsize = bufdata = 0;
3681 for(p = (unsigned char *)str; *p; p++)
3684 bufcat(buf, "\\b", 2);
3686 bufcat(buf, "\\t", 2);
3688 bufcat(buf, "\\n", 2);
3690 bufcat(buf, "\\r", 2);
3692 bufcat(buf, "\\\\", 2);
3696 bprintf(buf, "\\x%02x", *p);
3702 if((wbuf = icmbstowcs((char *)buf, DCCHARSET)) != NULL)
3704 enc = icwcstombs(wbuf, NULL);
3709 encsize = encdata = 0;
3710 for(p = buf; *p; p++) {
3714 bprintf(buf, "\\x%x", *p);
3721 static void logunimpl(char *list, char *cmd, char *args)
3725 if((log = fopen("/tmp/dc-unimpl", "a")) == NULL)
3727 flog(LOG_WARNING, "could not open unimpl log: %s", strerror(errno));
3732 fputs(quotestr(cmd), log);
3736 fputs(quotestr(args), log);
3742 static void dispatchcommand(struct qcommand *qcmd, struct command *cmdlist, struct socket *sk, void *data)
3745 struct command *cmd;
3747 if((p = strchr(qcmd->string, ' ')) != NULL)
3749 for(cmd = cmdlist; cmd->handler != NULL; cmd++)
3751 if(!strcmp(cmd->name, qcmd->string))
3754 if(cmd->handler != NULL)
3756 cmd->handler(sk, data, qcmd->string, p);
3757 } else if(confgetint("dc", "logunimpl")) {
3758 if(cmdlist == hubcmds)
3759 logunimpl("hub", qcmd->string, p);
3760 else if(cmdlist == peercmds)
3761 logunimpl("peer", qcmd->string, p);
3763 logunimpl("other?!", qcmd->string, p);
3767 static int run(void)
3769 struct fnetnode *fn, *nextfn;
3771 struct dcpeer *peer, *nextpeer;
3772 struct qcommand *qcmd;
3777 for(fn = fnetnodes; fn != NULL; fn = nextfn)
3780 if(fn->fnet != &dcnet)
3782 if(fn->data == NULL)
3784 hub = (struct dchub *)fn->data;
3785 while((quota > 0) && ((qcmd = ulqcmd(&hub->queue)) != NULL))
3787 if(*qcmd->string == '$')
3789 if((hub->sk != NULL) && (hub->sk->state == SOCK_EST))
3790 dispatchcommand(qcmd, hubcmds, hub->sk, fn);
3791 } else if(*qcmd->string != 0) {
3792 hubrecvchat(hub->sk, fn, NULL, qcmd->string);
3798 if(hub->queue.size < 1000)
3799 hub->sk->ignread = 0;
3804 for(peer = peers; peer != NULL; peer = nextpeer)
3806 nextpeer = peer->next;
3807 while((quota > 0) && ((qcmd = ulqcmd(&peer->queue)) != NULL))
3809 if(peer->timeout != NULL)
3810 canceltimer(peer->timeout);
3811 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
3812 if(*qcmd->string == '$')
3813 dispatchcommand(qcmd, peercmds, peer->sk, peer);
3818 if((peer->queue.size < 50) && (peer->inbufdata < 500000))
3819 peer->sk->ignread = 0;
3826 static void preinit(int hup)
3833 static int updateudpport(struct configvar *var, void *uudata)
3835 struct sockaddr_in addr;
3836 struct socket *newsock;
3838 memset(&addr, 0, sizeof(addr));
3839 addr.sin_family = AF_INET;
3840 addr.sin_port = htons(var->val.num);
3841 if((newsock = netcsdgram((struct sockaddr *)&addr, sizeof(addr))) == NULL)
3843 flog(LOG_WARNING, "could not create new DC UDP socket, reverting to old: %s", strerror(errno));
3846 newsock->readcb = udpread;
3853 static int updatetcpport(struct configvar *var, void *uudata)
3855 struct sockaddr_in addr;
3856 struct socket *newsock;
3858 memset(&addr, 0, sizeof(addr));
3859 addr.sin_family = AF_INET;
3860 addr.sin_port = htons(var->val.num);
3861 if((newsock = netcslisten(SOCK_STREAM, (struct sockaddr *)&addr, sizeof(addr), peeraccept, NULL)) == NULL)
3862 flog(LOG_INFO, "could not listen to a remote address, going into passive mode");
3869 static int init(int hup)
3871 struct sockaddr_in addr;
3875 GCBREG(sharechangecb, shareupdate, NULL);
3880 addr.sin_family = AF_INET;
3881 memset(&addr.sin_addr, 0, sizeof(addr.sin_addr));
3882 addr.sin_port = htons(confgetint("dc", "udpport"));
3883 if((udpsock = netcsdgram((struct sockaddr *)&addr, sizeof(addr))) == NULL)
3885 flog(LOG_CRIT, "could not create DC UDP socket: %s", strerror(errno));
3888 udpsock->readcb = udpread;
3889 addr.sin_port = htons(confgetint("dc", "tcpport"));
3890 if((tcpsock = netcslisten(SOCK_STREAM, (struct sockaddr *)&addr, sizeof(addr), peeraccept, NULL)) == NULL)
3891 flog(LOG_INFO, "could not listen to a remote address, going into passive mode");
3892 CBREG(confgetvar("dc", "udpport"), conf_update, updateudpport, NULL, NULL);
3893 CBREG(confgetvar("dc", "tcpport"), conf_update, updatetcpport, NULL, NULL);
3894 CBREG(confgetvar("net", "mode"), conf_update, updatetcpport, NULL, NULL);
3899 static void terminate(void)
3901 if(hmlistname != NULL)
3906 if(xmllistname != NULL)
3908 unlink(xmllistname);
3911 if(xmlbz2listname != NULL)
3913 unlink(xmlbz2listname);
3914 free(xmlbz2listname);
3918 static struct configvar myvars[] =
3920 /** Specifies the share description reported to other DC users. */
3921 {CONF_VAR_STRING, "desc", {.str = L""}},
3922 /** Specifies the speed reported to other DC users. Normal values
3923 * are 28.8Kbps, 33.6Kbps, 56Kbps, Satellite, ISDN, DSL, Cable,
3924 * LAN(T1) or LAN(T3)*/
3925 {CONF_VAR_STRING, "speedstring", {.str = L"LAN(T1)"}},
3926 /** The e-mail address to report to other DC users. */
3927 {CONF_VAR_STRING, "email", {.str = L"spam@spam.org"}},
3928 /** Specifies a specific UDP port to use for DC search results. If
3929 * left unspecified, a port is allocated dynamically. Useful for
3930 * NAT routers (see also the net.visibleipv4 address for those
3932 {CONF_VAR_INT, "udpport", {.num = 0}},
3933 /** Specifies a specific TCP port to use for DC peer
3934 * connections. If left unspecified, a port is allocated
3935 * dynamically. Useful for NAT routers (see also the
3936 * net.visibleipv4 address for those cases). */
3937 {CONF_VAR_INT, "tcpport", {.num = 0}},
3938 /** If set to true, doldacond will do its best to emulate DC++
3939 * (currently v0.674). This should be left off if at all possible,
3940 * since turning it on will violate the rules of most hubs and
3941 * thus give hub owners an actual reason to kick you if it is
3942 * detected. It might be needed for some of the more bone-headed
3943 * hub owners, though. Note that DC++ emulation can also be turned
3944 * on or off for individual hubs, overriding this setting. */
3945 {CONF_VAR_BOOL, "dcppemu", {.num = 0}},
3946 /** Use for debugging. If set to true, doldacond will log all
3947 * unknown commands it receives, and their arguments, to
3948 * /tmp/dc-unimpl. */
3949 {CONF_VAR_BOOL, "logunimpl", {.num = 0}},
3950 /** If set to true, doldacond will hide its support for deflate
3951 * compression of transfers from other clients, so that they will
3952 * not request compressed uploads. Compressed transfers may
3953 * consume a non-trivial amount of CPU time on slower machines. */
3954 {CONF_VAR_BOOL, "hidedeflate", {.num = 0}},
3958 static struct module me =
3967 .terminate = terminate,