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>
44 #include "sysevents.h"
49 * The Direct Connect protocol is extremely ugly. Thus, this code must
50 * also be a bit ugly in certain places. Please forgive me. =/
52 * This also means that there might be some pieces of the code that
53 * look completely illogical to you, and you think that you may make
54 * them much neater/better. However, in many cases it might just be
55 * that it's required to cope with some oddity of the protocol, such
56 * as the amazingly ugly delayed key response in the peer protocol.
59 /* I assume this is the correct character set to use for DC,
60 * considering it was developed without i18n support under Windows */
61 #define DCCHARSET "windows-1252"
75 void (*handler)(struct socket *sk, void *data, char *cmd, char *args);
82 struct qcommand *next;
88 struct qcommand *f, *l;
96 size_t inbufdata, inbufsize;
97 struct qcmdqueue queue;
98 int extended, dcppemu;
107 struct dcexppeer *next, *prev;
110 struct timer *expire;
115 struct dcpeer *next, *prev;
119 size_t inbufdata, inbufsize;
120 off_t curread, totalsize;
122 struct timer *timeout;
123 struct qcmdqueue queue;
124 struct transfer *transfer;
125 struct socket *trpipe;
127 int ptclose; /* Close after transfer is complete */
128 int accepted; /* If false, we connected, otherwise, we accepted */
129 int extended, dcppemu;
130 int direction; /* Using the constants from transfer.h */
132 int hascurpos, fetchingtthl, notthl;
133 struct tigertreehash tth;
142 static struct fnet dcnet;
143 static struct socket *udpsock = NULL;
144 static struct lport *tcpsock = NULL;
145 static struct dcpeer *peers = NULL;
147 static struct dcexppeer *expected = NULL;
148 static char *hmlistname = NULL;
149 static char *xmllistname = NULL;
150 static char *xmlbz2listname = NULL;
151 static struct timer *listwritetimer = NULL;
153 static struct socket *mktrpipe(struct dcpeer *peer);
154 static void peerconnect(struct socket *sk, int err, struct fnetnode *fn);
155 static void freedcpeer(struct dcpeer *peer);
156 static void transread(struct socket *sk, struct dcpeer *peer);
157 static void transerr(struct socket *sk, int err, struct dcpeer *peer);
158 static void transwrite(struct socket *sk, struct dcpeer *peer);
159 static void updatehmlist(void);
160 static void updatexmllist(void);
161 static void updatexmlbz2list(void);
162 static void requestfile(struct dcpeer *peer);
163 static void updatelists(int now);
164 static int trdestroycb(struct transfer *transfer, struct dcpeer *peer);
166 static int reservedchar(unsigned char c)
168 return((c == 0) || (c == 5) || (c == 124) || (c == 96) || (c == 126) || (c == 36));
171 /* Oh, how I despise having to do this... */
172 static char *dcmakekey(char *lock)
178 buf = smalloc(strlen(lock));
181 for(i = 0; lock[i]; i++)
183 buf[i] = lock[i] ^ save;
184 buf[i] = ((buf[i] & 0x0F) << 4) | ((buf[i] & 0xF0) >> 4);
186 if((i != 0) && reservedchar(buf[i]))
191 buf[0] ^= buf[i - 1];
192 if(reservedchar(buf[0]))
196 key = smalloc(len + 1);
198 for(i = 0; lock[i] != 0; i++)
200 if(reservedchar(buf[i]))
201 offset += sprintf(key + offset, "/%%DCN%03i%%/", buf[i]);
203 key[offset++] = buf[i];
210 static wchar_t *nmdc2path(char *nmdc, char *charset)
214 if((ret = icmbstowcs(nmdc, charset)) == NULL)
216 for(p = ret; *p != L'\0'; p++) {
223 static char *path2nmdc(wchar_t *path, char *charset)
227 if((ret = icwcstombs(path, charset)) == NULL)
229 for(p = ret; *p; p++) {
236 static wchar_t *adc2path(char *adc)
238 return(icmbstowcs(adc, "UTF-8"));
241 static char *path2adc(wchar_t *path)
243 return(icwcstombs(path, "UTF-8"));
246 static int isdchash(struct hash *hash)
248 if(wcscmp(hash->algo, L"TTH"))
256 * Uncomment when used!
258 static int hubsupports(struct dchub *hub, char *cap)
262 if(hub->supports == NULL)
264 for(p = hub->supports; *p != NULL; p++)
266 if(!strcasecmp(*p, cap))
273 static int supports(struct dcpeer *peer, char *cap)
277 if(peer->supports == NULL)
279 for(p = peer->supports; *p != NULL; p++)
281 if(!strcasecmp(*p, cap))
287 static void endcompress(struct dcpeer *peer)
289 if(peer->compress == CPRS_ZLIB)
291 deflateEnd(peer->cprsdata);
292 free(peer->cprsdata);
294 peer->compress = CPRS_NONE;
297 static void initcompress(struct dcpeer *peer, int algo)
302 peer->compress = algo;
303 if(algo == CPRS_ZLIB)
305 peer->cprsdata = smalloc(sizeof(z_stream));
306 memset(peer->cprsdata, 0, sizeof(z_stream));
307 if((ret = deflateInit(peer->cprsdata, 3)) != Z_OK)
309 flog(LOG_CRIT, "Aiya! zlib refuses to init (%i)!", ret);
315 static void unquote(wchar_t *in)
319 for(p = in; *p != L'\0'; p++)
323 for(p2 = p + 1; (*p2 != L'\0') && (*p2 != L';') && (*p2 != L'&'); p2++);
330 if(!wcscmp(p + 1, L"amp"))
333 } else if(p[1] == L'#') {
334 nc = ucptowc(wcstol(p + 2, NULL, 10));
343 memmove(p + 1, p2 + 1, (wcslen(p2 + 1) + 1) * sizeof(wchar_t));
348 static void freeexppeer(struct dcexppeer *ep)
351 ep->next->prev = ep->prev;
353 ep->prev->next = ep->next;
358 if(ep->expire != NULL)
359 canceltimer(ep->expire);
363 static void exppeerexpire(int cancelled, struct dcexppeer *ep)
370 static struct dcexppeer *expectpeer(char *nick, struct fnetnode *fn)
372 struct dcexppeer *ep;
374 ep = smalloc(sizeof(*ep));
375 ep->nick = sstrdup(nick);
376 getfnetnode(ep->fn = fn);
377 ep->expire = timercallback(ntime() + 300, (void (*)(int, void *))exppeerexpire, ep);
386 static struct qcommand *newqcmd(struct qcmdqueue *queue, char *string)
388 struct qcommand *new;
390 new = smalloc(sizeof(*new));
391 new->string = sstrdup(string);
396 queue->l->next = new;
402 static struct qcommand *ulqcmd(struct qcmdqueue *queue)
404 struct qcommand *qcmd;
406 if((qcmd = queue->f) == NULL)
408 if((queue->f = qcmd->next) == NULL)
414 static void freeqcmd(struct qcommand *qcmd)
420 static void hubrecvchat(struct socket *sk, struct fnetnode *fn, char *from, char *string)
422 wchar_t *chat, *wfrom, *wpeer;
424 struct fnetpeer *peer;
428 end = string + strlen(string);
429 while((p = strchr(string, 13)) != NULL)
430 memmove(p, p + 1, (end-- - p));
433 if((strlen(string) > strlen(from) + 2) && (*string == '<') && !memcmp(string + 1, from, strlen(from)) && (*(string + strlen(from) + 1) == '>'))
434 string += strlen(from) + 2;
435 if((wfrom = icmbstowcs(from, hub->charset)) == NULL)
437 wpeer = swcsdup(wfrom);
443 for(p = string + 1; *p; p++)
445 if((*p == ' ') || (*p == '>'))
453 if((wpeer = icmbstowcs(string + 1, hub->charset)) == NULL)
459 wpeer = swcsdup(L"");
461 if((chat = icmbstowcs(string, hub->charset)) == NULL)
471 if((peer = fnetfindpeer(fn, wfrom)) == NULL) /* Assume public chat */
472 fnethandlechat(fn, 1, wfrom, wpeer, chat);
474 fnethandlechat(fn, 0, wfrom, wpeer, chat);
476 fnethandlechat(fn, 1, L"", wpeer, chat);
484 static void peertimeout(int cancelled, struct dcpeer *peer)
486 peer->timeout = NULL;
492 static void sendadc(struct socket *sk, char *arg)
495 size_t bufsize, bufdata;
498 bufsize = bufdata = 0;
504 bufcat(buf, "\\s", 2);
505 } else if(*arg == '\n') {
506 bufcat(buf, "\\n", 2);
507 } else if(*arg == '\\') {
508 bufcat(buf, "\\\\", 2);
513 sockqueue(sk, buf, bufdata);
517 #if defined(__GNUC__)
518 static void __attribute__ ((format (printf, 2, 3))) sendadcf(struct socket *sk, char *arg, ...)
520 static void sendadcf(struct socket *sk, char *arg, ...)
527 buf = vsprintf2(arg, args);
535 static char **parseadc(char *args)
538 size_t retbufsize, retbufdata;
540 size_t bufsize, bufdata;
545 retbufsize = retbufdata = bufsize = bufdata = 0;
554 else if(*args != ' ')
560 if((*args == ' ') || (*args == 0))
563 addtobuf(retbuf, buf);
565 bufsize = bufdata = 0;
568 } else if(*args == '\\') {
571 addtobuf(buf, *args);
580 addtobuf(retbuf, NULL);
583 } else if((*args == 's') || (*args == ' ')) {
585 } else if(*args == 'n') {
587 } else if(*args == '\\') {
597 addtobuf(retbuf, NULL);
601 /* Macros useful in command handlers */
602 #define skipspace(s) ({if(((s) = strchr((s), ' ')) == NULL) return; else (s)++;})
603 #define qstr(sk, str) sockqueue(sk, str, strlen(str))
604 #define qstrf(sk, strandargs...) \
607 if((__buf__ = sprintf2(strandargs)) != NULL) { \
608 sockqueue(sk, __buf__, strlen(__buf__)); \
613 static char *tr(char *str, char *trans)
617 for(; *trans; trans += 2)
619 for(p = strchr(str, trans[0]); p != NULL; p = strchr(p, trans[0]))
625 static char *getadcid(struct dcpeer *peer)
632 if(!wcscmp(peer->transfer->path, L"files.xml") || !wcscmp(peer->transfer->path, L"files.xml.bz2") || !wcscmp(peer->transfer->path, L"MyList.DcLst"))
634 if(!isfilelist && (peer->transfer->hash != NULL) && isdchash(peer->transfer->hash) && supports(peer, "tthf"))
636 buf = base32encode(peer->transfer->hash->buf, 24);
637 ret = sprintf2("TTH/%.39s", buf);
640 ret = path2adc(peer->transfer->path);
646 static int trresumecb(struct transfer *transfer, wchar_t *cmd, wchar_t *arg, struct dcpeer *peer)
648 if(!wcscmp(cmd, L"resume"))
652 flog(LOG_WARNING, "filter returned no position for \"resume\" on transfer %i", transfer->id);
655 transfer->curpos = wcstoll(arg, NULL, 10);
664 static void sendmynick(struct dcpeer *peer)
670 qstrf(peer->sk, "$MyNick %s|", icswcstombs(confgetstr("cli", "defnick"), peer->charset, "DoldaConnectUser-IN"));
672 qstrf(peer->sk, "$MyNick %s|", icswcstombs(fn->mynick, peer->charset, "DoldaConnectUser-IN"));
675 static void sendpeerlock(struct dcpeer *peer)
678 qstrf(peer->sk, "$Lock EXTENDEDPROTOCOLABCABCABCABCABCABC Pk=DCPLUSPLUS0.674ABCABC|");
680 qstrf(peer->sk, "$Lock EXTENDEDPROTOCOLABCABCABCABCABCABC Pk=DOLDA%sABCABCABC|", VERSION);
683 static void sendsupports(struct dcpeer *peer)
686 qstr(peer->sk, "$Supports MiniSlots XmlBZList ADCGet TTHL TTHF GetZBlock ZLIG |");
688 qstr(peer->sk, "$Supports MiniSlots XmlBZList ADCGet TTHL TTHF");
689 if(!confgetint("dc", "hidedeflate"))
690 qstr(peer->sk, " GetZBlock ZLIG");
695 static void requestfile(struct dcpeer *peer)
699 if(peer->transfer->size == -1)
701 /* Use DCCHARSET for $Get paths until further researched... */
702 if((buf = path2nmdc(peer->transfer->path, DCCHARSET)) == NULL)
704 transferseterror(peer->transfer, TRNSE_NOTFOUND);
708 /* The transfer will be restarted later from
709 * cmd_filelength when it detects that the sizes
711 qstrf(peer->sk, "$Get %s$1|", buf);
715 if((peer->transfer->hash == NULL) && !peer->notthl)
717 if(supports(peer, "adcget") && supports(peer, "tthl"))
719 qstr(peer->sk, "$ADCGET");
720 sendadc(peer->sk, "tthl");
721 if((buf = getadcid(peer)) == NULL)
723 transferseterror(peer->transfer, TRNSE_NOTFOUND);
727 sendadc(peer->sk, buf);
729 sendadc(peer->sk, "0");
730 sendadc(peer->sk, "-1");
732 peer->fetchingtthl = 1;
738 if(forkfilter(peer->transfer))
740 flog(LOG_WARNING, "could not fork filter for transfer %i: %s", peer->transfer->id, strerror(errno));
746 if(supports(peer, "adcget"))
748 qstr(peer->sk, "$ADCGET");
749 sendadc(peer->sk, "file");
750 if((buf = getadcid(peer)) == NULL)
752 transferseterror(peer->transfer, TRNSE_NOTFOUND);
756 sendadc(peer->sk, buf);
758 sendadcf(peer->sk, "%ji", (intmax_t)peer->transfer->curpos);
759 sendadcf(peer->sk, "%ji", (intmax_t)(peer->transfer->size - peer->transfer->curpos));
761 } else if(supports(peer, "xmlbzlist")) {
762 if((buf = path2nmdc(peer->transfer->path, "UTF-8")) == NULL)
764 transferseterror(peer->transfer, TRNSE_NOTFOUND);
768 qstrf(peer->sk, "$UGetBlock %ji %ji %s|", (intmax_t)peer->transfer->curpos, (intmax_t)(peer->transfer->size - peer->transfer->curpos), buf);
771 /* Use DCCHARSET for $Get paths until further researched... */
772 if((buf = path2nmdc(peer->transfer->path, DCCHARSET)) == NULL)
774 transferseterror(peer->transfer, TRNSE_NOTFOUND);
778 qstrf(peer->sk, "$Get %s$%ji|", buf, (intmax_t)peer->transfer->curpos + 1);
783 static void sendmyinfo(struct socket *sk, struct fnetnode *fn)
787 struct fnetnode *cfn;
791 qstrf(sk, "$MyINFO $ALL %s ", hub->nativenick);
792 buf = tr(icswcstombs(confgetstr("dc", "desc"), hub->charset, "Charset_conv_failure"), "$_|_");
793 qstrf(sk, "%s", buf);
795 for(cfn = fnetnodes; cfn != NULL; cfn = cfn->next)
797 if((cfn->state == FNN_EST) || (cfn->state == FNN_HS))
799 if(cfn->regstatus == FNNS_OP)
801 else if(cfn->regstatus == FNNS_REG)
807 qstrf(sk, "<%s V:%s,M:%c,H:%i/%i/%i,S:%i>",
808 (hub->dcppemu)?"++":"Dolda",
809 (hub->dcppemu)?"0.674":VERSION,
810 (tcpsock == NULL)?'P':'A',
812 confgetint("transfer", "slots")
815 buf = tr(icswcstombs(confgetstr("dc", "speedstring"), hub->charset, "Charset_conv_failure"), "$_|_");
816 qstrf(sk, "%s\x01$", buf);
817 buf = tr(icswcstombs(confgetstr("dc", "email"), hub->charset, "Charset_conv_failure"), "$_|_");
818 qstrf(sk, "%s$", buf);
819 qstrf(sk, "%llu$|", sharesize);
822 static void hubhandleaction(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
827 if(!strcmp(cmd, "$Lock"))
829 qstrf(sk, "$ValidateNick %s|", hub->nativenick);
830 } else if(!strcmp(cmd, "$Hello")) {
831 if(fn->state == FNN_HS)
833 qstrf(sk, "$Version 1,0091|");
834 qstrf(sk, "$GetNickList|");
836 fnetsetstate(fn, FNN_EST);
838 qstrf(sk, "$GetINFO %s %s|", args, hub->nativenick);
843 static void cmd_lock(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
850 if(!strncmp(args, "EXTENDEDPROTOCOL", 16))
852 if((p = strchr(args, ' ')) != NULL)
857 qstrf(sk, "$Supports UserCommand NoGetINFO NoHello UserIP2 TTHSearch GetZBlock |");
859 qstrf(sk, "$Supports UserCommand NoGetINFO NoHello UserIP2 TTHSearch");
860 if(!confgetint("dc", "hidedeflate"))
861 qstr(sk, " GetZBlock");
865 key = dcmakekey(args);
866 qstrf(sk, "$Key %s|", key);
868 hubhandleaction(sk, fn, cmd, args);
871 static void cmd_hubname(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
877 if(hub->nativename != NULL)
878 free(hub->nativename);
879 hub->nativename = sstrdup(args);
880 buf = icmbstowcs(args, hub->charset);
881 fnetsetname(fn, (buf == NULL)?L"Hubname conv error":buf);
884 hubhandleaction(sk, fn, cmd, args);
887 static void cmd_hello(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
893 if((nick = icmbstowcs(args, hub->charset)) == NULL)
895 if(strcmp(args, hub->nativenick) && (fnetfindpeer(fn, nick) == NULL))
896 fnetaddpeer(fn, nick, nick);
898 hubhandleaction(sk, fn, cmd, args);
901 static void cmd_quit(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
904 struct fnetpeer *peer;
908 if((nick = icmbstowcs(args, hub->charset)) == NULL)
910 if((peer = fnetfindpeer(fn, nick)) != NULL)
913 hubhandleaction(sk, fn, cmd, args);
916 static void cmd_nicklist(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
921 struct fnetpeer *peer;
924 for(peer = btreeiter(fn->peers); peer != NULL; peer = btreeiter(NULL))
925 peer->flags.b.delete = 1;
926 while((p = strstr(args, "$$")) != NULL)
929 if((buf = icmbstowcs(args, hub->charset)) != NULL)
931 if((peer = fnetfindpeer(fn, buf)) == NULL)
932 peer = fnetaddpeer(fn, buf, buf);
934 peer->flags.b.delete = 0;
936 qstrf(sk, "$GetINFO %s %s|", args, hub->nativenick);
941 hubhandleaction(sk, fn, cmd, args);
944 static void cmd_oplist(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
949 struct fnetpeer *peer;
952 for(peer = btreeiter(fn->peers); peer != NULL; peer = btreeiter(NULL))
953 peer->flags.b.op = 0;
954 while((p = strstr(args, "$$")) != NULL)
957 if((buf = icmbstowcs(args, hub->charset)) != NULL)
959 if((peer = fnetfindpeer(fn, buf)) != NULL)
960 peer->flags.b.op = 1;
965 hubhandleaction(sk, fn, cmd, args);
968 static void cmd_myinfo(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
971 wchar_t *buf, *wp, *wp2;
973 struct fnetpeer *peer;
978 if(strncmp(p, "$ALL ", 5))
981 if((p2 = strchr(p, ' ')) == NULL)
984 if((buf = icmbstowcs(p, hub->charset)) == NULL)
986 if((peer = fnetfindpeer(fn, buf)) == NULL)
987 peer = fnetaddpeer(fn, buf, buf);
990 if((p2 = strstr(p, "$ $")) == NULL)
993 if((buf = icmbstowcs(p, hub->charset)) == NULL)
995 if((wcslen(buf) > 0) && (buf[wcslen(buf) - 1] == L'>') && ((wp = wcsrchr(buf, L'<')) != NULL))
997 buf[wcslen(buf) - 1] = L'\0';
999 if((wp2 = wcschr(wp, L' ')) != NULL)
1002 fnetpeersetstr(peer, L"dc-client", wp);
1006 if((wp2 = wcschr(wp, L',')) != NULL)
1010 swprintf(abuf, 10, L"dc-tag-%lc", wp[0]);
1011 fnetpeersetstr(peer, abuf, wp + 2);
1013 } while(wp2 != NULL);
1016 fnetpeersetstr(peer, L"descr", buf);
1019 if((p2 = strchr(p, '$')) == NULL)
1022 if((buf = icmbstowcs(p, hub->charset)) == NULL)
1024 fnetpeersetstr(peer, L"dc-speed", buf);
1027 if((p2 = strchr(p, '$')) == NULL)
1030 if((buf = icmbstowcs(p, hub->charset)) == NULL)
1032 fnetpeersetstr(peer, L"email", buf);
1037 fnetpeersetlnum(peer, L"share", strtoll(p, NULL, 10));
1038 hubhandleaction(sk, fn, cmd, args);
1041 /* I do not implement the fully in that I do not disconnect from the
1042 * old hub. I do this since I believe that if the hub owner really
1043 * wants to get rid of us, then it is his responsibility to disconnect
1045 static void cmd_forcemove(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1048 struct fnetnode *newfn;
1052 if(strchr(args, ':') == NULL)
1054 args = strcpy(smalloc(strlen(args) + 5), args);
1055 strcat(args, ":411");
1060 if((newfn = fnetinitconnect(L"dc", fn->owner, args, NULL)) != NULL)
1062 linkfnetnode(newfn);
1065 hubhandleaction(sk, fn, cmd, args);
1070 static char *getdcpath(struct sharecache *node, size_t *retlen, char *charset)
1075 if(node->parent == NULL)
1077 if(node->parent == shareroot)
1079 if((buf = icwcstombs(node->name, charset)) == NULL)
1082 *retlen = strlen(buf);
1085 if((buf2 = icwcstombs(node->name, charset)) == NULL)
1087 if((buf = getdcpath(node->parent, &len, charset)) == NULL)
1092 len2 = strlen(buf2);
1093 buf = srealloc(buf, len + 1 + len2 + 1);
1095 strcpy(buf + len, buf2);
1096 buf[len + len2] = 0;
1099 *retlen = len + len2;
1105 * This is the main share searching function for Direct Connect
1106 * peers. Feel free to optimize it if you feel the need for it. I
1107 * haven't ever seen it take any noticable CPU time anyway, so I
1108 * haven't felt that need.
1110 * It may feel dubious to just return the directory when all terms are
1111 * satisfied rather than all the files in it, but it really benefits
1112 * everyone: Less cycles used for us, less UDP squelching for active
1113 * searchers, and less bandwidth waste for hubs when serving passive
1116 static void cmd_search(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1121 char *prefix, *infix, *postfix, *buf, *buf2;
1123 struct sockaddr_in addr;
1124 struct sharecache *node;
1125 int minsize, maxsize;
1128 int termnum, satisfied, matches, skipcheck, proper;
1129 int level, tersat[32];
1130 wchar_t *terms[32], *lname;
1134 if((p = strchr(args, ' ')) == NULL)
1138 memset(terms, 0, sizeof(terms));
1139 prefix = infix = postfix = NULL;
1143 if(!strncmp(args, "Hub:", 4))
1145 if(!strcmp(cmd, "$MultiSearch"))
1147 if(!strcmp(args + 4, hub->nativenick))
1149 prefix = sprintf2("$SR %s ", hub->nativenick);
1150 infix = sprintf2(" %i/%i\005", slotsleft(), confgetint("transfer", "slots"));
1151 postfix = sprintf2(" (%s)\005%s|", formatsockpeer(hub->sk), args + 4);
1155 if((p2 = strchr(args, ':')) == NULL)
1158 addr.sin_family = AF_INET;
1159 if(!inet_aton(args, &addr.sin_addr))
1161 addr.sin_port = htons(atoi(p2));
1162 prefix = sprintf2("$SR %s ", hub->nativenick);
1163 infix = sprintf2(" %i/%i\005", slotsleft(), confgetint("transfer", "slots"));
1164 postfix = sprintf2(" (%s)|", formatsockpeer(hub->sk));
1165 dsk = netdgramconn(udpsock, (struct sockaddr *)&addr, sizeof(addr));
1168 minsize = maxsize = -1;
1177 if((*(p++) == 'T') && (minsize == 0))
1184 if((p2 = strchr(p, '?')) == NULL)
1200 if((*p2 == 0) || (*p2 == '$'))
1208 if(!dotth && !strncmp(p, "TTH:", 4))
1211 if(((buf = base32decode(p + 4, &buflen)) == NULL) || (buflen != 24))
1216 memcpy(hashtth, buf, 24);
1219 if((terms[termnum] = icmbstowcs(p, hub->charset)) != NULL) {
1220 wcslower(terms[termnum]);
1221 if(wcslen(terms[termnum]) > 1)
1236 node = shareroot->child;
1238 for(i = 0; i < termnum; i++)
1245 if(node->f.b.type == FILE_REG)
1247 if((minsize >= 0) && (node->size < minsize))
1249 if((maxsize >= 0) && (node->size > maxsize))
1252 if(!skipcheck && dotth)
1254 if((node->f.b.type != FILE_REG) || (node->f.b.hastth && memcmp(hashtth, node->hashtth, 24)))
1259 lname = wcslower(swcsdup(node->name));
1260 for(i = 0; i < termnum; i++)
1264 if(wcsstr(lname, terms[i]))
1268 } else if(node->child == NULL) {
1274 if(!skipcheck && (satisfied == termnum))
1276 /* Use DCCHARSET in $Get paths until further researched... */
1277 if((buf = getdcpath(node, NULL, DCCHARSET)) != NULL)
1279 if(node->f.b.hastth)
1281 buf2 = base32encode(node->hashtth, 24);
1282 qstrf(dsk, "%s%s\005%ji%sTTH:%.39s%s", prefix, buf, (intmax_t)node->size, infix, buf2, postfix);
1285 qstrf(dsk, "%s%s\005%ji%s%s%s", prefix, buf, (intmax_t)node->size, infix, hub->nativename, postfix);
1292 if((!skipcheck && (satisfied == termnum)) || (node->child == NULL))
1294 while(node->next == NULL)
1296 if((node = node->parent) == shareroot)
1300 if(node == shareroot)
1302 for(i = 0; i < termnum; i++)
1304 if(tersat[i] >= level)
1317 hubhandleaction(sk, fn, cmd, args);
1328 for(i = 0; (i < 32) && (terms[i] != NULL); i++)
1332 static void cmd_connecttome(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1336 struct sockaddr_in addr;
1339 if((p = strchr(args, ' ')) == NULL)
1342 if(strcmp(args, hub->nativenick))
1344 addr.sin_family = AF_INET;
1346 if((p = strchr(args, ':')) == NULL)
1349 addr.sin_port = htons(atoi(p));
1350 if(!inet_aton(args, &addr.sin_addr))
1352 putsock(netcsconn((struct sockaddr *)&addr, sizeof(addr), (void (*)(struct socket *, int, void *))peerconnect, fn));
1354 hubhandleaction(sk, fn, cmd, args);
1357 static void sendctm(struct socket *sk, char *nick)
1359 struct sockaddr *addr;
1364 if(lstgetremotename2(tcpsock, sk, &addr, &addrlen) < 0)
1366 if(addr->sa_family == AF_INET)
1367 qstrf(sk, "$ConnectToMe %s %s|", nick, formataddress(addr, addrlen));
1369 flog(LOG_WARNING, "Direct Connect TCP socket is suddenly not AF_INET, but %i", addr->sa_family);
1373 static void cmd_revconnecttome(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1379 if((p = strchr(args, ' ')) == NULL)
1382 if(strcmp(p, hub->nativenick))
1385 expectpeer(args, fn);
1386 hubhandleaction(sk, fn, cmd, args);
1389 static void cmd_getnetinfo(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1392 struct fnetnode *node;
1397 for(node = fnetnodes; node != NULL; node = node->next)
1399 if(node->state == FNN_EST)
1402 qstrf(sk, "$NetInfo %i$%i$%c$0|", confgetint("transfer", "slots"), numhubs, (tcpsock == NULL)?'P':'A');
1403 hubhandleaction(sk, fn, cmd, args);
1406 static void cmd_to(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1413 if((p2 = strchr(p, ' ')) == NULL)
1417 if((p2 = strchr(p, ' ')) == NULL)
1420 if(strcmp(p, "From:"))
1423 if((p2 = strstr(p, " $")) == NULL)
1427 hubrecvchat(hub->sk, fn, p, p2);
1428 hubhandleaction(sk, fn, cmd, args);
1431 static void cmd_sr(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1435 char *nick, *filename, *hubname;
1440 wchar_t *wnick, *wfile;
1444 if((p2 = strchr(p, ' ')) == NULL)
1449 if((p2 = strchr(p, 5)) == NULL)
1453 if((p2 = strchr(p, ' ')) == NULL)
1456 size = strtoll(p, NULL, 10);
1458 if((p2 = strchr(p, '/')) == NULL)
1463 if((p2 = strchr(p, 5)) == NULL)
1467 if((p2 = strstr(p, " (")) == NULL)
1470 if((wnick = icmbstowcs(nick, hub->charset)) == NULL)
1472 /* Use DCCHARSET in $Get paths until further researched... */
1473 if((wfile = nmdc2path(filename, DCCHARSET)) == NULL)
1478 sr = newsrchres(&dcnet, wfile, wnick);
1479 if(sr->peernick != NULL)
1481 sr->peernick = swcsdup(wnick);
1486 if(!strncmp(hubname, "TTH:", 4))
1488 if((buf = base32decode(hubname + 4, &buflen)) != NULL)
1491 sr->hash = newhash(L"TTH", 24, buf);
1495 getfnetnode(sr->fn = fn);
1498 hubhandleaction(sk, fn, cmd, args);
1501 static void cmd_usercommand(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1503 /* Do nothing for now. */
1506 static void cmd_getpass(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1513 pw = wpfind(fn->args, L"password");
1514 if((pw == NULL) || ((mbspw = icwcstombs(pw, hub->charset)) == NULL))
1519 qstrf(sk, "$MyPass %s|", mbspw);
1521 fn->regstatus = FNNS_REG;
1522 hubhandleaction(sk, fn, cmd, args);
1525 static void cmd_logedin(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1530 fn->regstatus = FNNS_OP;
1531 hubhandleaction(sk, fn, cmd, args);
1534 static void cmd_hubsupports(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1540 size_t arrsize, arrdata;
1543 if(hub->supports != NULL)
1545 for(i = 0; hub->supports[i] != NULL; i++)
1546 free(hub->supports[i]);
1547 free(hub->supports);
1550 arrsize = arrdata = 0;
1554 if((p2 = strchr(p, ' ')) != NULL)
1558 addtobuf(arr, sstrdup(p));
1559 } while((p = p2) != NULL);
1560 addtobuf(arr, NULL);
1561 hub->supports = arr;
1564 static void cmd_mynick(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1566 struct dcexppeer *expect;
1569 if(peer->nativename != NULL)
1570 free(peer->nativename);
1571 peer->nativename = sstrdup(args);
1572 if(peer->wcsname != NULL)
1573 free(peer->wcsname);
1574 if((peer->wcsname = icmbstowcs(peer->nativename, peer->charset)) == NULL)
1581 for(expect = expected; expect != NULL; expect = expect->next)
1583 if(!strcmp(expect->nick, args))
1590 hub = expect->fn->data;
1591 peer->fn = expect->fn;
1592 getfnetnode(peer->fn);
1593 peer->dcppemu = hub->dcppemu;
1594 freeexppeer(expect);
1599 static void peerattach(struct dcpeer *peer, struct transfer *transfer)
1601 peer->transfer = transfer;
1602 CBREG(peer->transfer, trans_filterout, (int (*)(struct transfer *, wchar_t *, wchar_t *, void *))trresumecb, NULL, peer);
1603 CBREG(peer->transfer, trans_destroy, (int (*)(struct transfer *, void *))trdestroycb, NULL, peer);
1606 static void cmd_direction(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1610 struct transfer *transfer;
1612 if((p = strchr(args, ' ')) == NULL)
1615 if(!strcmp(args, "Upload"))
1617 if(!strcmp(args, "Download"))
1621 if((peer->transfer == NULL) || (mydir != peer->direction))
1626 if(peer->direction == TRNSD_DOWN)
1629 if((peer->wcsname == NULL) || (peer->transfer != NULL))
1634 peer->direction = mydir;
1635 if(peer->direction == TRNSD_UP)
1637 if(confgetint("transfer", "ulquota") && hasupload(&dcnet, peer->wcsname))
1642 transfer = newupload(peer->fn, &dcnet, peer->wcsname, (peer->trpipe = mktrpipe(peer))->back);
1644 if((transfer = finddownload(peer->wcsname)) == NULL)
1649 transferattach(transfer, (peer->trpipe = mktrpipe(peer))->back);
1650 transfersetstate(transfer, TRNS_HS);
1652 transfersetnick(transfer, peer->wcsname);
1653 peerattach(peer, transfer);
1656 qstrf(sk, "$Direction %s %i|", (peer->direction == TRNSD_UP)?"Upload":"Download", rand() % 10000);
1657 if(peer->key != NULL)
1658 qstrf(sk, "$Key %s|", peer->key);
1659 if(peer->direction == TRNSD_DOWN)
1664 static void cmd_peerlock(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1667 struct transfer *transfer;
1669 if((p = strchr(args, ' ')) == NULL)
1672 if(!strncmp(args, "EXTENDEDPROTOCOL", 16))
1674 key = dcmakekey(args);
1677 if(peer->wcsname == NULL)
1686 if((transfer = finddownload(peer->wcsname)) == NULL)
1688 if(confgetint("transfer", "ulquota") && hasupload(&dcnet, peer->wcsname))
1693 peer->direction = TRNSD_UP;
1694 transfer = newupload(peer->fn, &dcnet, peer->wcsname, (peer->trpipe = mktrpipe(peer))->back);
1696 peer->direction = TRNSD_DOWN;
1697 transferattach(transfer, (peer->trpipe = mktrpipe(peer))->back);
1698 transfersetstate(transfer, TRNS_HS);
1700 transfersetnick(transfer, peer->wcsname);
1701 peerattach(peer, transfer);
1702 qstrf(sk, "$Direction %s %i|", (peer->direction == TRNSD_UP)?"Upload":"Download", rand() % 10000);
1703 qstrf(sk, "$Key %s|", key);
1706 if(peer->key != NULL)
1712 static void cmd_key(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1717 static void startdl(struct dcpeer *peer)
1719 if(peer->timeout != NULL)
1720 canceltimer(peer->timeout);
1721 peer->state = PEER_TRNS;
1722 transferstartdl(peer->transfer, peer->sk);
1723 peer->sk->readcb = (void (*)(struct socket *, void *))transread;
1724 peer->sk->errcb = (void (*)(struct socket *, int, void *))transerr;
1727 static void startul(struct dcpeer *peer)
1729 if(peer->timeout != NULL)
1730 canceltimer(peer->timeout);
1731 peer->state = PEER_TRNS;
1732 transferstartul(peer->transfer, peer->sk);
1733 peer->sk->writecb = (void (*)(struct socket *, void *))transwrite;
1734 transwrite(peer->sk, peer);
1737 static void cmd_filelength(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1740 struct transfer *transfer;
1742 if(peer->transfer == NULL)
1747 size = strtoll(args, NULL, 10);
1748 if(peer->transfer->size != size)
1750 transfersetsize(peer->transfer, size);
1751 transfer = peer->transfer;
1753 resettransfer(transfer);
1754 trytransferbypeer(transfer->fnet, transfer->peerid);
1758 qstr(peer->sk, "$Send|");
1761 static void cmd_error(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1763 if(peer->fetchingtthl)
1765 peer->fetchingtthl = 0;
1770 if((peer->transfer != NULL) && (peer->transfer->dir == TRNSD_DOWN))
1772 transferseterror(peer->transfer, TRNSE_NOTFOUND);
1773 resettransfer(peer->transfer);
1779 static void cmd_maxedout(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1781 if((peer->transfer != NULL) && (peer->transfer->dir == TRNSD_DOWN))
1783 transferseterror(peer->transfer, TRNSE_NOSLOTS);
1784 resettransfer(peer->transfer);
1797 {"MyList.DcLst", &hmlistname, updatehmlist},
1798 {"files.xml", &xmllistname, updatexmllist},
1799 {"files.xml.bz2", &xmlbz2listname, updatexmlbz2list},
1803 static int openfilelist(char *name)
1808 for(i = 0; lists[i].name != NULL; i++)
1810 if(!strcmp(name, lists[i].name))
1814 if(lists[i].name == NULL)
1817 if((*lists[i].file == NULL) || ((fd = open(*lists[i].file, O_RDONLY)) < 0))
1819 if((fd < 0) && ((*lists[i].file == NULL) || ((fd = open(*lists[i].file, O_RDONLY)) < 0)))
1822 flog(LOG_ERR, "could not open filelist tempfile: %s", strerror(errno));
1829 static struct sharecache *findbytth(char *tth32)
1833 struct sharecache *node;
1835 if((buf = base32decode(tth32, &buflen)) == NULL)
1842 for(node = shareroot->child; node != NULL; node = nextscnode(node))
1844 if(node->f.b.hastth && !memcmp(node->hashtth, buf, 24))
1851 static struct sharecache *resdcpath(char *path, char *charset, char sep)
1853 struct sharecache *node;
1860 if((p2 = strchr(p, sep)) != NULL)
1862 if((node = findcache(node, icsmbstowcs(p, charset, L""))) == NULL)
1869 static void cmd_get(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1874 struct sharecache *node;
1875 struct socket *lesk;
1879 if(peer->transfer == NULL)
1884 if((p = strchr(args, '$')) == NULL)
1890 if((offset = (strtoll(p, NULL, 10) - 1)) < 0)
1895 if(((fd = openfilelist(args)) < 0) && (errno != 0))
1897 qstr(sk, "$Error Could not send file list|");
1900 } else if(fd >= 0) {
1901 if((buf2 = nmdc2path(args, DCCHARSET)) != NULL) {
1902 transfersetpath(peer->transfer, buf2);
1905 peer->transfer->flags.b.minislot = 1;
1909 /* Use DCCHARSET in $Get paths until further researched... */
1910 if((node = resdcpath(args, DCCHARSET, '\\')) == NULL)
1912 qstrf(sk, "$Error File not in share|");
1916 if((fd = opensharecache(node)) < 0)
1918 qstrf(sk, "$Error %s|", strerror(errno));
1922 buf = getfspath(node);
1923 if((buf2 = icsmbstowcs(buf, NULL, NULL)) == NULL)
1924 flog(LOG_WARNING, "could not convert native path into a wcs (%s): %s", buf, strerror(errno));
1926 transfersetpath(peer->transfer, buf2);
1929 if(fstat(fd, &sb) < 0)
1932 flog(LOG_WARNING, "could not stat file %ls: %s", node->name, strerror(errno));
1933 qstrf(sk, "$Error|");
1937 if(sb.st_size < 65536)
1938 peer->transfer->flags.b.minislot = 1;
1939 if(!peer->transfer->flags.b.minislot && (slotsleft() < 1)) {
1941 qstr(sk, "$MaxedOut|");
1945 if((offset != 0) && (lseek(fd, offset, SEEK_SET) < 0))
1948 qstrf(sk, "$Error Offset out of range|");
1952 lesk = wrapsock(fd);
1953 transferprepul(peer->transfer, sb.st_size, offset, -1, lesk);
1955 qstrf(sk, "$FileLength %ji|", (intmax_t)peer->transfer->size);
1958 static void cmd_send(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1960 if(peer->transfer == NULL)
1965 if(peer->transfer->localend == NULL)
1974 static void cmd_supports(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1979 size_t arrsize, arrdata;
1981 if(peer->supports != NULL)
1983 for(i = 0; peer->supports[i] != NULL; i++)
1984 free(peer->supports[i]);
1985 free(peer->supports);
1988 arrsize = arrdata = 0;
1992 if((p2 = strchr(p, ' ')) != NULL)
1996 addtobuf(arr, sstrdup(p));
1997 } while((p = p2) != NULL);
1998 addtobuf(arr, NULL);
1999 peer->supports = arr;
2002 static void cmd_getblock(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2006 off_t start, numbytes;
2007 char *charset, *buf;
2009 struct sharecache *node;
2011 struct socket *lesk;
2013 if(peer->transfer == NULL)
2019 if((p2 = strchr(p, ' ')) == NULL)
2025 start = strtoll(p, NULL, 10);
2027 if((p2 = strchr(p, ' ')) == NULL)
2033 numbytes = strtoll(p, NULL, 10);
2035 if(!strcmp(cmd, "$UGetBlock") || !strcmp(cmd, "$UGetZBlock"))
2038 /* Use DCCHARSET in $Get paths until further researched... */
2039 charset = DCCHARSET;
2040 if(!strcmp(cmd, "$GetZBlock") || !strcmp(cmd, "$UGetZBlock"))
2041 initcompress(peer, CPRS_ZLIB);
2042 if(((fd = openfilelist(p)) < 0) && (errno != 0))
2044 qstr(sk, "$Error Could not send file list|");
2046 } else if(fd >= 0) {
2047 if((buf2 = nmdc2path(args, charset)) != NULL) {
2048 transfersetpath(peer->transfer, buf2);
2051 peer->transfer->flags.b.minislot = 1;
2055 if((node = resdcpath(p, charset, '\\')) == NULL)
2057 qstr(sk, "$Error File not in cache|");
2060 if((fd = opensharecache(node)) < 0)
2062 qstrf(sk, "$Error %s|", strerror(errno));
2065 buf = getfspath(node);
2066 if((buf2 = icsmbstowcs(buf, NULL, NULL)) == NULL)
2067 flog(LOG_WARNING, "could not convert native path into a wcs (%s): %s", buf, strerror(errno));
2069 transfersetpath(peer->transfer, buf2);
2072 if(fstat(fd, &sb) < 0)
2075 flog(LOG_WARNING, "could not stat file %ls: %s", node->name, strerror(errno));
2076 qstr(sk, "$Error|");
2079 if(sb.st_size < 65536)
2080 peer->transfer->flags.b.minislot = 1;
2081 if(!peer->transfer->flags.b.minislot && (slotsleft() < 1)) {
2083 qstr(sk, "$MaxedOut|");
2086 if((start != 0) && ((start >= sb.st_size) || (lseek(fd, start, SEEK_SET) < 0)))
2089 qstr(sk, "$Error Offset out of range|");
2092 if((numbytes < 0) || (start + numbytes > sb.st_size))
2093 numbytes = sb.st_size - start;
2094 lesk = wrapsock(fd);
2095 transferprepul(peer->transfer, sb.st_size, start, start + numbytes, lesk);
2097 qstrf(sk, "$Sending %ji|", (intmax_t)numbytes);
2101 static void cmd_adcget(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2105 off_t start, numbytes;
2106 struct sharecache *node;
2108 struct socket *lesk;
2112 if(peer->transfer == NULL)
2117 if((argv = parseadc(args)) == NULL)
2122 if(parrlen(argv) < 4)
2127 start = strtoll(argv[2], NULL, 10);
2128 numbytes = strtoll(argv[3], NULL, 10);
2131 if(((fd = openfilelist(argv[1])) < 0) && (errno != 0))
2133 qstr(sk, "$Error Could not send file list|");
2135 } else if(fd >= 0) {
2136 if((wbuf = adc2path(argv[1])) != NULL)
2137 transfersetpath(peer->transfer, wbuf);
2139 peer->transfer->flags.b.minislot = 1;
2143 if(!strncmp(argv[1], "TTH/", 4))
2145 if((node = findbytth(argv[1] + 4)) == NULL)
2147 qstr(sk, "$Error File not in cache|");
2151 if((node = resdcpath((argv[1][0] == '/')?(argv[1] + 1):(argv[1]), "UTF-8", '/')) == NULL)
2153 qstr(sk, "$Error File not in cache|");
2157 if((fd = opensharecache(node)) < 0)
2159 qstrf(sk, "$Error %s|", strerror(errno));
2162 buf = getfspath(node);
2163 if((wbuf = icsmbstowcs(buf, NULL, NULL)) == NULL)
2164 flog(LOG_WARNING, "could not convert native path into a wcs (%s): %s", buf, strerror(errno));
2166 transfersetpath(peer->transfer, wbuf);
2169 if(!strcmp(argv[0], "file"))
2171 for(i = 4; argv[i] != NULL; i++)
2173 if(!strcmp(argv[i], "ZL1"))
2174 initcompress(peer, CPRS_ZLIB);
2176 if(fstat(fd, &sb) < 0)
2178 flog(LOG_WARNING, "could not stat file %ls: %s", node->name, strerror(errno));
2179 qstr(sk, "$Error|");
2182 if(sb.st_size < 65536)
2183 peer->transfer->flags.b.minislot = 1;
2184 if(!peer->transfer->flags.b.minislot && (slotsleft() < 1)) {
2185 qstr(sk, "$MaxedOut|");
2188 if((start != 0) && ((start >= sb.st_size) || (lseek(fd, start, SEEK_SET) < 0)))
2190 qstr(sk, "$Error Offset out of range|");
2193 if((numbytes < 0) || (start + numbytes > sb.st_size))
2194 numbytes = sb.st_size - start;
2195 lesk = wrapsock(fd);
2196 transferprepul(peer->transfer, sb.st_size, start, start + numbytes, lesk);
2199 qstr(sk, "$ADCSND");
2200 sendadc(sk, "file");
2201 sendadc(sk, argv[1]);
2202 sendadcf(sk, "%ji", (intmax_t)start);
2203 sendadcf(sk, "%ji", (intmax_t)numbytes);
2204 if(peer->compress == CPRS_ZLIB)
2208 } else if(!strcmp(argv[0], "tthl")) {
2210 * XXX: Implement full TTHL support.
2212 * In the meantime, this is better than nothing, since it at
2213 * least allows fetching of the TTH root if it isn't already
2218 qstr(sk, "$Error no TTHL data for virtual files|");
2221 qstr(sk, "$ADCSND");
2222 sendadc(sk, "tthl");
2223 sendadc(sk, argv[1]);
2227 sockqueue(sk, node->hashtth, 24);
2229 qstr(sk, "$Error Namespace not implemented|");
2239 static void handletthl(struct dcpeer *peer)
2243 while(peer->inbufdata >= 24)
2245 pushtigertree(&peer->tth, peer->inbuf);
2246 memmove(peer->inbuf, peer->inbuf + 24, peer->inbufdata -= 24);
2247 peer->curread += 24;
2249 if(peer->curread >= peer->totalsize)
2251 if(peer->timeout == NULL)
2252 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
2253 peer->state = PEER_CMD;
2254 synctigertree(&peer->tth);
2255 restigertree(&peer->tth, buf);
2256 transfersethash(peer->transfer, newhash(L"TTH", 24, buf));
2261 static void cmd_adcsnd(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2264 off_t start, numbytes;
2266 if(peer->transfer == NULL)
2271 if((argv = parseadc(args)) == NULL)
2276 if(parrlen(argv) < 4)
2281 start = strtoll(argv[2], NULL, 10);
2282 numbytes = strtoll(argv[3], NULL, 10);
2283 if(!strcmp(argv[0], "tthl"))
2285 if((start != 0) || (numbytes % 24 != 0))
2287 /* Weird. Bail out. */
2291 if(peer->timeout != NULL)
2292 canceltimer(peer->timeout);
2293 peer->state = PEER_TTHL;
2294 peer->totalsize = numbytes;
2296 peer->fetchingtthl = 0;
2297 inittigertree(&peer->tth);
2299 } else if(!strcmp(argv[0], "file")) {
2300 if(start != peer->transfer->curpos)
2305 if(start + numbytes != peer->transfer->size)
2307 transfersetsize(peer->transfer, start + numbytes);
2312 if(peer->inbufdata > 0)
2314 sockpushdata(sk, peer->inbuf, peer->inbufdata);
2315 peer->inbufdata = 0;
2318 /* We certainly didn't request this...*/
2327 static void cmd_sending(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2331 if(peer->transfer == NULL)
2336 numbytes = strtoll(args, NULL, 10);
2337 if(peer->transfer->size - peer->transfer->curpos != numbytes)
2339 transfersetsize(peer->transfer, peer->transfer->curpos + numbytes);
2344 if(peer->inbufdata > 0)
2346 sockpushdata(sk, peer->inbuf, peer->inbufdata);
2347 peer->inbufdata = 0;
2353 static void cmd_(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
2358 hubhandleaction(sk, fn, cmd, args);
2362 static void cmd_(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2368 static int hubreqconn(struct fnetpeer *peer)
2373 if((peer->fn->state != FNN_EST) || (peer->fn->fnet != &dcnet))
2378 if((hub = peer->fn->data) == NULL)
2383 if((mbsnick = icwcstombs(peer->id, hub->charset)) == NULL)
2384 return(1); /* Shouldn't happen, of course, but who knows... */
2387 sendctm(hub->sk, mbsnick);
2388 expectpeer(mbsnick, peer->fn);
2390 qstrf(hub->sk, "$RevConnectToMe %s %s|", hub->nativenick, mbsnick);
2396 static int hubsendchat(struct fnetnode *fn, int public, wchar_t *to, wchar_t *string)
2399 char *mbsstring, *mbsto;
2402 if((mbsto = icwcstombs(to, hub->charset)) == NULL)
2407 if((mbsstring = icwcstombs(string, hub->charset)) == NULL)
2412 if((strchr(mbsto, '|') != NULL) || (strchr(mbsto, ' ') != NULL))
2419 if(strchr(mbsstring, '|') != NULL)
2430 qstrf(hub->sk, "<%s> %s|", hub->nativenick, mbsstring);
2432 qstrf(hub->sk, "$To: %s From: %s $<%s> %s|", mbsto, hub->nativenick, hub->nativenick, mbsstring);
2435 qstrf(hub->sk, "$To: %s From: %s $<%s> %s|", mbsto, hub->nativenick, hub->nativenick, mbsstring);
2442 static void findsizelimit(struct sexpr *sexpr, off_t *min, off_t *max)
2444 off_t minl, maxl, minr, maxr, retmin, retmax;
2449 findsizelimit(sexpr->l, &minl, &maxl);
2450 findsizelimit(sexpr->r, &minr, &maxr);
2451 retmin = (minl > minr)?minl:minr;
2452 if((maxl != -1) && (maxr != -1))
2453 retmax = (maxl < maxr)?maxl:maxr;
2462 findsizelimit(sexpr->l, &minl, &maxl);
2463 findsizelimit(sexpr->r, &minr, &maxr);
2464 retmin = (minl < minr)?minl:minr;
2465 if((maxl == -1) || (maxr == -1))
2468 retmax = (maxl > maxr)?maxl:maxr;
2471 findsizelimit(sexpr->l, &minl, &maxl);
2472 if((minl == 0) && (maxl == -1)) /* Interval is unspecified */
2476 } else if((minl == 0) && (maxl != -1)) {
2479 } else if((minl != 0) && (maxl == -1)) {
2482 } else { /* This would yield two seperate intervals, which DC cannot handle */
2488 retmax = sexpr->d.sz - 1;
2491 retmin = sexpr->d.sz;
2492 retmax = sexpr->d.sz;
2495 retmin = sexpr->d.sz + 1;
2509 static struct hash *findsehash(struct sexpr *sexpr)
2511 struct hash *h1, *h2;
2516 if((h1 = findsehash(sexpr->l)) != NULL)
2518 if((h1 = findsehash(sexpr->r)) != NULL)
2522 if((h1 = findsehash(sexpr->l)) == NULL)
2524 if((h2 = findsehash(sexpr->r)) == NULL)
2530 if(!wcscmp(sexpr->d.hash->algo, L"TTH"))
2531 return(sexpr->d.hash);
2538 static int hubsearch(struct fnetnode *fn, struct search *srch, struct srchfnnlist *ln)
2541 struct wcslist *list, *cur;
2542 char *sstr, *buf, *p;
2543 size_t sstrsize, sstrdata;
2544 struct sockaddr *name;
2546 off_t minsize, maxsize;
2550 if((fn->state != FNN_EST) || (hub->sk == NULL) || (hub->sk->state != SOCK_EST))
2552 list = findsexprstrs(srch->sexpr);
2553 findsizelimit(srch->sexpr, &minsize, &maxsize);
2554 hash = findsehash(srch->sexpr);
2555 if((minsize != 0) && (maxsize != -1))
2557 /* Choose either minsize or maxsize by trying to determine
2558 * which choice will be most restrictive. The result can be
2559 * approximative at best anyway, so don't try too hard... */
2560 if((50000000 - maxsize) > (minsize - 50000000))
2566 sstrsize = sstrdata = 0;
2567 if((hash != NULL) && (hash->len == 24))
2569 /* Prioritize hash searches above all else */
2570 bufcat(sstr, "F?T?0?9?TTH:", 12);
2571 buf = base32encode(hash->buf, hash->len);
2573 bufcat(sstr, buf, 39);
2578 sizebuf2(sstr, sstrdata + 32, 1);
2579 sstrdata += snprintf(sstr + sstrdata, sstrsize - sstrdata, "T?F?%ji?1?", (intmax_t)minsize);
2580 } else if(maxsize != -1) {
2581 sizebuf2(sstr, sstrdata + 32, 1);
2582 sstrdata += snprintf(sstr + sstrdata, sstrsize - sstrdata, "T?T?%ji?1?", (intmax_t)maxsize);
2584 bufcat(sstr, "F?F?0?1?", 8);
2588 for(cur = list; cur != NULL; cur = cur->next)
2590 /* Use DCCHARSET in $Get paths until further researched... */
2591 if((buf = icwcstombs(cur->str, DCCHARSET)) == NULL)
2593 /* Can't find anything anyway if the search expression
2594 * requires characters outside DC's charset. There's
2595 * nothing technically wrong with the search itself,
2596 * however, so return success. This should be
2597 * considered as an optimization. */
2604 addtobuf(sstr, '$');
2606 * It probably doesn't hurt if buf contains any extra
2607 * dollar signs - it will just result in extra search
2608 * terms, and the extraneous results will be filtered by
2609 * the search layer anyway. It hurts if it contains any
2610 * pipes, though, so let's sell them for money.
2612 for(p = buf; *p; p++)
2617 bufcat(sstr, buf, strlen(buf));
2621 /* Will match all files... :-/ */
2622 addtobuf(sstr, '.');
2628 if(sockgetremotename2(udpsock, hub->sk, &name, &namelen) < 0)
2630 flog(LOG_WARNING, "cannot get address of UDP socket");
2632 qstrf(hub->sk, "$Search %s %s|", formataddress(name, namelen), sstr);
2636 qstrf(hub->sk, "$Search Hub:%s %s|", hub->nativenick, sstr);
2640 fn->lastsrch = time(NULL);
2648 #define cc(c) ((void (*)(struct socket *, void *, char *, char *))(c))
2649 static struct command hubcmds[] =
2651 {"$Lock", cc(cmd_lock)},
2652 {"$HubName", cc(cmd_hubname)},
2653 {"$Hello", cc(cmd_hello)},
2654 {"$Quit", cc(cmd_quit)},
2655 {"$NickList", cc(cmd_nicklist)},
2656 {"$OpList", cc(cmd_oplist)},
2657 {"$MyINFO", cc(cmd_myinfo)},
2658 {"$ForceMove", cc(cmd_forcemove)},
2659 {"$Search", cc(cmd_search), .limit = 100},
2660 {"$MultiSearch", cc(cmd_search), .limit = 50},
2661 {"$ConnectToMe", cc(cmd_connecttome), .limit = 200},
2662 {"$RevConnectToMe", cc(cmd_revconnecttome), .limit = 500},
2663 {"$GetNetInfo", cc(cmd_getnetinfo)},
2664 {"$To:", cc(cmd_to)},
2665 {"$SR", cc(cmd_sr)},
2666 {"$UserCommand", cc(cmd_usercommand)},
2667 {"$GetPass", cc(cmd_getpass)},
2668 {"$LogedIn", cc(cmd_logedin)}, /* sic */
2669 {"$Supports", cc(cmd_hubsupports)},
2673 static struct command peercmds[] =
2675 {"$MyNick", cc(cmd_mynick)},
2676 {"$Lock", cc(cmd_peerlock)},
2677 {"$Direction", cc(cmd_direction)},
2678 {"$Key", cc(cmd_key)},
2679 {"$FileLength", cc(cmd_filelength)},
2680 {"$Error", cc(cmd_error)},
2681 {"$MaxedOut", cc(cmd_maxedout)},
2682 {"$Get", cc(cmd_get)},
2683 {"$Send", cc(cmd_send)},
2684 {"$Supports", cc(cmd_supports)},
2685 {"$GetBlock", cc(cmd_getblock)},
2686 {"$UGetBlock", cc(cmd_getblock)},
2687 {"$GetZBlock", cc(cmd_getblock)},
2688 {"$UGetZBlock", cc(cmd_getblock)},
2689 {"$ADCGET", cc(cmd_adcget)},
2690 {"$ADCSND", cc(cmd_adcsnd), .stop = 1},
2691 {"$Sending", cc(cmd_sending), .stop = 1},
2696 static void dctransgotdata(struct transfer *transfer, struct dcpeer *peer)
2700 unsigned char outbuf[1024];
2704 if((peer->state == PEER_TRNS) || (peer->state == PEER_SYNC))
2706 if(sockqueueleft(peer->sk) > 0)
2708 if((buf = sockgetinbuf(peer->trpipe, &bufsize)) != NULL)
2710 if(peer->compress == CPRS_NONE)
2712 sockqueue(peer->sk, buf, bufsize);
2713 } else if(peer->compress == CPRS_ZLIB) {
2714 cstr = peer->cprsdata;
2715 cstr->next_in = buf;
2716 cstr->avail_in = bufsize;
2717 while(cstr->avail_in > 0)
2719 cstr->next_out = outbuf;
2720 cstr->avail_out = sizeof(outbuf);
2721 if((ret = deflate(cstr, 0)) != Z_OK)
2723 flog(LOG_WARNING, "bug? deflate() did not return Z_OK (but rather %i)", ret);
2727 sockqueue(peer->sk, outbuf, sizeof(outbuf) - cstr->avail_out);
2732 if(peer->state == PEER_SYNC)
2734 if(peer->compress == CPRS_ZLIB)
2736 cstr = peer->cprsdata;
2737 cstr->next_in = NULL;
2741 cstr->next_out = outbuf;
2742 cstr->avail_out = sizeof(outbuf);
2743 ret = deflate(cstr, Z_FINISH);
2744 if((ret != Z_OK) && (ret != Z_STREAM_END))
2746 flog(LOG_WARNING, "bug? deflate(Z_FINISH) did not return Z_OK (but rather %i)", ret);
2750 sockqueue(peer->sk, outbuf, sizeof(outbuf) - cstr->avail_out);
2751 } while(ret != Z_STREAM_END);
2757 if(peer->timeout == NULL)
2758 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
2759 peer->state = PEER_CMD;
2761 transfersetstate(transfer, TRNS_HS);
2762 socksettos(peer->sk, confgetint("fnet", "fnptos"));
2763 transfer->flags.b.minislot = 0;
2764 peer->sk->writecb = NULL;
2771 static void peerdetach(struct dcpeer *peer)
2773 CBUNREG(peer->transfer, trans_filterout, peer);
2774 CBUNREG(peer->transfer, trans_destroy, peer);
2775 peer->trpipe->pnext = NULL;
2776 closesock(peer->trpipe);
2777 quitsock(peer->trpipe);
2778 peer->trpipe = NULL;
2779 peer->transfer = NULL;
2782 static int trdestroycb(struct transfer *transfer, struct dcpeer *peer)
2789 static void transread(struct socket *sk, struct dcpeer *peer)
2794 if(peer->transfer == NULL) {
2798 if(sockqueueleft(peer->trpipe) < 0)
2800 if((buf = sockgetinbuf(sk, &bufsize)) != NULL)
2802 if(peer->transfer == NULL)
2808 sockqueue(peer->trpipe, buf, bufsize);
2811 if(peer->transfer->curpos >= peer->transfer->size)
2819 static void transerr(struct socket *sk, int err, struct dcpeer *peer)
2821 struct transfer *transfer;
2823 if((transfer = peer->transfer) == NULL)
2832 static void transwrite(struct socket *sk, struct dcpeer *peer)
2834 if((peer->state != PEER_TRNS) && (peer->state != PEER_SYNC))
2836 if(peer->transfer == NULL)
2841 dctransgotdata(peer->transfer, peer);
2842 sockread(peer->trpipe);
2845 static void trpiperead(struct socket *sk, struct dcpeer *peer)
2847 dctransgotdata(peer->transfer, peer);
2850 static void trpipewrite(struct socket *sk, struct dcpeer *peer)
2852 transread(peer->sk, peer);
2855 static void trpipeerr(struct socket *sk, int errno, struct dcpeer *peer)
2857 peer->state = PEER_SYNC;
2858 dctransgotdata(peer->transfer, peer);
2860 if(peer->state != PEER_CMD)
2864 static struct socket *mktrpipe(struct dcpeer *peer)
2869 sk->pnext = peer->sk;
2871 sk->readcb = (void (*)(struct socket *, void *))trpiperead;
2872 sk->writecb = (void (*)(struct socket *, void *))trpipewrite;
2873 sk->errcb = (void (*)(struct socket *, int, void *))trpipeerr;
2877 static void udpread(struct socket *sk, void *data)
2879 char *buf, *p, *p2, *hashbuf;
2880 size_t buflen, hashlen;
2881 char *nick, *filename, *hubname;
2882 struct sockaddr_in hubaddr;
2883 struct sockaddr *addrbuf;
2886 struct fnetnode *fn, *myfn;
2889 wchar_t *wnick, *wfile;
2892 if((buf = sockgetinbuf(sk, &buflen)) == NULL)
2894 buf = srealloc(buf, buflen + 1);
2896 if(!strncmp(buf, "$SR ", 4))
2900 if((p2 = strchr(p, ' ')) == NULL)
2908 if((p2 = strchr(p, 5)) == NULL)
2915 if((p2 = strchr(p, ' ')) == NULL)
2921 size = strtoll(p, NULL, 10);
2923 if((p2 = strchr(p, '/')) == NULL)
2931 if((p2 = strchr(p, 5)) == NULL)
2938 if((p2 = strstr(p, " (")) == NULL)
2945 if((p2 = strchr(p, ':')) == NULL)
2951 hubaddr.sin_family = AF_INET;
2952 if(!inet_aton(p, &hubaddr.sin_addr))
2958 if((p2 = strchr(p, ')')) == NULL)
2964 hubaddr.sin_port = htons(atoi(p));
2965 /* Use DCCHARSET in $Get paths until further researched... */
2966 if((wfile = nmdc2path(filename, DCCHARSET)) == NULL)
2973 if(!strncmp(hubname, "TTH:", 4))
2975 if((hashbuf = base32decode(hubname + 4, &hashlen)) != NULL)
2978 hash = newhash(L"TTH", 24, hashbuf);
2982 for(fn = fnetnodes; fn != NULL; fn = fn->next)
2984 if((fn->fnet == &dcnet) && ((hub = fn->data) != NULL))
2986 if((hub->nativename != NULL) && !strcmp(hub->nativename, hubname))
3001 for(fn = fnetnodes; fn != NULL; fn = fn->next)
3003 if((fn->fnet == &dcnet) && ((hub = fn->data) != NULL) && !sockpeeraddr(hub->sk, &addrbuf, NULL))
3005 if((hub->sk != NULL) && addreq(addrbuf, (struct sockaddr *)&hubaddr))
3018 if((wnick = icmbstowcs(nick, (hub == NULL)?DCCHARSET:(hub->charset))) == NULL)
3023 sr = newsrchres(&dcnet, wfile, wnick);
3024 if(sr->peernick != NULL)
3026 sr->peernick = swcsdup(wnick);
3032 getfnetnode(sr->fn = myfn);
3041 static void hubread(struct socket *sk, struct fnetnode *fn)
3044 struct command *cmd;
3046 size_t datalen, cnlen;
3049 hub = (struct dchub *)fn->data;
3050 if(hub->queue.size > 1000)
3052 if((newbuf = sockgetinbuf(sk, &datalen)) == NULL)
3054 if(hub->inbufdata > 500000) /* Discard possible malicious data */
3056 sizebuf2(hub->inbuf, hub->inbufdata + datalen, 1);
3057 memcpy(hub->inbuf + hub->inbufdata, newbuf, datalen);
3060 hub->inbufdata += datalen;
3061 while((p - hub->inbuf < hub->inbufdata) && ((p2 = memchr(p, '|', hub->inbufdata - (p - hub->inbuf))) != NULL))
3064 for(cmd = hubcmds; cmd->handler != NULL; cmd++)
3066 cnlen = strlen(cmd->name);
3067 if(!strncmp(p, cmd->name, cnlen) && ((p[cnlen] == ' ') || (p[cnlen] == 0)))
3070 if((cmd->limit == 0) || (hub->queue.size < cmd->limit))
3071 newqcmd(&hub->queue, p);
3074 memmove(hub->inbuf, p, hub->inbufdata -= p - hub->inbuf);
3077 static void huberr(struct socket *sk, int err, struct fnetnode *fn)
3082 static int hubsetnick(struct fnetnode *fn, wchar_t *newnick)
3088 if((buf = icwcstombs(newnick, (hub == NULL)?DCCHARSET:(hub->charset))) == NULL)
3090 if((strchr(buf, ' ') != NULL) || (strchr(buf, '|') != NULL) || (strchr(buf, '$') != NULL))
3095 if(hub == NULL) /* Not yet connected */
3100 if(hub->nativenick != NULL)
3101 free(hub->nativenick);
3102 hub->nativenick = buf;
3106 static struct dchub *newdchub(struct fnetnode *fn)
3113 new = smalloc(sizeof(*new));
3114 memset(new, 0, sizeof(*new));
3116 if(confgetint("dc", "dcppemu"))
3118 if((emu = wpfind(fn->args, L"dcppemu")) != NULL)
3126 if((wcharset = wpfind(fn->args, L"charset")) != NULL)
3128 if((charset = icwcstombs(wcharset, "US-ASCII")) != NULL)
3130 if(!havecharset(charset))
3138 new->charset = charset;
3140 new->charset = sstrdup(DCCHARSET);
3141 if(hubsetnick(fn, fn->mynick))
3142 fnetsetnick(fn, L"DoldaConnectUser-IN");
3143 /* IN as in Invalid Nick */
3147 static struct dcpeer *newdcpeer(struct socket *sk)
3151 new = smalloc(sizeof(*new));
3152 memset(new, 0, sizeof(*new));
3155 if(confgetint("dc", "dcppemu"))
3166 static void freedcpeer(struct dcpeer *peer)
3169 struct qcommand *qcmd;
3173 if(peer->next != NULL)
3174 peer->next->prev = peer->prev;
3175 if(peer->prev != NULL)
3176 peer->prev->next = peer->next;
3177 if(peer->transfer != NULL)
3179 if(peer->timeout != NULL)
3180 canceltimer(peer->timeout);
3181 if(peer->sk->data == peer)
3182 peer->sk->data = NULL;
3183 peer->sk->readcb = NULL;
3184 peer->sk->writecb = NULL;
3185 peer->sk->errcb = NULL;
3188 if(peer->supports != NULL)
3190 for(i = 0; peer->supports[i] != NULL; i++)
3191 free(peer->supports[i]);
3192 free(peer->supports);
3194 if(peer->inbuf != NULL)
3196 if(peer->key != NULL)
3198 if(peer->wcsname != NULL)
3199 free(peer->wcsname);
3200 if(peer->nativename != NULL)
3201 free(peer->nativename);
3202 if(peer->charset != NULL)
3203 free(peer->charset);
3204 if(peer->fn != NULL)
3205 putfnetnode(peer->fn);
3206 while((qcmd = ulqcmd(&peer->queue)) != NULL)
3212 static void hubconnect(struct fnetnode *fn, struct socket *sk)
3216 sk->readcb = (void (*)(struct socket *, void *))hubread;
3217 sk->errcb = (void (*)(struct socket *, int, void *))huberr;
3218 fn->data = hub = newdchub(fn);
3220 getsock(hub->sk = sk);
3224 static void hubdestroy(struct fnetnode *fn)
3228 struct qcommand *qcmd;
3230 hub = (struct dchub *)fn->data;
3232 while((qcmd = ulqcmd(&hub->queue)) != NULL)
3234 if(hub->supports != NULL)
3236 for(i = 0; hub->supports[i] != NULL; i++)
3237 free(hub->supports[i]);
3238 free(hub->supports);
3240 if(hub->nativename != NULL)
3241 free(hub->nativename);
3242 if(hub->nativenick != NULL)
3243 free(hub->nativenick);
3244 if(hub->charset != NULL)
3246 if(hub->inbuf != NULL)
3251 static void hubkill(struct fnetnode *fn)
3255 hub = (struct dchub *)fn->data;
3259 static struct fnet dcnet =
3262 .connect = hubconnect,
3263 .destroy = hubdestroy,
3265 .setnick = hubsetnick,
3266 .reqconn = hubreqconn,
3267 .sendchat = hubsendchat,
3268 .search = hubsearch,
3271 static void peerread(struct socket *sk, struct dcpeer *peer)
3274 size_t datalen, cnlen;
3275 struct command *cmd;
3277 if(peer->state == PEER_CMD) {
3278 if((peer->queue.size > 50) || (peer->inbufdata > 65536))
3280 } else if(peer->state == PEER_TTHL) {
3284 if((newbuf = sockgetinbuf(sk, &datalen)) == NULL)
3286 sizebuf2(peer->inbuf, peer->inbufdata + datalen, 1);
3287 memcpy(peer->inbuf + peer->inbufdata, newbuf, datalen);
3289 peer->inbufdata += datalen;
3290 if(peer->state == PEER_CMD)
3293 while((peer->inbufdata > 0) && (p = memchr(peer->inbuf, '|', peer->inbufdata)) != NULL)
3296 for(cmd = peercmds; cmd->handler != NULL; cmd++)
3298 cnlen = strlen(cmd->name);
3299 if(!strncmp(peer->inbuf, cmd->name, cnlen) && ((peer->inbuf[cnlen] == ' ') || (peer->inbuf[cnlen] == 0)))
3302 if((cmd->limit == 0) || (peer->queue.size < cmd->limit))
3303 newqcmd(&peer->queue, peer->inbuf);
3304 memmove(peer->inbuf, p, peer->inbufdata -= p - peer->inbuf);
3307 peer->state = PEER_STOP;
3311 } else if(peer->state == PEER_TTHL) {
3316 static void peererror(struct socket *sk, int err, struct dcpeer *peer)
3321 static void peerconnect(struct socket *sk, int err, struct fnetnode *fn)
3323 struct dcpeer *peer;
3332 peer = newdcpeer(sk);
3335 peer->dcppemu = hub->dcppemu;
3336 sk->readcb = (void (*)(struct socket *, void *))peerread;
3337 sk->errcb = (void (*)(struct socket *, int, void *))peererror;
3339 socksettos(sk, confgetint("fnet", "fnptos"));
3340 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
3345 static void peeraccept(struct lport *lp, struct socket *newsk, void *data)
3347 struct dcpeer *peer;
3349 peer = newdcpeer(newsk);
3351 newsk->readcb = (void (*)(struct socket *, void *))peerread;
3352 newsk->errcb = (void (*)(struct socket *, int, void *))peererror;
3354 socksettos(newsk, confgetint("fnet", "fnptos"));
3355 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
3358 static void updatehmlist(void)
3360 int i, lev, ic, ret;
3361 struct sharecache *node;
3362 char *buf, *buf2, numbuf[32];
3363 size_t bufsize, bufdata;
3368 buf = smalloc(bufsize = 65536);
3369 node = shareroot->child;
3374 /* Use DCCHARSET in $Get paths until further researched... */
3375 if((buf2 = icwcstombs(node->name, DCCHARSET)) != NULL)
3377 for(i = 0; i < lev; i++)
3379 bufcat(buf, buf2, strlen(buf2));
3381 if(node->f.b.type == FILE_REG)
3384 sprintf(numbuf, "%ji", (intmax_t)node->size);
3385 bufcat(buf, numbuf, strlen(numbuf));
3392 if((node->child != NULL) && !ic)
3396 } else if(node->next != NULL) {
3399 while(node->next == NULL)
3402 node = node->parent;
3403 if(node == shareroot)
3406 if(node == shareroot)
3411 if(hmlistname != NULL)
3416 hmlistname = sstrdup("/tmp/dc-filelist-hm-XXXXXX");
3417 if((fd = mkstemp(hmlistname)) < 0)
3419 flog(LOG_WARNING, "could not create HM file list tempfile: %s", strerror(errno));
3423 out = fdopen(fd, "w");
3425 * I do not want to implement a good Huffman encoder, and it's not
3426 * like Huffman encoding actually yields any impressive results
3427 * for DC file lists anyway, so I'll just output a bogus
3428 * tree. Implement a good encoder if you want to.
3430 fwrite("HE3\r\0", 1, 5, out);
3431 fwrite(&bufdata, 4, 1, out); /* XXX: Endian unsafe */
3433 fwrite(&ibuf, 2, 1, out);
3435 for(i = 0; i < 256; i++)
3437 fwrite(&i, 1, 1, out);
3438 fwrite(&ibuf, 1, 1, out);
3440 for(i = 0; i < 256; i++)
3441 fwrite(&i, 1, 1, out);
3442 for(buf2 = buf; bufdata > 0;)
3444 if((ret = fwrite(buf2, 1, bufdata, out)) < 0)
3446 flog(LOG_WARNING, "could not write file list: %s", strerror(errno));
3457 static struct xmlent
3464 /* {L'\'', L"""}, Emulate DC++ escaping by omitting this. */
3468 static wchar_t *escapexml(wchar_t *src)
3470 static wchar_t *buf = NULL;;
3473 size_t bufsize, bufdata;
3479 bufsize = bufdata = 0;
3480 for(; *src != L'\0'; src++)
3483 if((c > 0) && (c < 32))
3485 bufcat(buf, L"&#", 2);
3486 ret = swprintf(nbuf, (sizeof(nbuf) / sizeof(*nbuf)), L"%i", c);
3487 bufcat(buf, nbuf, ret);
3488 addtobuf(buf, L';');
3490 for(ent = entities; ent->ent != NULL; ent++)
3494 bufcat(buf, ent->ent, wcslen(ent->ent));
3498 if(ent->ent == NULL)
3499 addtobuf(buf, *src);
3502 addtobuf(buf, L'\0');
3506 static void updatexmllist(void)
3510 char cidbuf[14], *namebuf;
3512 struct sharecache *node;
3514 if(xmllistname != NULL)
3516 unlink(xmllistname);
3519 xmllistname = sstrdup("/tmp/dc-filelist-dcxml-XXXXXX");
3520 if((fd = mkstemp(xmllistname)) < 0)
3522 flog(LOG_WARNING, "could not create XML file list tempfile: %s", strerror(errno));
3527 if((fs = fdopen(fd, "w")) == NULL)
3529 flog(LOG_WARNING, "could not fdopen XML list fd %i: %s", fd, strerror(errno));
3530 unlink(xmllistname);
3536 fprintf(fs, "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>\r\n");
3537 for(i = 0; i < sizeof(cidbuf) - 1; i++)
3538 cidbuf[i] = (rand() % ('Z' - 'A' + 1)) + 'A';
3540 if(confgetint("dc", "dcppemu"))
3541 fprintf(fs, "<FileListing Version=\"1\" CID=\"%s\" Base=\"/\" Generator=\"DC++ 0.674\">\r\n", cidbuf);
3543 fprintf(fs, "<FileListing Version=\"1\" CID=\"%s\" Base=\"/\" Generator=\"%s\">\r\n", cidbuf, "DoldaConnect" VERSION);
3545 node = shareroot->child;
3549 if((namebuf = icswcstombs(escapexml(node->name), "UTF-8", NULL)) != NULL)
3551 for(i = 0; i < lev; i++)
3553 if(node->child != NULL)
3555 fprintf(fs, "<Directory Name=\"%s\">\r\n", namebuf);
3560 fprintf(fs, "<File Name=\"%s\" Size=\"%ji\"", namebuf, (intmax_t)node->size);
3561 if(node->f.b.hastth)
3563 hashbuf = base32encode(node->hashtth, 24);
3564 fprintf(fs, " TTH=\"%.39s\"", hashbuf);
3567 fprintf(fs, "/>\r\n");
3569 while(node->next == NULL)
3571 node = node->parent;
3572 if(node == shareroot)
3577 for(i = 0; i < lev; i++)
3579 fprintf(fs, "</Directory>\r\n");
3582 if(node == shareroot)
3588 if(confgetint("dc", "dcppemu"))
3589 fprintf(fs, "</FileListing>");
3591 fprintf(fs, "</FileListing>\r\n");
3595 static void updatexmlbz2list(void)
3604 if(xmllistname == NULL)
3606 if((in = fopen(xmllistname, "r")) == NULL)
3608 flog(LOG_WARNING, "could not open XML file list for bzipping: %s", strerror(errno));
3611 if(xmlbz2listname != NULL)
3613 unlink(xmlbz2listname);
3614 free(xmlbz2listname);
3616 xmlbz2listname = sstrdup("/tmp/dc-filelist-dcxmlbz2-XXXXXX");
3617 if((fd = mkstemp(xmlbz2listname)) < 0)
3619 flog(LOG_WARNING, "could not create bzipped XML file list tempfile: %s", strerror(errno));
3620 free(xmlbz2listname);
3621 xmlbz2listname = NULL;
3625 if((real = fdopen(fd, "w")) == NULL)
3627 flog(LOG_WARNING, "could not fdopen bzipped XML list fd %i: %s", fd, strerror(errno));
3629 unlink(xmlbz2listname);
3630 free(xmlbz2listname);
3631 xmlbz2listname = NULL;
3635 out = BZ2_bzWriteOpen(&err, real, 9, 0, 0);
3638 flog(LOG_WARNING, "could not open bzip2 stream from XML list");
3640 unlink(xmlbz2listname);
3641 free(xmlbz2listname);
3642 xmlbz2listname = NULL;
3648 bufdata = fread(buf, 1, sizeof(buf), in);
3649 BZ2_bzWrite(&err, out, buf, bufdata);
3652 BZ2_bzWriteClose(&err, out, 0, NULL, NULL);
3656 static void listtimercb(int cancelled, void *uudata)
3658 listwritetimer = NULL;
3663 static void updatelists(int now)
3665 if((hmlistname == NULL) || (xmllistname == NULL) || (xmlbz2listname == NULL))
3669 if(listwritetimer == NULL)
3670 listwritetimer = timercallback(ntime() + confgetint("cli", "hashwritedelay"), listtimercb, NULL);
3673 if(listwritetimer != NULL)
3674 canceltimer(listwritetimer);
3680 static int shareupdate(unsigned long long uusharesize, void *data)
3686 static char *quotestr(char *str)
3690 size_t bufsize, bufdata;
3692 static char *enc = NULL;
3693 size_t encsize, encdata;
3696 bufsize = bufdata = 0;
3697 for(p = (unsigned char *)str; *p; p++)
3700 bufcat(buf, "\\b", 2);
3702 bufcat(buf, "\\t", 2);
3704 bufcat(buf, "\\n", 2);
3706 bufcat(buf, "\\r", 2);
3708 bufcat(buf, "\\\\", 2);
3712 bprintf(buf, "\\x%02x", *p);
3718 if((wbuf = icmbstowcs((char *)buf, DCCHARSET)) != NULL)
3720 enc = icwcstombs(wbuf, NULL);
3725 encsize = encdata = 0;
3726 for(p = buf; *p; p++) {
3730 bprintf(buf, "\\x%x", *p);
3737 static void logunimpl(char *list, char *cmd, char *args)
3741 if((log = fopen("/tmp/dc-unimpl", "a")) == NULL)
3743 flog(LOG_WARNING, "could not open unimpl log: %s", strerror(errno));
3748 fputs(quotestr(cmd), log);
3752 fputs(quotestr(args), log);
3758 static void dispatchcommand(struct qcommand *qcmd, struct command *cmdlist, struct socket *sk, void *data)
3761 struct command *cmd;
3763 if((p = strchr(qcmd->string, ' ')) != NULL)
3765 for(cmd = cmdlist; cmd->handler != NULL; cmd++)
3767 if(!strcmp(cmd->name, qcmd->string))
3770 if(cmd->handler != NULL)
3772 cmd->handler(sk, data, qcmd->string, p);
3773 } else if(confgetint("dc", "logunimpl")) {
3774 if(cmdlist == hubcmds)
3775 logunimpl("hub", qcmd->string, p);
3776 else if(cmdlist == peercmds)
3777 logunimpl("peer", qcmd->string, p);
3779 logunimpl("other?!", qcmd->string, p);
3783 static int run(void)
3785 struct fnetnode *fn, *nextfn;
3787 struct dcpeer *peer, *nextpeer;
3788 struct qcommand *qcmd;
3793 for(fn = fnetnodes; fn != NULL; fn = nextfn)
3796 if(fn->fnet != &dcnet)
3798 if(fn->data == NULL)
3800 hub = (struct dchub *)fn->data;
3801 while((quota > 0) && ((qcmd = ulqcmd(&hub->queue)) != NULL))
3803 if(*qcmd->string == '$')
3805 if((hub->sk != NULL) && (hub->sk->state == SOCK_EST))
3806 dispatchcommand(qcmd, hubcmds, hub->sk, fn);
3807 } else if(*qcmd->string != 0) {
3808 hubrecvchat(hub->sk, fn, NULL, qcmd->string);
3814 if(hub->queue.size < 1000)
3815 hubread(hub->sk, fn);
3820 for(peer = peers; peer != NULL; peer = peer->next)
3822 while(!peer->close && (quota > 0) && ((qcmd = ulqcmd(&peer->queue)) != NULL))
3824 if(peer->timeout != NULL)
3825 canceltimer(peer->timeout);
3826 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
3827 if(*qcmd->string == '$')
3828 dispatchcommand(qcmd, peercmds, peer->sk, peer);
3833 if((peer->queue.size < 50) && (peer->inbufdata < 500000))
3834 peerread(peer->sk, peer);
3838 for(peer = peers; peer != NULL; peer = nextpeer)
3840 nextpeer = peer->next;
3847 static void preinit(int hup)
3854 static int updateudpport(struct configvar *var, void *uudata)
3856 struct sockaddr_in addr;
3857 struct socket *newsock;
3859 memset(&addr, 0, sizeof(addr));
3860 addr.sin_family = AF_INET;
3861 addr.sin_port = htons(var->val.num);
3862 if((newsock = netcsdgram((struct sockaddr *)&addr, sizeof(addr))) == NULL)
3864 flog(LOG_WARNING, "could not create new DC UDP socket, reverting to old: %s", strerror(errno));
3867 newsock->readcb = udpread;
3874 static int updatetcpport(struct configvar *var, void *uudata)
3876 struct sockaddr_in addr;
3877 struct lport *newsock;
3879 memset(&addr, 0, sizeof(addr));
3880 addr.sin_family = AF_INET;
3881 addr.sin_port = htons(var->val.num);
3882 if((newsock = netcslisten(SOCK_STREAM, (struct sockaddr *)&addr, sizeof(addr), peeraccept, NULL)) == NULL)
3883 flog(LOG_INFO, "could not listen to a remote address, going into passive mode");
3885 closelport(tcpsock);
3890 static int init(int hup)
3892 struct sockaddr_in addr;
3896 GCBREG(sharechangecb, shareupdate, NULL);
3900 closelport(tcpsock);
3901 addr.sin_family = AF_INET;
3902 memset(&addr.sin_addr, 0, sizeof(addr.sin_addr));
3903 addr.sin_port = htons(confgetint("dc", "udpport"));
3904 if((udpsock = netcsdgram((struct sockaddr *)&addr, sizeof(addr))) == NULL)
3906 flog(LOG_CRIT, "could not create DC UDP socket: %s", strerror(errno));
3909 udpsock->readcb = udpread;
3910 addr.sin_port = htons(confgetint("dc", "tcpport"));
3911 if((tcpsock = netcslisten(SOCK_STREAM, (struct sockaddr *)&addr, sizeof(addr), peeraccept, NULL)) == NULL)
3912 flog(LOG_INFO, "could not listen to a remote address, going into passive mode");
3913 CBREG(confgetvar("dc", "udpport"), conf_update, updateudpport, NULL, NULL);
3914 CBREG(confgetvar("dc", "tcpport"), conf_update, updatetcpport, NULL, NULL);
3915 CBREG(confgetvar("net", "mode"), conf_update, updatetcpport, NULL, NULL);
3920 static void terminate(void)
3922 if(hmlistname != NULL)
3927 if(xmllistname != NULL)
3929 unlink(xmllistname);
3932 if(xmlbz2listname != NULL)
3934 unlink(xmlbz2listname);
3935 free(xmlbz2listname);
3939 static struct configvar myvars[] =
3941 /** Specifies the share description reported to other DC users. */
3942 {CONF_VAR_STRING, "desc", {.str = L""}},
3943 /** Specifies the speed reported to other DC users. Normal values
3944 * are 28.8Kbps, 33.6Kbps, 56Kbps, Satellite, ISDN, DSL, Cable,
3945 * LAN(T1) or LAN(T3)*/
3946 {CONF_VAR_STRING, "speedstring", {.str = L"LAN(T1)"}},
3947 /** The e-mail address to report to other DC users. */
3948 {CONF_VAR_STRING, "email", {.str = L"spam@spam.org"}},
3949 /** Specifies a specific UDP port to use for DC search results. If
3950 * left unspecified, a port is allocated dynamically. Useful for
3951 * NAT routers (see also the net.visibleipv4 address for those
3953 {CONF_VAR_INT, "udpport", {.num = 0}},
3954 /** Specifies a specific TCP port to use for DC peer
3955 * connections. If left unspecified, a port is allocated
3956 * dynamically. Useful for NAT routers (see also the
3957 * net.visibleipv4 address for those cases). */
3958 {CONF_VAR_INT, "tcpport", {.num = 0}},
3959 /** If set to true, doldacond will do its best to emulate DC++
3960 * (currently v0.674). This should be left off if at all possible,
3961 * since turning it on will violate the rules of most hubs and
3962 * thus give hub owners an actual reason to kick you if it is
3963 * detected. It might be needed for some of the more bone-headed
3964 * hub owners, though. Note that DC++ emulation can also be turned
3965 * on or off for individual hubs, overriding this setting. */
3966 {CONF_VAR_BOOL, "dcppemu", {.num = 0}},
3967 /** Use for debugging. If set to true, doldacond will log all
3968 * unknown commands it receives, and their arguments, to
3969 * /tmp/dc-unimpl. */
3970 {CONF_VAR_BOOL, "logunimpl", {.num = 0}},
3971 /** If set to true, doldacond will hide its support for deflate
3972 * compression of transfers from other clients, so that they will
3973 * not request compressed uploads. Compressed transfers may
3974 * consume a non-trivial amount of CPU time on slower machines. */
3975 {CONF_VAR_BOOL, "hidedeflate", {.num = 0}},
3979 static struct module me =
3988 .terminate = terminate,