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 != ' ')
558 if((*args == ' ') || (*args == 0))
561 addtobuf(retbuf, buf);
563 bufsize = bufdata = 0;
566 } else if(*args == '\\') {
569 addtobuf(buf, *args);
578 addtobuf(retbuf, NULL);
581 } else if((*args == 's') || (*args == ' ')) {
583 } else if(*args == 'n') {
585 } else if(*args == '\\') {
595 addtobuf(retbuf, NULL);
599 /* Macros useful in command handlers */
600 #define skipspace(s) ({if(((s) = strchr((s), ' ')) == NULL) return; else (s)++;})
601 #define qstr(sk, str) sockqueue(sk, str, strlen(str))
602 #define qstrf(sk, strandargs...) \
605 if((__buf__ = sprintf2(strandargs)) != NULL) { \
606 sockqueue(sk, __buf__, strlen(__buf__)); \
611 static char *tr(char *str, char *trans)
615 for(; *trans; trans += 2)
617 for(p = strchr(str, trans[0]); p != NULL; p = strchr(p, trans[0]))
623 static char *getadcid(struct dcpeer *peer)
630 if(!wcscmp(peer->transfer->path, L"files.xml") || !wcscmp(peer->transfer->path, L"files.xml.bz2") || !wcscmp(peer->transfer->path, L"MyList.DcLst"))
632 if(!isfilelist && (peer->transfer->hash != NULL) && isdchash(peer->transfer->hash) && supports(peer, "tthf"))
634 buf = base32encode(peer->transfer->hash->buf, 24);
635 ret = sprintf2("TTH/%.39s", buf);
638 ret = path2adc(peer->transfer->path);
644 static int trresumecb(struct transfer *transfer, wchar_t *cmd, wchar_t *arg, struct dcpeer *peer)
646 if(!wcscmp(cmd, L"resume"))
650 flog(LOG_WARNING, "filter returned no position for \"resume\" on transfer %i", transfer->id);
653 transfer->curpos = wcstoll(arg, NULL, 10);
662 static void sendmynick(struct dcpeer *peer)
668 qstrf(peer->sk, "$MyNick %s|", icswcstombs(confgetstr("cli", "defnick"), peer->charset, "DoldaConnectUser-IN"));
670 qstrf(peer->sk, "$MyNick %s|", icswcstombs(fn->mynick, peer->charset, "DoldaConnectUser-IN"));
673 static void sendpeerlock(struct dcpeer *peer)
676 qstrf(peer->sk, "$Lock EXTENDEDPROTOCOLABCABCABCABCABCABC Pk=DCPLUSPLUS0.674ABCABC|");
678 qstrf(peer->sk, "$Lock EXTENDEDPROTOCOLABCABCABCABCABCABC Pk=DOLDA%sABCABCABC|", VERSION);
681 static void sendsupports(struct dcpeer *peer)
684 qstr(peer->sk, "$Supports MiniSlots XmlBZList ADCGet TTHL TTHF GetZBlock ZLIG |");
686 qstr(peer->sk, "$Supports MiniSlots XmlBZList ADCGet TTHL TTHF");
687 if(!confgetint("dc", "hidedeflate"))
688 qstr(peer->sk, " GetZBlock ZLIG");
693 static void requestfile(struct dcpeer *peer)
697 if(peer->transfer->size == -1)
699 /* Use DCCHARSET for $Get paths until further researched... */
700 if((buf = path2nmdc(peer->transfer->path, DCCHARSET)) == NULL)
702 transferseterror(peer->transfer, TRNSE_NOTFOUND);
706 /* The transfer will be restarted later from
707 * cmd_filelength when it detects that the sizes
709 qstrf(peer->sk, "$Get %s$1|", buf);
713 if((peer->transfer->hash == NULL) && !peer->notthl)
715 if(supports(peer, "adcget") && supports(peer, "tthl"))
717 qstr(peer->sk, "$ADCGET");
718 sendadc(peer->sk, "tthl");
719 if((buf = getadcid(peer)) == NULL)
721 transferseterror(peer->transfer, TRNSE_NOTFOUND);
725 sendadc(peer->sk, buf);
727 sendadc(peer->sk, "0");
728 sendadc(peer->sk, "-1");
730 peer->fetchingtthl = 1;
736 if(forkfilter(peer->transfer))
738 flog(LOG_WARNING, "could not fork filter for transfer %i: %s", peer->transfer->id, strerror(errno));
744 if(supports(peer, "adcget"))
746 qstr(peer->sk, "$ADCGET");
747 sendadc(peer->sk, "file");
748 if((buf = getadcid(peer)) == NULL)
750 transferseterror(peer->transfer, TRNSE_NOTFOUND);
754 sendadc(peer->sk, buf);
756 sendadcf(peer->sk, "%ji", (intmax_t)peer->transfer->curpos);
757 sendadcf(peer->sk, "%ji", (intmax_t)(peer->transfer->size - peer->transfer->curpos));
759 } else if(supports(peer, "xmlbzlist")) {
760 if((buf = path2nmdc(peer->transfer->path, "UTF-8")) == NULL)
762 transferseterror(peer->transfer, TRNSE_NOTFOUND);
766 qstrf(peer->sk, "$UGetBlock %ji %ji %s|", (intmax_t)peer->transfer->curpos, (intmax_t)(peer->transfer->size - peer->transfer->curpos), buf);
769 /* Use DCCHARSET for $Get paths until further researched... */
770 if((buf = path2nmdc(peer->transfer->path, DCCHARSET)) == NULL)
772 transferseterror(peer->transfer, TRNSE_NOTFOUND);
776 qstrf(peer->sk, "$Get %s$%ji|", buf, (intmax_t)peer->transfer->curpos + 1);
781 static void sendmyinfo(struct socket *sk, struct fnetnode *fn)
785 struct fnetnode *cfn;
789 qstrf(sk, "$MyINFO $ALL %s ", hub->nativenick);
790 buf = tr(icswcstombs(confgetstr("dc", "desc"), hub->charset, "Charset_conv_failure"), "$_|_");
791 qstrf(sk, "%s", buf);
793 for(cfn = fnetnodes; cfn != NULL; cfn = cfn->next)
795 if((cfn->state == FNN_EST) || (cfn->state == FNN_HS))
797 if(cfn->regstatus == FNNS_OP)
799 else if(cfn->regstatus == FNNS_REG)
805 qstrf(sk, "<%s V:%s,M:%c,H:%i/%i/%i,S:%i>",
806 (hub->dcppemu)?"++":"Dolda",
807 (hub->dcppemu)?"0.674":VERSION,
808 (tcpsock == NULL)?'P':'A',
810 confgetint("transfer", "slots")
813 buf = tr(icswcstombs(confgetstr("dc", "speedstring"), hub->charset, "Charset_conv_failure"), "$_|_");
814 qstrf(sk, "%s\x01$", buf);
815 buf = tr(icswcstombs(confgetstr("dc", "email"), hub->charset, "Charset_conv_failure"), "$_|_");
816 qstrf(sk, "%s$", buf);
817 qstrf(sk, "%llu$|", sharesize);
820 static void hubhandleaction(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
825 if(!strcmp(cmd, "$Lock"))
827 qstrf(sk, "$ValidateNick %s|", hub->nativenick);
828 } else if(!strcmp(cmd, "$Hello")) {
829 if(fn->state == FNN_HS)
831 qstrf(sk, "$Version 1,0091|");
832 qstrf(sk, "$GetNickList|");
834 fnetsetstate(fn, FNN_EST);
836 qstrf(sk, "$GetINFO %s %s|", args, hub->nativenick);
841 static void cmd_lock(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
848 if(!strncmp(args, "EXTENDEDPROTOCOL", 16))
850 if((p = strchr(args, ' ')) != NULL)
855 qstrf(sk, "$Supports UserCommand NoGetINFO NoHello UserIP2 TTHSearch GetZBlock |");
857 qstrf(sk, "$Supports UserCommand NoGetINFO NoHello UserIP2 TTHSearch");
858 if(!confgetint("dc", "hidedeflate"))
859 qstr(sk, " GetZBlock");
863 key = dcmakekey(args);
864 qstrf(sk, "$Key %s|", key);
866 hubhandleaction(sk, fn, cmd, args);
869 static void cmd_hubname(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
875 if(hub->nativename != NULL)
876 free(hub->nativename);
877 hub->nativename = sstrdup(args);
878 buf = icmbstowcs(args, hub->charset);
879 fnetsetname(fn, (buf == NULL)?L"Hubname conv error":buf);
882 hubhandleaction(sk, fn, cmd, args);
885 static void cmd_hello(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
891 if((nick = icmbstowcs(args, hub->charset)) == NULL)
893 if(strcmp(args, hub->nativenick) && (fnetfindpeer(fn, nick) == NULL))
894 fnetaddpeer(fn, nick, nick);
896 hubhandleaction(sk, fn, cmd, args);
899 static void cmd_quit(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
902 struct fnetpeer *peer;
906 if((nick = icmbstowcs(args, hub->charset)) == NULL)
908 if((peer = fnetfindpeer(fn, nick)) != NULL)
911 hubhandleaction(sk, fn, cmd, args);
914 static void cmd_nicklist(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
919 struct fnetpeer *peer;
922 for(peer = btreeiter(fn->peers); peer != NULL; peer = btreeiter(NULL))
923 peer->flags.b.delete = 1;
924 while((p = strstr(args, "$$")) != NULL)
927 if((buf = icmbstowcs(args, hub->charset)) != NULL)
929 if((peer = fnetfindpeer(fn, buf)) == NULL)
930 peer = fnetaddpeer(fn, buf, buf);
932 peer->flags.b.delete = 0;
934 qstrf(sk, "$GetINFO %s %s|", args, hub->nativenick);
939 hubhandleaction(sk, fn, cmd, args);
942 static void cmd_oplist(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
947 struct fnetpeer *peer;
950 for(peer = btreeiter(fn->peers); peer != NULL; peer = btreeiter(NULL))
951 peer->flags.b.op = 0;
952 while((p = strstr(args, "$$")) != NULL)
955 if((buf = icmbstowcs(args, hub->charset)) != NULL)
957 if((peer = fnetfindpeer(fn, buf)) != NULL)
958 peer->flags.b.op = 1;
963 hubhandleaction(sk, fn, cmd, args);
966 static void cmd_myinfo(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
969 wchar_t *buf, *wp, *wp2;
971 struct fnetpeer *peer;
976 if(strncmp(p, "$ALL ", 5))
979 if((p2 = strchr(p, ' ')) == NULL)
982 if((buf = icmbstowcs(p, hub->charset)) == NULL)
984 if((peer = fnetfindpeer(fn, buf)) == NULL)
985 peer = fnetaddpeer(fn, buf, buf);
988 if((p2 = strstr(p, "$ $")) == NULL)
991 if((buf = icmbstowcs(p, hub->charset)) == NULL)
993 if((wcslen(buf) > 0) && (buf[wcslen(buf) - 1] == L'>') && ((wp = wcsrchr(buf, L'<')) != NULL))
995 buf[wcslen(buf) - 1] = L'\0';
997 if((wp2 = wcschr(wp, L' ')) != NULL)
1000 fnetpeersetstr(peer, L"dc-client", wp);
1004 if((wp2 = wcschr(wp, L',')) != NULL)
1008 swprintf(abuf, 10, L"dc-tag-%lc", wp[0]);
1009 fnetpeersetstr(peer, abuf, wp + 2);
1011 } while(wp2 != NULL);
1014 fnetpeersetstr(peer, L"descr", buf);
1017 if((p2 = strchr(p, '$')) == NULL)
1020 if((buf = icmbstowcs(p, hub->charset)) == NULL)
1022 fnetpeersetstr(peer, L"dc-speed", buf);
1025 if((p2 = strchr(p, '$')) == NULL)
1028 if((buf = icmbstowcs(p, hub->charset)) == NULL)
1030 fnetpeersetstr(peer, L"email", buf);
1035 fnetpeersetlnum(peer, L"share", strtoll(p, NULL, 10));
1036 hubhandleaction(sk, fn, cmd, args);
1039 /* I do not implement the fully in that I do not disconnect from the
1040 * old hub. I do this since I believe that if the hub owner really
1041 * wants to get rid of us, then it is his responsibility to disconnect
1043 static void cmd_forcemove(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1046 struct fnetnode *newfn;
1050 if(strchr(args, ':') == NULL)
1052 args = strcpy(smalloc(strlen(args) + 5), args);
1053 strcat(args, ":411");
1058 if((newfn = fnetinitconnect(L"dc", fn->owner, args, NULL)) != NULL)
1060 linkfnetnode(newfn);
1063 hubhandleaction(sk, fn, cmd, args);
1068 static char *getdcpath(struct sharecache *node, size_t *retlen, char *charset)
1073 if(node->parent == NULL)
1075 if(node->parent == shareroot)
1077 if((buf = icwcstombs(node->name, charset)) == NULL)
1080 *retlen = strlen(buf);
1083 if((buf2 = icwcstombs(node->name, charset)) == NULL)
1085 if((buf = getdcpath(node->parent, &len, charset)) == NULL)
1090 len2 = strlen(buf2);
1091 buf = srealloc(buf, len + 1 + len2 + 1);
1093 strcpy(buf + len, buf2);
1094 buf[len + len2] = 0;
1097 *retlen = len + len2;
1103 * This is the main share searching function for Direct Connect
1104 * peers. Feel free to optimize it if you feel the need for it. I
1105 * haven't ever seen it take any noticable CPU time anyway, so I
1106 * haven't felt that need.
1108 * It may feel dubious to just return the directory when all terms are
1109 * satisfied rather than all the files in it, but it really benefits
1110 * everyone: Less cycles used for us, less UDP squelching for active
1111 * searchers, and less bandwidth waste for hubs when serving passive
1114 static void cmd_search(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1119 char *prefix, *infix, *postfix, *buf, *buf2;
1121 struct sockaddr_in addr;
1122 struct sharecache *node;
1123 int minsize, maxsize;
1126 int termnum, satisfied, skipcheck;
1127 int level, tersat[32];
1128 wchar_t *terms[32], *lname;
1132 if((p = strchr(args, ' ')) == NULL)
1136 memset(terms, 0, sizeof(terms));
1137 prefix = infix = postfix = NULL;
1141 if(!strncmp(args, "Hub:", 4))
1143 if(!strcmp(cmd, "$MultiSearch"))
1145 if(!strcmp(args + 4, hub->nativenick))
1147 prefix = sprintf2("$SR %s ", hub->nativenick);
1148 infix = sprintf2(" %i/%i\005", slotsleft(), confgetint("transfer", "slots"));
1149 postfix = sprintf2(" (%s)\005%s|", formatsockpeer(hub->sk), args + 4);
1153 if((p2 = strchr(args, ':')) == NULL)
1156 addr.sin_family = AF_INET;
1157 if(!inet_aton(args, &addr.sin_addr))
1159 addr.sin_port = htons(atoi(p2));
1160 prefix = sprintf2("$SR %s ", hub->nativenick);
1161 infix = sprintf2(" %i/%i\005", slotsleft(), confgetint("transfer", "slots"));
1162 postfix = sprintf2(" (%s)|", formatsockpeer(hub->sk));
1163 dsk = netdgramconn(udpsock, (struct sockaddr *)&addr, sizeof(addr));
1166 minsize = maxsize = -1;
1175 if((*(p++) == 'T') && (minsize == 0))
1182 if((p2 = strchr(p, '?')) == NULL)
1197 if((*p2 == 0) || (*p2 == '$'))
1205 if(!dotth && !strncmp(p, "TTH:", 4))
1208 if(((buf = base32decode(p + 4, &buflen)) == NULL) || (buflen != 24))
1213 memcpy(hashtth, buf, 24);
1216 if((terms[termnum] = icmbstowcs(p, hub->charset)) != NULL) {
1217 wcslower(terms[termnum]);
1229 node = shareroot->child;
1231 for(i = 0; i < termnum; i++)
1237 if(node->f.b.type == FILE_REG)
1239 if((minsize >= 0) && (node->size < minsize))
1241 if((maxsize >= 0) && (node->size > maxsize))
1244 if(!skipcheck && dotth)
1246 if((node->f.b.type != FILE_REG) || (node->f.b.hastth && memcmp(hashtth, node->hashtth, 24)))
1251 lname = wcslower(swcsdup(node->name));
1252 for(i = 0; i < termnum; i++)
1256 if(wcsstr(lname, terms[i]))
1260 } else if(node->child == NULL) {
1266 if(!skipcheck && (satisfied == termnum))
1268 /* Use DCCHARSET in $Get paths until further researched... */
1269 if((buf = getdcpath(node, NULL, DCCHARSET)) != NULL)
1271 if(node->f.b.hastth)
1273 buf2 = base32encode(node->hashtth, 24);
1274 qstrf(dsk, "%s%s\005%ji%sTTH:%.39s%s", prefix, buf, (intmax_t)node->size, infix, buf2, postfix);
1277 qstrf(dsk, "%s%s\005%ji%s%s%s", prefix, buf, (intmax_t)node->size, infix, hub->nativename, postfix);
1282 if((!skipcheck && (satisfied == termnum)) || (node->child == NULL))
1284 while(node->next == NULL)
1286 if((node = node->parent) == shareroot)
1290 if(node == shareroot)
1292 for(i = 0; i < termnum; i++)
1294 if(tersat[i] >= level)
1307 hubhandleaction(sk, fn, cmd, args);
1318 for(i = 0; (i < 32) && (terms[i] != NULL); i++)
1322 static void cmd_connecttome(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1326 struct sockaddr_in addr;
1329 if((p = strchr(args, ' ')) == NULL)
1332 if(strcmp(args, hub->nativenick))
1334 addr.sin_family = AF_INET;
1336 if((p = strchr(args, ':')) == NULL)
1339 addr.sin_port = htons(atoi(p));
1340 if(!inet_aton(args, &addr.sin_addr))
1342 putsock(netcsconn((struct sockaddr *)&addr, sizeof(addr), (void (*)(struct socket *, int, void *))peerconnect, fn));
1344 hubhandleaction(sk, fn, cmd, args);
1347 static void sendctm(struct socket *sk, char *nick)
1349 struct sockaddr *addr;
1354 if(lstgetremotename2(tcpsock, sk, &addr, &addrlen) < 0)
1356 if(addr->sa_family == AF_INET)
1357 qstrf(sk, "$ConnectToMe %s %s|", nick, formataddress(addr, addrlen));
1359 flog(LOG_WARNING, "Direct Connect TCP socket is suddenly not AF_INET, but %i", addr->sa_family);
1363 static void cmd_revconnecttome(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1369 if((p = strchr(args, ' ')) == NULL)
1372 if(strcmp(p, hub->nativenick))
1375 expectpeer(args, fn);
1376 hubhandleaction(sk, fn, cmd, args);
1379 static void cmd_getnetinfo(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1382 struct fnetnode *node;
1387 for(node = fnetnodes; node != NULL; node = node->next)
1389 if(node->state == FNN_EST)
1392 qstrf(sk, "$NetInfo %i$%i$%c$0|", confgetint("transfer", "slots"), numhubs, (tcpsock == NULL)?'P':'A');
1393 hubhandleaction(sk, fn, cmd, args);
1396 static void cmd_to(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1403 if((p2 = strchr(p, ' ')) == NULL)
1407 if((p2 = strchr(p, ' ')) == NULL)
1410 if(strcmp(p, "From:"))
1413 if((p2 = strstr(p, " $")) == NULL)
1417 hubrecvchat(hub->sk, fn, p, p2);
1418 hubhandleaction(sk, fn, cmd, args);
1421 static void cmd_sr(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1425 char *nick, *filename, *hubname;
1430 wchar_t *wnick, *wfile;
1434 if((p2 = strchr(p, ' ')) == NULL)
1439 if((p2 = strchr(p, 5)) == NULL)
1443 if((p2 = strchr(p, ' ')) == NULL)
1446 size = strtoll(p, NULL, 10);
1448 if((p2 = strchr(p, '/')) == NULL)
1453 if((p2 = strchr(p, 5)) == NULL)
1457 if((p2 = strstr(p, " (")) == NULL)
1460 if((wnick = icmbstowcs(nick, hub->charset)) == NULL)
1462 /* Use DCCHARSET in $Get paths until further researched... */
1463 if((wfile = nmdc2path(filename, DCCHARSET)) == NULL)
1468 sr = newsrchres(&dcnet, wfile, wnick);
1469 if(sr->peernick != NULL)
1471 sr->peernick = swcsdup(wnick);
1476 if(!strncmp(hubname, "TTH:", 4))
1478 if((buf = base32decode(hubname + 4, &buflen)) != NULL)
1481 sr->hash = newhash(L"TTH", 24, buf);
1485 getfnetnode(sr->fn = fn);
1488 hubhandleaction(sk, fn, cmd, args);
1491 static void cmd_usercommand(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1493 /* Do nothing for now. */
1496 static void cmd_getpass(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1503 pw = wpfind(fn->args, L"password");
1504 if((pw == NULL) || ((mbspw = icwcstombs(pw, hub->charset)) == NULL))
1509 qstrf(sk, "$MyPass %s|", mbspw);
1511 fn->regstatus = FNNS_REG;
1512 hubhandleaction(sk, fn, cmd, args);
1515 static void cmd_logedin(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1520 fn->regstatus = FNNS_OP;
1521 hubhandleaction(sk, fn, cmd, args);
1524 static void cmd_hubsupports(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1530 size_t arrsize, arrdata;
1533 if(hub->supports != NULL)
1535 for(i = 0; hub->supports[i] != NULL; i++)
1536 free(hub->supports[i]);
1537 free(hub->supports);
1540 arrsize = arrdata = 0;
1544 if((p2 = strchr(p, ' ')) != NULL)
1548 addtobuf(arr, sstrdup(p));
1549 } while((p = p2) != NULL);
1550 addtobuf(arr, NULL);
1551 hub->supports = arr;
1554 static void cmd_mynick(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1556 struct dcexppeer *expect;
1559 if(peer->nativename != NULL)
1560 free(peer->nativename);
1561 peer->nativename = sstrdup(args);
1562 if(peer->wcsname != NULL)
1563 free(peer->wcsname);
1564 if((peer->wcsname = icmbstowcs(peer->nativename, peer->charset)) == NULL)
1571 for(expect = expected; expect != NULL; expect = expect->next)
1573 if(!strcmp(expect->nick, args))
1580 hub = expect->fn->data;
1581 peer->fn = expect->fn;
1582 getfnetnode(peer->fn);
1583 peer->dcppemu = hub->dcppemu;
1584 freeexppeer(expect);
1589 static void peerattach(struct dcpeer *peer, struct transfer *transfer)
1591 peer->transfer = transfer;
1592 CBREG(peer->transfer, trans_filterout, (int (*)(struct transfer *, wchar_t *, wchar_t *, void *))trresumecb, NULL, peer);
1593 CBREG(peer->transfer, trans_destroy, (int (*)(struct transfer *, void *))trdestroycb, NULL, peer);
1596 static void cmd_direction(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1600 struct transfer *transfer;
1602 if((p = strchr(args, ' ')) == NULL)
1605 if(!strcmp(args, "Upload"))
1607 if(!strcmp(args, "Download"))
1611 if((peer->transfer == NULL) || (mydir != peer->direction))
1616 if(peer->direction == TRNSD_DOWN)
1619 if(peer->wcsname == NULL)
1624 peer->direction = mydir;
1625 if(peer->direction == TRNSD_UP)
1627 if(confgetint("transfer", "ulquota") && hasupload(&dcnet, peer->wcsname))
1632 transfer = newupload(peer->fn, &dcnet, peer->wcsname, (peer->trpipe = mktrpipe(peer))->back);
1634 if((transfer = finddownload(peer->wcsname)) == NULL)
1639 transferattach(transfer, (peer->trpipe = mktrpipe(peer))->back);
1640 transfersetstate(transfer, TRNS_HS);
1642 transfersetnick(transfer, peer->wcsname);
1643 peerattach(peer, transfer);
1646 qstrf(sk, "$Direction %s %i|", (peer->direction == TRNSD_UP)?"Upload":"Download", rand() % 10000);
1647 if(peer->key != NULL)
1648 qstrf(sk, "$Key %s|", peer->key);
1649 if(peer->direction == TRNSD_DOWN)
1654 static void cmd_peerlock(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1657 struct transfer *transfer;
1659 if((p = strchr(args, ' ')) == NULL)
1662 if(!strncmp(args, "EXTENDEDPROTOCOL", 16))
1664 key = dcmakekey(args);
1667 if(peer->wcsname == NULL)
1676 if((transfer = finddownload(peer->wcsname)) == NULL)
1678 if(confgetint("transfer", "ulquota") && hasupload(&dcnet, peer->wcsname))
1683 peer->direction = TRNSD_UP;
1684 transfer = newupload(peer->fn, &dcnet, peer->wcsname, (peer->trpipe = mktrpipe(peer))->back);
1686 peer->direction = TRNSD_DOWN;
1687 transferattach(transfer, (peer->trpipe = mktrpipe(peer))->back);
1688 transfersetstate(transfer, TRNS_HS);
1690 transfersetnick(transfer, peer->wcsname);
1691 peerattach(peer, transfer);
1692 qstrf(sk, "$Direction %s %i|", (peer->direction == TRNSD_UP)?"Upload":"Download", rand() % 10000);
1693 qstrf(sk, "$Key %s|", key);
1696 if(peer->key != NULL)
1702 static void cmd_key(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1707 static void startdl(struct dcpeer *peer)
1709 if(peer->timeout != NULL)
1710 canceltimer(peer->timeout);
1711 peer->state = PEER_TRNS;
1712 transferstartdl(peer->transfer, peer->sk);
1713 peer->sk->readcb = (void (*)(struct socket *, void *))transread;
1714 peer->sk->errcb = (void (*)(struct socket *, int, void *))transerr;
1717 static void startul(struct dcpeer *peer)
1719 if(peer->timeout != NULL)
1720 canceltimer(peer->timeout);
1721 peer->state = PEER_TRNS;
1722 transferstartul(peer->transfer, peer->sk);
1723 peer->sk->writecb = (void (*)(struct socket *, void *))transwrite;
1724 transwrite(peer->sk, peer);
1727 static void cmd_filelength(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1730 struct transfer *transfer;
1732 if(peer->transfer == NULL)
1737 size = strtoll(args, NULL, 10);
1738 if(peer->transfer->size != size)
1740 transfersetsize(peer->transfer, size);
1741 transfer = peer->transfer;
1743 resettransfer(transfer);
1744 trytransferbypeer(transfer->fnet, transfer->peerid);
1748 qstr(peer->sk, "$Send|");
1751 static void cmd_error(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1753 if(peer->fetchingtthl)
1755 peer->fetchingtthl = 0;
1760 if((peer->transfer != NULL) && (peer->transfer->dir == TRNSD_DOWN))
1762 transferseterror(peer->transfer, TRNSE_NOTFOUND);
1763 resettransfer(peer->transfer);
1769 static void cmd_maxedout(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1771 if((peer->transfer != NULL) && (peer->transfer->dir == TRNSD_DOWN))
1773 transferseterror(peer->transfer, TRNSE_NOSLOTS);
1774 resettransfer(peer->transfer);
1787 {"MyList.DcLst", &hmlistname, updatehmlist},
1788 {"files.xml", &xmllistname, updatexmllist},
1789 {"files.xml.bz2", &xmlbz2listname, updatexmlbz2list},
1793 static int openfilelist(char *name)
1798 for(i = 0; lists[i].name != NULL; i++)
1800 if(!strcmp(name, lists[i].name))
1804 if(lists[i].name == NULL)
1807 if((*lists[i].file == NULL) || ((fd = open(*lists[i].file, O_RDONLY)) < 0))
1809 if((fd < 0) && ((*lists[i].file == NULL) || ((fd = open(*lists[i].file, O_RDONLY)) < 0)))
1812 flog(LOG_ERR, "could not open filelist tempfile: %s", strerror(errno));
1819 static struct sharecache *findbytth(char *tth32)
1823 struct sharecache *node;
1825 if((buf = base32decode(tth32, &buflen)) == NULL)
1832 for(node = shareroot->child; node != NULL; node = nextscnode(node))
1834 if(node->f.b.hastth && !memcmp(node->hashtth, buf, 24))
1841 static struct sharecache *resdcpath(char *path, char *charset, char sep)
1843 struct sharecache *node;
1850 if((p2 = strchr(p, sep)) != NULL)
1852 if((node = findcache(node, icsmbstowcs(p, charset, L""))) == NULL)
1859 static void cmd_get(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1864 struct sharecache *node;
1865 struct socket *lesk;
1869 if(peer->transfer == NULL)
1874 if((p = strchr(args, '$')) == NULL)
1880 if((offset = (strtoll(p, NULL, 10) - 1)) < 0)
1885 if(((fd = openfilelist(args)) < 0) && (errno != 0))
1887 qstr(sk, "$Error Could not send file list|");
1890 } else if(fd >= 0) {
1891 if((buf2 = nmdc2path(args, DCCHARSET)) != NULL) {
1892 transfersetpath(peer->transfer, buf2);
1895 peer->transfer->flags.b.minislot = 1;
1899 /* Use DCCHARSET in $Get paths until further researched... */
1900 if((node = resdcpath(args, DCCHARSET, '\\')) == NULL)
1902 qstrf(sk, "$Error File not in share|");
1906 if((fd = opensharecache(node)) < 0)
1908 qstrf(sk, "$Error %s|", strerror(errno));
1912 buf = getfspath(node);
1913 if((buf2 = icsmbstowcs(buf, NULL, NULL)) == NULL)
1914 flog(LOG_WARNING, "could not convert native path into a wcs (%s): %s", buf, strerror(errno));
1916 transfersetpath(peer->transfer, buf2);
1919 if(fstat(fd, &sb) < 0)
1922 flog(LOG_WARNING, "could not stat file %ls: %s", node->name, strerror(errno));
1923 qstrf(sk, "$Error|");
1927 if(sb.st_size < 65536)
1928 peer->transfer->flags.b.minislot = 1;
1929 if(!peer->transfer->flags.b.minislot && (slotsleft() < 1)) {
1931 qstr(sk, "$MaxedOut|");
1935 if((offset != 0) && (lseek(fd, offset, SEEK_SET) < 0))
1938 qstrf(sk, "$Error Offset out of range|");
1942 lesk = wrapsock(fd);
1943 transferprepul(peer->transfer, sb.st_size, offset, -1, lesk);
1945 qstrf(sk, "$FileLength %ji|", (intmax_t)peer->transfer->size);
1948 static void cmd_send(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1950 if(peer->transfer == NULL)
1955 if(peer->transfer->localend == NULL)
1964 static void cmd_supports(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1969 size_t arrsize, arrdata;
1971 if(peer->supports != NULL)
1973 for(i = 0; peer->supports[i] != NULL; i++)
1974 free(peer->supports[i]);
1975 free(peer->supports);
1978 arrsize = arrdata = 0;
1982 if((p2 = strchr(p, ' ')) != NULL)
1986 addtobuf(arr, sstrdup(p));
1987 } while((p = p2) != NULL);
1988 addtobuf(arr, NULL);
1989 peer->supports = arr;
1992 static void cmd_getblock(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1996 off_t start, numbytes;
1997 char *charset, *buf;
1999 struct sharecache *node;
2001 struct socket *lesk;
2003 if(peer->transfer == NULL)
2009 if((p2 = strchr(p, ' ')) == NULL)
2015 start = strtoll(p, NULL, 10);
2017 if((p2 = strchr(p, ' ')) == NULL)
2023 numbytes = strtoll(p, NULL, 10);
2025 if(!strcmp(cmd, "$UGetBlock") || !strcmp(cmd, "$UGetZBlock"))
2028 /* Use DCCHARSET in $Get paths until further researched... */
2029 charset = DCCHARSET;
2030 if(!strcmp(cmd, "$GetZBlock") || !strcmp(cmd, "$UGetZBlock"))
2031 initcompress(peer, CPRS_ZLIB);
2032 if(((fd = openfilelist(p)) < 0) && (errno != 0))
2034 qstr(sk, "$Error Could not send file list|");
2036 } else if(fd >= 0) {
2037 if((buf2 = nmdc2path(args, charset)) != NULL) {
2038 transfersetpath(peer->transfer, buf2);
2041 peer->transfer->flags.b.minislot = 1;
2045 if((node = resdcpath(p, charset, '\\')) == NULL)
2047 qstr(sk, "$Error File not in cache|");
2050 if((fd = opensharecache(node)) < 0)
2052 qstrf(sk, "$Error %s|", strerror(errno));
2055 buf = getfspath(node);
2056 if((buf2 = icsmbstowcs(buf, NULL, NULL)) == NULL)
2057 flog(LOG_WARNING, "could not convert native path into a wcs (%s): %s", buf, strerror(errno));
2059 transfersetpath(peer->transfer, buf2);
2062 if(fstat(fd, &sb) < 0)
2065 flog(LOG_WARNING, "could not stat file %ls: %s", node->name, strerror(errno));
2066 qstr(sk, "$Error|");
2069 if(sb.st_size < 65536)
2070 peer->transfer->flags.b.minislot = 1;
2071 if(!peer->transfer->flags.b.minislot && (slotsleft() < 1)) {
2073 qstr(sk, "$MaxedOut|");
2076 if((start != 0) && ((start >= sb.st_size) || (lseek(fd, start, SEEK_SET) < 0)))
2079 qstr(sk, "$Error Offset out of range|");
2082 if((numbytes < 0) || (start + numbytes > sb.st_size))
2083 numbytes = sb.st_size - start;
2084 lesk = wrapsock(fd);
2085 transferprepul(peer->transfer, sb.st_size, start, start + numbytes, lesk);
2087 qstrf(sk, "$Sending %ji|", (intmax_t)numbytes);
2091 static void cmd_adcget(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2095 off_t start, numbytes;
2096 struct sharecache *node;
2098 struct socket *lesk;
2102 if(peer->transfer == NULL)
2107 if((argv = parseadc(args)) == NULL)
2112 if(parrlen(argv) < 4)
2117 start = strtoll(argv[2], NULL, 10);
2118 numbytes = strtoll(argv[3], NULL, 10);
2121 if(((fd = openfilelist(argv[1])) < 0) && (errno != 0))
2123 qstr(sk, "$Error Could not send file list|");
2125 } else if(fd >= 0) {
2126 if((wbuf = adc2path(argv[1])) != NULL)
2127 transfersetpath(peer->transfer, wbuf);
2129 peer->transfer->flags.b.minislot = 1;
2133 if(!strncmp(argv[1], "TTH/", 4))
2135 if((node = findbytth(argv[1] + 4)) == NULL)
2137 qstr(sk, "$Error File not in cache|");
2141 if((node = resdcpath((argv[1][0] == '/')?(argv[1] + 1):(argv[1]), "UTF-8", '/')) == NULL)
2143 qstr(sk, "$Error File not in cache|");
2147 if((fd = opensharecache(node)) < 0)
2149 qstrf(sk, "$Error %s|", strerror(errno));
2152 buf = getfspath(node);
2153 if((wbuf = icsmbstowcs(buf, NULL, NULL)) == NULL)
2154 flog(LOG_WARNING, "could not convert native path into a wcs (%s): %s", buf, strerror(errno));
2156 transfersetpath(peer->transfer, wbuf);
2159 if(!strcmp(argv[0], "file"))
2161 for(i = 4; argv[i] != NULL; i++)
2163 if(!strcmp(argv[i], "ZL1"))
2164 initcompress(peer, CPRS_ZLIB);
2166 if(fstat(fd, &sb) < 0)
2168 flog(LOG_WARNING, "could not stat file %ls: %s", node->name, strerror(errno));
2169 qstr(sk, "$Error|");
2172 if(sb.st_size < 65536)
2173 peer->transfer->flags.b.minislot = 1;
2174 if(!peer->transfer->flags.b.minislot && (slotsleft() < 1)) {
2175 qstr(sk, "$MaxedOut|");
2178 if((start != 0) && ((start >= sb.st_size) || (lseek(fd, start, SEEK_SET) < 0)))
2180 qstr(sk, "$Error Offset out of range|");
2183 if((numbytes < 0) || (start + numbytes > sb.st_size))
2184 numbytes = sb.st_size - start;
2185 lesk = wrapsock(fd);
2186 transferprepul(peer->transfer, sb.st_size, start, start + numbytes, lesk);
2189 qstr(sk, "$ADCSND");
2190 sendadc(sk, "file");
2191 sendadc(sk, argv[1]);
2192 sendadcf(sk, "%ji", (intmax_t)start);
2193 sendadcf(sk, "%ji", (intmax_t)numbytes);
2194 if(peer->compress == CPRS_ZLIB)
2198 } else if(!strcmp(argv[0], "tthl")) {
2200 * XXX: Implement full TTHL support.
2202 * In the meantime, this is better than nothing, since it at
2203 * least allows fetching of the TTH root if it isn't already
2208 qstr(sk, "$Error no TTHL data for virtual files|");
2211 qstr(sk, "$ADCSND");
2212 sendadc(sk, "tthl");
2213 sendadc(sk, argv[1]);
2217 sockqueue(sk, node->hashtth, 24);
2219 qstr(sk, "$Error Namespace not implemented|");
2229 static void handletthl(struct dcpeer *peer)
2233 while(peer->inbufdata >= 24)
2235 pushtigertree(&peer->tth, peer->inbuf);
2236 memmove(peer->inbuf, peer->inbuf + 24, peer->inbufdata -= 24);
2237 peer->curread += 24;
2239 if(peer->curread >= peer->totalsize)
2241 if(peer->timeout == NULL)
2242 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
2243 peer->state = PEER_CMD;
2244 synctigertree(&peer->tth);
2245 restigertree(&peer->tth, buf);
2246 transfersethash(peer->transfer, newhash(L"TTH", 24, buf));
2251 static void cmd_adcsnd(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2254 off_t start, numbytes;
2256 if(peer->transfer == NULL)
2261 if((argv = parseadc(args)) == NULL)
2266 if(parrlen(argv) < 4)
2271 start = strtoll(argv[2], NULL, 10);
2272 numbytes = strtoll(argv[3], NULL, 10);
2273 if(!strcmp(argv[0], "tthl"))
2275 if((start != 0) || (numbytes % 24 != 0))
2277 /* Weird. Bail out. */
2281 if(peer->timeout != NULL)
2282 canceltimer(peer->timeout);
2283 peer->state = PEER_TTHL;
2284 peer->totalsize = numbytes;
2286 peer->fetchingtthl = 0;
2287 inittigertree(&peer->tth);
2289 } else if(!strcmp(argv[0], "file")) {
2290 if(start != peer->transfer->curpos)
2295 if(start + numbytes != peer->transfer->size)
2297 transfersetsize(peer->transfer, start + numbytes);
2302 if(peer->inbufdata > 0)
2304 sockpushdata(sk, peer->inbuf, peer->inbufdata);
2305 peer->inbufdata = 0;
2308 /* We certainly didn't request this...*/
2317 static void cmd_sending(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2321 if(peer->transfer == NULL)
2326 numbytes = strtoll(args, NULL, 10);
2327 if(peer->transfer->size - peer->transfer->curpos != numbytes)
2329 transfersetsize(peer->transfer, peer->transfer->curpos + numbytes);
2334 if(peer->inbufdata > 0)
2336 sockpushdata(sk, peer->inbuf, peer->inbufdata);
2337 peer->inbufdata = 0;
2343 static void cmd_(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
2348 hubhandleaction(sk, fn, cmd, args);
2352 static void cmd_(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2358 static int hubreqconn(struct fnetpeer *peer)
2363 if((peer->fn->state != FNN_EST) || (peer->fn->fnet != &dcnet))
2368 if((hub = peer->fn->data) == NULL)
2373 if((mbsnick = icwcstombs(peer->id, hub->charset)) == NULL)
2374 return(1); /* Shouldn't happen, of course, but who knows... */
2377 sendctm(hub->sk, mbsnick);
2378 expectpeer(mbsnick, peer->fn);
2380 qstrf(hub->sk, "$RevConnectToMe %s %s|", hub->nativenick, mbsnick);
2386 static int hubsendchat(struct fnetnode *fn, int public, wchar_t *to, wchar_t *string)
2389 char *mbsstring, *mbsto;
2392 if((mbsto = icwcstombs(to, hub->charset)) == NULL)
2397 if((mbsstring = icwcstombs(string, hub->charset)) == NULL)
2402 if((strchr(mbsto, '|') != NULL) || (strchr(mbsto, ' ') != NULL))
2409 if(strchr(mbsstring, '|') != NULL)
2420 qstrf(hub->sk, "<%s> %s|", hub->nativenick, mbsstring);
2422 qstrf(hub->sk, "$To: %s From: %s $<%s> %s|", mbsto, hub->nativenick, hub->nativenick, mbsstring);
2425 qstrf(hub->sk, "$To: %s From: %s $<%s> %s|", mbsto, hub->nativenick, hub->nativenick, mbsstring);
2432 static void findsizelimit(struct sexpr *sexpr, int *min, int *max)
2434 int minl, maxl, minr, maxr, retmin, retmax;
2439 findsizelimit(sexpr->l, &minl, &maxl);
2440 findsizelimit(sexpr->r, &minr, &maxr);
2441 retmin = (minl > minr)?minl:minr;
2442 if((maxl != -1) && (maxr != -1))
2443 retmax = (maxl < maxr)?maxl:maxr;
2452 findsizelimit(sexpr->l, &minl, &maxl);
2453 findsizelimit(sexpr->r, &minr, &maxr);
2454 retmin = (minl < minr)?minl:minr;
2455 if((maxl == -1) || (maxr == -1))
2458 retmax = (maxl > maxr)?maxl:maxr;
2461 findsizelimit(sexpr->l, &minl, &maxl);
2462 if((minl == 0) && (maxl == -1)) /* Interval is unspecified */
2466 } else if((minl == 0) && (maxl != -1)) {
2469 } else if((minl != 0) && (maxl == -1)) {
2472 } else { /* This would yield two seperate intervals, which DC cannot handle */
2478 retmax = sexpr->d.n - 1;
2481 retmin = sexpr->d.n;
2482 retmax = sexpr->d.n;
2485 retmin = sexpr->d.n + 1;
2499 static struct hash *findsehash(struct sexpr *sexpr)
2501 struct hash *h1, *h2;
2506 if((h1 = findsehash(sexpr->l)) != NULL)
2508 if((h1 = findsehash(sexpr->r)) != NULL)
2512 if((h1 = findsehash(sexpr->l)) == NULL)
2514 if((h2 = findsehash(sexpr->r)) == NULL)
2520 if(!wcscmp(sexpr->d.hash->algo, L"TTH"))
2521 return(sexpr->d.hash);
2528 static int hubsearch(struct fnetnode *fn, struct search *srch, struct srchfnnlist *ln)
2531 struct wcslist *list, *cur;
2532 char *sstr, *buf, *p;
2533 size_t sstrsize, sstrdata;
2534 struct sockaddr *name;
2536 int minsize, maxsize;
2540 if((fn->state != FNN_EST) || (hub->sk == NULL) || (hub->sk->state != SOCK_EST))
2542 list = findsexprstrs(srch->sexpr);
2543 findsizelimit(srch->sexpr, &minsize, &maxsize);
2544 hash = findsehash(srch->sexpr);
2545 if((minsize != 0) && (maxsize != -1))
2547 /* Choose either minsize or maxsize by trying to determine
2548 * which choice will be most restrictive. The result can be
2549 * approximative at best anyway, so don't try too hard... */
2550 if((50000000 - maxsize) > (minsize - 50000000))
2556 sstrsize = sstrdata = 0;
2557 if((hash != NULL) && (hash->len == 24))
2559 /* Prioritize hash searches above all else */
2560 bufcat(sstr, "F?T?0?9?TTH:", 12);
2561 buf = base32encode(hash->buf, hash->len);
2563 bufcat(sstr, buf, 39);
2568 sizebuf2(sstr, sstrdata + 32, 1);
2569 sstrdata += snprintf(sstr + sstrdata, sstrsize - sstrdata, "T?F?%i?1?", minsize);
2570 } else if(maxsize != -1) {
2571 sizebuf2(sstr, sstrdata + 32, 1);
2572 sstrdata += snprintf(sstr + sstrdata, sstrsize - sstrdata, "T?T?%i?1?", maxsize);
2574 bufcat(sstr, "F?F?0?1?", 8);
2578 for(cur = list; cur != NULL; cur = cur->next)
2580 /* Use DCCHARSET in $Get paths until further researched... */
2581 if((buf = icwcstombs(cur->str, DCCHARSET)) == NULL)
2583 /* Can't find anything anyway if the search expression
2584 * requires characters outside DC's charset. There's
2585 * nothing technically wrong with the search itself,
2586 * however, so return success. This should be
2587 * considered as an optimization. */
2594 addtobuf(sstr, '$');
2596 * It probably doesn't hurt if buf contains any extra
2597 * dollar signs - it will just result in extra search
2598 * terms, and the extraneous results will be filtered by
2599 * the search layer anyway. It hurts if it contains any
2600 * pipes, though, so let's sell them for money.
2602 for(p = buf; *p; p++)
2607 bufcat(sstr, buf, strlen(buf));
2611 /* Will match all files... :-/ */
2612 addtobuf(sstr, '.');
2618 if(sockgetremotename2(udpsock, hub->sk, &name, &namelen) < 0)
2620 flog(LOG_WARNING, "cannot get address of UDP socket");
2622 qstrf(hub->sk, "$Search %s %s|", formataddress(name, namelen), sstr);
2626 qstrf(hub->sk, "$Search Hub:%s %s|", hub->nativenick, sstr);
2630 fn->lastsrch = time(NULL);
2638 #define cc(c) ((void (*)(struct socket *, void *, char *, char *))(c))
2639 static struct command hubcmds[] =
2641 {"$Lock", cc(cmd_lock)},
2642 {"$HubName", cc(cmd_hubname)},
2643 {"$Hello", cc(cmd_hello)},
2644 {"$Quit", cc(cmd_quit)},
2645 {"$NickList", cc(cmd_nicklist)},
2646 {"$OpList", cc(cmd_oplist)},
2647 {"$MyINFO", cc(cmd_myinfo)},
2648 {"$ForceMove", cc(cmd_forcemove)},
2649 {"$Search", cc(cmd_search), .limit = 100},
2650 {"$MultiSearch", cc(cmd_search), .limit = 50},
2651 {"$ConnectToMe", cc(cmd_connecttome), .limit = 200},
2652 {"$RevConnectToMe", cc(cmd_revconnecttome), .limit = 500},
2653 {"$GetNetInfo", cc(cmd_getnetinfo)},
2654 {"$To:", cc(cmd_to)},
2655 {"$SR", cc(cmd_sr)},
2656 {"$UserCommand", cc(cmd_usercommand)},
2657 {"$GetPass", cc(cmd_getpass)},
2658 {"$LogedIn", cc(cmd_logedin)}, /* sic */
2659 {"$Supports", cc(cmd_hubsupports)},
2663 static struct command peercmds[] =
2665 {"$MyNick", cc(cmd_mynick)},
2666 {"$Lock", cc(cmd_peerlock)},
2667 {"$Direction", cc(cmd_direction)},
2668 {"$Key", cc(cmd_key)},
2669 {"$FileLength", cc(cmd_filelength)},
2670 {"$Error", cc(cmd_error)},
2671 {"$MaxedOut", cc(cmd_maxedout)},
2672 {"$Get", cc(cmd_get)},
2673 {"$Send", cc(cmd_send)},
2674 {"$Supports", cc(cmd_supports)},
2675 {"$GetBlock", cc(cmd_getblock)},
2676 {"$UGetBlock", cc(cmd_getblock)},
2677 {"$GetZBlock", cc(cmd_getblock)},
2678 {"$UGetZBlock", cc(cmd_getblock)},
2679 {"$ADCGET", cc(cmd_adcget)},
2680 {"$ADCSND", cc(cmd_adcsnd), .stop = 1},
2681 {"$Sending", cc(cmd_sending), .stop = 1},
2686 static void dctransgotdata(struct transfer *transfer, struct dcpeer *peer)
2690 unsigned char outbuf[1024];
2694 if((peer->state == PEER_TRNS) || (peer->state == PEER_SYNC))
2696 if(sockqueueleft(peer->sk) > 0)
2698 if((buf = sockgetinbuf(peer->trpipe, &bufsize)) != NULL)
2700 if(peer->compress == CPRS_NONE)
2702 sockqueue(peer->sk, buf, bufsize);
2703 } else if(peer->compress == CPRS_ZLIB) {
2704 cstr = peer->cprsdata;
2705 cstr->next_in = buf;
2706 cstr->avail_in = bufsize;
2707 while(cstr->avail_in > 0)
2709 cstr->next_out = outbuf;
2710 cstr->avail_out = sizeof(outbuf);
2711 if((ret = deflate(cstr, 0)) != Z_OK)
2713 flog(LOG_WARNING, "bug? deflate() did not return Z_OK (but rather %i)", ret);
2717 sockqueue(peer->sk, outbuf, sizeof(outbuf) - cstr->avail_out);
2722 if(peer->state == PEER_SYNC)
2724 if(peer->compress == CPRS_ZLIB)
2726 cstr = peer->cprsdata;
2727 cstr->next_in = NULL;
2731 cstr->next_out = outbuf;
2732 cstr->avail_out = sizeof(outbuf);
2733 ret = deflate(cstr, Z_FINISH);
2734 if((ret != Z_OK) && (ret != Z_STREAM_END))
2736 flog(LOG_WARNING, "bug? deflate(Z_FINISH) did not return Z_OK (but rather %i)", ret);
2740 sockqueue(peer->sk, outbuf, sizeof(outbuf) - cstr->avail_out);
2741 } while(ret != Z_STREAM_END);
2747 if(peer->timeout == NULL)
2748 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
2749 peer->state = PEER_CMD;
2751 transfersetstate(transfer, TRNS_HS);
2752 socksettos(peer->sk, confgetint("fnet", "fnptos"));
2753 transfer->flags.b.minislot = 0;
2754 peer->sk->writecb = NULL;
2761 static void peerdetach(struct dcpeer *peer)
2763 CBUNREG(peer->transfer, trans_filterout, peer);
2764 CBUNREG(peer->transfer, trans_destroy, peer);
2765 peer->trpipe->pnext = NULL;
2766 closesock(peer->trpipe);
2767 quitsock(peer->trpipe);
2768 peer->trpipe = NULL;
2769 peer->transfer = NULL;
2772 static int trdestroycb(struct transfer *transfer, struct dcpeer *peer)
2779 static void transread(struct socket *sk, struct dcpeer *peer)
2784 if(peer->transfer == NULL) {
2788 if(sockqueueleft(peer->trpipe) < 0)
2790 if((buf = sockgetinbuf(sk, &bufsize)) != NULL)
2792 if(peer->transfer == NULL)
2798 sockqueue(peer->trpipe, buf, bufsize);
2801 if(peer->transfer->curpos >= peer->transfer->size)
2809 static void transerr(struct socket *sk, int err, struct dcpeer *peer)
2811 struct transfer *transfer;
2813 if((transfer = peer->transfer) == NULL)
2822 static void transwrite(struct socket *sk, struct dcpeer *peer)
2824 if((peer->state != PEER_TRNS) && (peer->state != PEER_SYNC))
2826 if(peer->transfer == NULL)
2831 dctransgotdata(peer->transfer, peer);
2832 sockread(peer->trpipe);
2835 static void trpiperead(struct socket *sk, struct dcpeer *peer)
2837 dctransgotdata(peer->transfer, peer);
2840 static void trpipewrite(struct socket *sk, struct dcpeer *peer)
2842 transread(peer->sk, peer);
2845 static void trpipeerr(struct socket *sk, int errno, struct dcpeer *peer)
2847 peer->state = PEER_SYNC;
2848 dctransgotdata(peer->transfer, peer);
2850 if(peer->state != PEER_CMD)
2854 static struct socket *mktrpipe(struct dcpeer *peer)
2859 sk->pnext = peer->sk;
2861 sk->readcb = (void (*)(struct socket *, void *))trpiperead;
2862 sk->writecb = (void (*)(struct socket *, void *))trpipewrite;
2863 sk->errcb = (void (*)(struct socket *, int, void *))trpipeerr;
2867 static void udpread(struct socket *sk, void *data)
2869 char *buf, *p, *p2, *hashbuf;
2870 size_t buflen, hashlen;
2871 char *nick, *filename, *hubname;
2872 struct sockaddr_in hubaddr;
2873 struct sockaddr *addrbuf;
2876 struct fnetnode *fn, *myfn;
2879 wchar_t *wnick, *wfile;
2882 if((buf = sockgetinbuf(sk, &buflen)) == NULL)
2884 buf = srealloc(buf, buflen + 1);
2886 if(!strncmp(buf, "$SR ", 4))
2890 if((p2 = strchr(p, ' ')) == NULL)
2898 if((p2 = strchr(p, 5)) == NULL)
2905 if((p2 = strchr(p, ' ')) == NULL)
2911 size = strtoll(p, NULL, 10);
2913 if((p2 = strchr(p, '/')) == NULL)
2921 if((p2 = strchr(p, 5)) == NULL)
2928 if((p2 = strstr(p, " (")) == NULL)
2935 if((p2 = strchr(p, ':')) == NULL)
2941 hubaddr.sin_family = AF_INET;
2942 if(!inet_aton(p, &hubaddr.sin_addr))
2948 if((p2 = strchr(p, ')')) == NULL)
2954 hubaddr.sin_port = htons(atoi(p));
2955 /* Use DCCHARSET in $Get paths until further researched... */
2956 if((wfile = nmdc2path(filename, DCCHARSET)) == NULL)
2963 if(!strncmp(hubname, "TTH:", 4))
2965 if((hashbuf = base32decode(hubname + 4, &hashlen)) != NULL)
2968 hash = newhash(L"TTH", 24, hashbuf);
2972 for(fn = fnetnodes; fn != NULL; fn = fn->next)
2974 if((fn->fnet == &dcnet) && ((hub = fn->data) != NULL))
2976 if((hub->nativename != NULL) && !strcmp(hub->nativename, hubname))
2991 for(fn = fnetnodes; fn != NULL; fn = fn->next)
2993 if((fn->fnet == &dcnet) && ((hub = fn->data) != NULL) && !sockpeeraddr(hub->sk, &addrbuf, NULL))
2995 if((hub->sk != NULL) && addreq(addrbuf, (struct sockaddr *)&hubaddr))
3008 if((wnick = icmbstowcs(nick, (hub == NULL)?DCCHARSET:(hub->charset))) == NULL)
3013 sr = newsrchres(&dcnet, wfile, wnick);
3014 if(sr->peernick != NULL)
3016 sr->peernick = swcsdup(wnick);
3022 getfnetnode(sr->fn = myfn);
3031 static void hubread(struct socket *sk, struct fnetnode *fn)
3034 struct command *cmd;
3036 size_t datalen, cnlen;
3039 hub = (struct dchub *)fn->data;
3040 if(hub->queue.size > 1000)
3042 if((newbuf = sockgetinbuf(sk, &datalen)) == NULL)
3044 if(hub->inbufdata > 500000) /* Discard possible malicious data */
3046 sizebuf2(hub->inbuf, hub->inbufdata + datalen, 1);
3047 memcpy(hub->inbuf + hub->inbufdata, newbuf, datalen);
3050 hub->inbufdata += datalen;
3051 while((p - hub->inbuf < hub->inbufdata) && ((p2 = memchr(p, '|', hub->inbufdata - (p - hub->inbuf))) != NULL))
3054 for(cmd = hubcmds; cmd->handler != NULL; cmd++)
3056 cnlen = strlen(cmd->name);
3057 if(!strncmp(p, cmd->name, cnlen) && ((p[cnlen] == ' ') || (p[cnlen] == 0)))
3060 if((cmd->limit == 0) || (hub->queue.size < cmd->limit))
3061 newqcmd(&hub->queue, p);
3064 memmove(hub->inbuf, p, hub->inbufdata -= p - hub->inbuf);
3067 static void huberr(struct socket *sk, int err, struct fnetnode *fn)
3072 static int hubsetnick(struct fnetnode *fn, wchar_t *newnick)
3078 if((buf = icwcstombs(newnick, (hub == NULL)?DCCHARSET:(hub->charset))) == NULL)
3080 if((strchr(buf, ' ') != NULL) || (strchr(buf, '|') != NULL) || (strchr(buf, '$') != NULL))
3085 if(hub == NULL) /* Not yet connected */
3090 if(hub->nativenick != NULL)
3091 free(hub->nativenick);
3092 hub->nativenick = buf;
3096 static struct dchub *newdchub(struct fnetnode *fn)
3103 new = smalloc(sizeof(*new));
3104 memset(new, 0, sizeof(*new));
3106 if(confgetint("dc", "dcppemu"))
3108 if((emu = wpfind(fn->args, L"dcppemu")) != NULL)
3116 if((wcharset = wpfind(fn->args, L"charset")) != NULL)
3118 if((charset = icwcstombs(wcharset, "US-ASCII")) != NULL)
3120 if(!havecharset(charset))
3128 new->charset = charset;
3130 new->charset = sstrdup(DCCHARSET);
3131 if(hubsetnick(fn, fn->mynick))
3132 fnetsetnick(fn, L"DoldaConnectUser-IN");
3133 /* IN as in Invalid Nick */
3137 static struct dcpeer *newdcpeer(struct socket *sk)
3141 new = smalloc(sizeof(*new));
3142 memset(new, 0, sizeof(*new));
3145 if(confgetint("dc", "dcppemu"))
3156 static void freedcpeer(struct dcpeer *peer)
3159 struct qcommand *qcmd;
3163 if(peer->next != NULL)
3164 peer->next->prev = peer->prev;
3165 if(peer->prev != NULL)
3166 peer->prev->next = peer->next;
3167 if(peer->transfer != NULL)
3169 if(peer->timeout != NULL)
3170 canceltimer(peer->timeout);
3171 if(peer->sk->data == peer)
3172 peer->sk->data = NULL;
3173 peer->sk->readcb = NULL;
3174 peer->sk->writecb = NULL;
3175 peer->sk->errcb = NULL;
3178 if(peer->supports != NULL)
3180 for(i = 0; peer->supports[i] != NULL; i++)
3181 free(peer->supports[i]);
3182 free(peer->supports);
3184 if(peer->inbuf != NULL)
3186 if(peer->key != NULL)
3188 if(peer->wcsname != NULL)
3189 free(peer->wcsname);
3190 if(peer->nativename != NULL)
3191 free(peer->nativename);
3192 if(peer->charset != NULL)
3193 free(peer->charset);
3194 if(peer->fn != NULL)
3195 putfnetnode(peer->fn);
3196 while((qcmd = ulqcmd(&peer->queue)) != NULL)
3202 static void hubconnect(struct fnetnode *fn, struct socket *sk)
3206 sk->readcb = (void (*)(struct socket *, void *))hubread;
3207 sk->errcb = (void (*)(struct socket *, int, void *))huberr;
3208 fn->data = hub = newdchub(fn);
3210 getsock(hub->sk = sk);
3214 static void hubdestroy(struct fnetnode *fn)
3218 struct qcommand *qcmd;
3220 hub = (struct dchub *)fn->data;
3222 while((qcmd = ulqcmd(&hub->queue)) != NULL)
3224 if(hub->supports != NULL)
3226 for(i = 0; hub->supports[i] != NULL; i++)
3227 free(hub->supports[i]);
3228 free(hub->supports);
3230 if(hub->nativename != NULL)
3231 free(hub->nativename);
3232 if(hub->nativenick != NULL)
3233 free(hub->nativenick);
3234 if(hub->charset != NULL)
3236 if(hub->inbuf != NULL)
3241 static void hubkill(struct fnetnode *fn)
3245 hub = (struct dchub *)fn->data;
3249 static struct fnet dcnet =
3252 .connect = hubconnect,
3253 .destroy = hubdestroy,
3255 .setnick = hubsetnick,
3256 .reqconn = hubreqconn,
3257 .sendchat = hubsendchat,
3258 .search = hubsearch,
3261 static void peerread(struct socket *sk, struct dcpeer *peer)
3264 size_t datalen, cnlen;
3265 struct command *cmd;
3267 if(peer->state == PEER_CMD) {
3268 if((peer->queue.size > 50) || (peer->inbufdata > 65536))
3270 } else if(peer->state == PEER_TTHL) {
3274 if((newbuf = sockgetinbuf(sk, &datalen)) == NULL)
3276 sizebuf2(peer->inbuf, peer->inbufdata + datalen, 1);
3277 memcpy(peer->inbuf + peer->inbufdata, newbuf, datalen);
3279 peer->inbufdata += datalen;
3280 if(peer->state == PEER_CMD)
3283 while((peer->inbufdata > 0) && (p = memchr(peer->inbuf, '|', peer->inbufdata)) != NULL)
3286 for(cmd = peercmds; cmd->handler != NULL; cmd++)
3288 cnlen = strlen(cmd->name);
3289 if(!strncmp(peer->inbuf, cmd->name, cnlen) && ((peer->inbuf[cnlen] == ' ') || (peer->inbuf[cnlen] == 0)))
3292 if((cmd->limit == 0) || (peer->queue.size < cmd->limit))
3293 newqcmd(&peer->queue, peer->inbuf);
3294 memmove(peer->inbuf, p, peer->inbufdata -= p - peer->inbuf);
3297 peer->state = PEER_STOP;
3301 } else if(peer->state == PEER_TTHL) {
3306 static void peererror(struct socket *sk, int err, struct dcpeer *peer)
3311 static void peerconnect(struct socket *sk, int err, struct fnetnode *fn)
3313 struct dcpeer *peer;
3322 peer = newdcpeer(sk);
3325 peer->dcppemu = hub->dcppemu;
3326 sk->readcb = (void (*)(struct socket *, void *))peerread;
3327 sk->errcb = (void (*)(struct socket *, int, void *))peererror;
3329 socksettos(sk, confgetint("fnet", "fnptos"));
3330 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
3335 static void peeraccept(struct lport *lp, struct socket *newsk, void *data)
3337 struct dcpeer *peer;
3339 peer = newdcpeer(newsk);
3341 newsk->readcb = (void (*)(struct socket *, void *))peerread;
3342 newsk->errcb = (void (*)(struct socket *, int, void *))peererror;
3344 socksettos(newsk, confgetint("fnet", "fnptos"));
3345 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
3348 static void updatehmlist(void)
3350 int i, lev, ic, ret;
3351 struct sharecache *node;
3352 char *buf, *buf2, numbuf[32];
3353 size_t bufsize, bufdata;
3358 buf = smalloc(bufsize = 65536);
3359 node = shareroot->child;
3364 /* Use DCCHARSET in $Get paths until further researched... */
3365 if((buf2 = icwcstombs(node->name, DCCHARSET)) != NULL)
3367 for(i = 0; i < lev; i++)
3369 bufcat(buf, buf2, strlen(buf2));
3371 if(node->f.b.type == FILE_REG)
3374 sprintf(numbuf, "%ji", (intmax_t)node->size);
3375 bufcat(buf, numbuf, strlen(numbuf));
3382 if((node->child != NULL) && !ic)
3386 } else if(node->next != NULL) {
3389 while(node->next == NULL)
3392 node = node->parent;
3393 if(node == shareroot)
3396 if(node == shareroot)
3401 if(hmlistname != NULL)
3406 hmlistname = sstrdup("/tmp/dc-filelist-hm-XXXXXX");
3407 if((fd = mkstemp(hmlistname)) < 0)
3409 flog(LOG_WARNING, "could not create HM file list tempfile: %s", strerror(errno));
3413 out = fdopen(fd, "w");
3415 * I do not want to implement a good Huffman encoder, and it's not
3416 * like Huffman encoding actually yields any impressive results
3417 * for DC file lists anyway, so I'll just output a bogus
3418 * tree. Implement a good encoder if you want to.
3420 fwrite("HE3\r\0", 1, 5, out);
3421 fwrite(&bufdata, 4, 1, out); /* XXX: Endian unsafe */
3423 fwrite(&ibuf, 2, 1, out);
3425 for(i = 0; i < 256; i++)
3427 fwrite(&i, 1, 1, out);
3428 fwrite(&ibuf, 1, 1, out);
3430 for(i = 0; i < 256; i++)
3431 fwrite(&i, 1, 1, out);
3432 for(buf2 = buf; bufdata > 0;)
3434 if((ret = fwrite(buf2, 1, bufdata, out)) < 0)
3436 flog(LOG_WARNING, "could not write file list: %s", strerror(errno));
3447 static struct xmlent
3454 /* {L'\'', L"""}, Emulate DC++ escaping by omitting this. */
3458 static wchar_t *escapexml(wchar_t *src)
3460 static wchar_t *buf = NULL;;
3463 size_t bufsize, bufdata;
3469 bufsize = bufdata = 0;
3470 for(; *src != L'\0'; src++)
3473 if((c > 0) && (c < 32))
3475 bufcat(buf, L"&#", 2);
3476 ret = swprintf(nbuf, (sizeof(nbuf) / sizeof(*nbuf)), L"%i", c);
3477 bufcat(buf, nbuf, ret);
3478 addtobuf(buf, L';');
3480 for(ent = entities; ent->ent != NULL; ent++)
3484 bufcat(buf, ent->ent, wcslen(ent->ent));
3488 if(ent->ent == NULL)
3489 addtobuf(buf, *src);
3492 addtobuf(buf, L'\0');
3496 static void updatexmllist(void)
3500 char cidbuf[14], *namebuf;
3502 struct sharecache *node;
3504 if(xmllistname != NULL)
3506 unlink(xmllistname);
3509 xmllistname = sstrdup("/tmp/dc-filelist-dcxml-XXXXXX");
3510 if((fd = mkstemp(xmllistname)) < 0)
3512 flog(LOG_WARNING, "could not create XML file list tempfile: %s", strerror(errno));
3517 if((fs = fdopen(fd, "w")) == NULL)
3519 flog(LOG_WARNING, "could not fdopen XML list fd %i: %s", fd, strerror(errno));
3520 unlink(xmllistname);
3526 fprintf(fs, "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>\r\n");
3527 for(i = 0; i < sizeof(cidbuf) - 1; i++)
3528 cidbuf[i] = (rand() % ('Z' - 'A' + 1)) + 'A';
3530 if(confgetint("dc", "dcppemu"))
3531 fprintf(fs, "<FileListing Version=\"1\" CID=\"%s\" Base=\"/\" Generator=\"DC++ 0.674\">\r\n", cidbuf);
3533 fprintf(fs, "<FileListing Version=\"1\" CID=\"%s\" Base=\"/\" Generator=\"%s\">\r\n", cidbuf, "DoldaConnect" VERSION);
3535 node = shareroot->child;
3539 if((namebuf = icswcstombs(escapexml(node->name), "UTF-8", NULL)) != NULL)
3541 for(i = 0; i < lev; i++)
3543 if(node->child != NULL)
3545 fprintf(fs, "<Directory Name=\"%s\">\r\n", namebuf);
3550 fprintf(fs, "<File Name=\"%s\" Size=\"%ji\"", namebuf, (intmax_t)node->size);
3551 if(node->f.b.hastth)
3553 hashbuf = base32encode(node->hashtth, 24);
3554 fprintf(fs, " TTH=\"%.39s\"", hashbuf);
3557 fprintf(fs, "/>\r\n");
3559 while(node->next == NULL)
3561 node = node->parent;
3562 if(node == shareroot)
3567 for(i = 0; i < lev; i++)
3569 fprintf(fs, "</Directory>\r\n");
3572 if(node == shareroot)
3578 if(confgetint("dc", "dcppemu"))
3579 fprintf(fs, "</FileListing>");
3581 fprintf(fs, "</FileListing>\r\n");
3585 static void updatexmlbz2list(void)
3594 if(xmllistname == NULL)
3596 if((in = fopen(xmllistname, "r")) == NULL)
3598 flog(LOG_WARNING, "could not open XML file list for bzipping: %s", strerror(errno));
3601 if(xmlbz2listname != NULL)
3603 unlink(xmlbz2listname);
3604 free(xmlbz2listname);
3606 xmlbz2listname = sstrdup("/tmp/dc-filelist-dcxmlbz2-XXXXXX");
3607 if((fd = mkstemp(xmlbz2listname)) < 0)
3609 flog(LOG_WARNING, "could not create bzipped XML file list tempfile: %s", strerror(errno));
3610 free(xmlbz2listname);
3611 xmlbz2listname = NULL;
3615 if((real = fdopen(fd, "w")) == NULL)
3617 flog(LOG_WARNING, "could not fdopen bzipped XML list fd %i: %s", fd, strerror(errno));
3619 unlink(xmlbz2listname);
3620 free(xmlbz2listname);
3621 xmlbz2listname = NULL;
3625 out = BZ2_bzWriteOpen(&err, real, 9, 0, 0);
3628 flog(LOG_WARNING, "could not open bzip2 stream from XML list");
3630 unlink(xmlbz2listname);
3631 free(xmlbz2listname);
3632 xmlbz2listname = NULL;
3638 bufdata = fread(buf, 1, sizeof(buf), in);
3639 BZ2_bzWrite(&err, out, buf, bufdata);
3642 BZ2_bzWriteClose(&err, out, 0, NULL, NULL);
3646 static void listtimercb(int cancelled, void *uudata)
3648 listwritetimer = NULL;
3653 static void updatelists(int now)
3655 if((hmlistname == NULL) || (xmllistname == NULL) || (xmlbz2listname == NULL))
3659 if(listwritetimer == NULL)
3660 listwritetimer = timercallback(ntime() + confgetint("cli", "hashwritedelay"), listtimercb, NULL);
3663 if(listwritetimer != NULL)
3664 canceltimer(listwritetimer);
3670 static int shareupdate(unsigned long long uusharesize, void *data)
3676 static char *quotestr(char *str)
3680 size_t bufsize, bufdata;
3682 static char *enc = NULL;
3683 size_t encsize, encdata;
3686 bufsize = bufdata = 0;
3687 for(p = (unsigned char *)str; *p; p++)
3690 bufcat(buf, "\\b", 2);
3692 bufcat(buf, "\\t", 2);
3694 bufcat(buf, "\\n", 2);
3696 bufcat(buf, "\\r", 2);
3698 bufcat(buf, "\\\\", 2);
3702 bprintf(buf, "\\x%02x", *p);
3708 if((wbuf = icmbstowcs((char *)buf, DCCHARSET)) != NULL)
3710 enc = icwcstombs(wbuf, NULL);
3715 encsize = encdata = 0;
3716 for(p = buf; *p; p++) {
3720 bprintf(buf, "\\x%x", *p);
3727 static void logunimpl(char *list, char *cmd, char *args)
3731 if((log = fopen("/tmp/dc-unimpl", "a")) == NULL)
3733 flog(LOG_WARNING, "could not open unimpl log: %s", strerror(errno));
3738 fputs(quotestr(cmd), log);
3742 fputs(quotestr(args), log);
3748 static void dispatchcommand(struct qcommand *qcmd, struct command *cmdlist, struct socket *sk, void *data)
3751 struct command *cmd;
3753 if((p = strchr(qcmd->string, ' ')) != NULL)
3755 for(cmd = cmdlist; cmd->handler != NULL; cmd++)
3757 if(!strcmp(cmd->name, qcmd->string))
3760 if(cmd->handler != NULL)
3762 cmd->handler(sk, data, qcmd->string, p);
3763 } else if(confgetint("dc", "logunimpl")) {
3764 if(cmdlist == hubcmds)
3765 logunimpl("hub", qcmd->string, p);
3766 else if(cmdlist == peercmds)
3767 logunimpl("peer", qcmd->string, p);
3769 logunimpl("other?!", qcmd->string, p);
3773 static int run(void)
3775 struct fnetnode *fn, *nextfn;
3777 struct dcpeer *peer, *nextpeer;
3778 struct qcommand *qcmd;
3783 for(fn = fnetnodes; fn != NULL; fn = nextfn)
3786 if(fn->fnet != &dcnet)
3788 if(fn->data == NULL)
3790 hub = (struct dchub *)fn->data;
3791 while((quota > 0) && ((qcmd = ulqcmd(&hub->queue)) != NULL))
3793 if(*qcmd->string == '$')
3795 if((hub->sk != NULL) && (hub->sk->state == SOCK_EST))
3796 dispatchcommand(qcmd, hubcmds, hub->sk, fn);
3797 } else if(*qcmd->string != 0) {
3798 hubrecvchat(hub->sk, fn, NULL, qcmd->string);
3804 if(hub->queue.size < 1000)
3805 hubread(hub->sk, fn);
3810 for(peer = peers; peer != NULL; peer = peer->next)
3812 while(!peer->close && (quota > 0) && ((qcmd = ulqcmd(&peer->queue)) != NULL))
3814 if(peer->timeout != NULL)
3815 canceltimer(peer->timeout);
3816 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
3817 if(*qcmd->string == '$')
3818 dispatchcommand(qcmd, peercmds, peer->sk, peer);
3823 if((peer->queue.size < 50) && (peer->inbufdata < 500000))
3824 peerread(peer->sk, peer);
3828 for(peer = peers; peer != NULL; peer = nextpeer)
3830 nextpeer = peer->next;
3837 static void preinit(int hup)
3844 static int updateudpport(struct configvar *var, void *uudata)
3846 struct sockaddr_in addr;
3847 struct socket *newsock;
3849 memset(&addr, 0, sizeof(addr));
3850 addr.sin_family = AF_INET;
3851 addr.sin_port = htons(var->val.num);
3852 if((newsock = netcsdgram((struct sockaddr *)&addr, sizeof(addr))) == NULL)
3854 flog(LOG_WARNING, "could not create new DC UDP socket, reverting to old: %s", strerror(errno));
3857 newsock->readcb = udpread;
3864 static int updatetcpport(struct configvar *var, void *uudata)
3866 struct sockaddr_in addr;
3867 struct lport *newsock;
3869 memset(&addr, 0, sizeof(addr));
3870 addr.sin_family = AF_INET;
3871 addr.sin_port = htons(var->val.num);
3872 if((newsock = netcslisten(SOCK_STREAM, (struct sockaddr *)&addr, sizeof(addr), peeraccept, NULL)) == NULL)
3873 flog(LOG_INFO, "could not listen to a remote address, going into passive mode");
3875 closelport(tcpsock);
3880 static int init(int hup)
3882 struct sockaddr_in addr;
3886 GCBREG(sharechangecb, shareupdate, NULL);
3890 closelport(tcpsock);
3891 addr.sin_family = AF_INET;
3892 memset(&addr.sin_addr, 0, sizeof(addr.sin_addr));
3893 addr.sin_port = htons(confgetint("dc", "udpport"));
3894 if((udpsock = netcsdgram((struct sockaddr *)&addr, sizeof(addr))) == NULL)
3896 flog(LOG_CRIT, "could not create DC UDP socket: %s", strerror(errno));
3899 udpsock->readcb = udpread;
3900 addr.sin_port = htons(confgetint("dc", "tcpport"));
3901 if((tcpsock = netcslisten(SOCK_STREAM, (struct sockaddr *)&addr, sizeof(addr), peeraccept, NULL)) == NULL)
3902 flog(LOG_INFO, "could not listen to a remote address, going into passive mode");
3903 CBREG(confgetvar("dc", "udpport"), conf_update, updateudpport, NULL, NULL);
3904 CBREG(confgetvar("dc", "tcpport"), conf_update, updatetcpport, NULL, NULL);
3905 CBREG(confgetvar("net", "mode"), conf_update, updatetcpport, NULL, NULL);
3910 static void terminate(void)
3912 if(hmlistname != NULL)
3917 if(xmllistname != NULL)
3919 unlink(xmllistname);
3922 if(xmlbz2listname != NULL)
3924 unlink(xmlbz2listname);
3925 free(xmlbz2listname);
3929 static struct configvar myvars[] =
3931 /** Specifies the share description reported to other DC users. */
3932 {CONF_VAR_STRING, "desc", {.str = L""}},
3933 /** Specifies the speed reported to other DC users. Normal values
3934 * are 28.8Kbps, 33.6Kbps, 56Kbps, Satellite, ISDN, DSL, Cable,
3935 * LAN(T1) or LAN(T3)*/
3936 {CONF_VAR_STRING, "speedstring", {.str = L"LAN(T1)"}},
3937 /** The e-mail address to report to other DC users. */
3938 {CONF_VAR_STRING, "email", {.str = L"spam@spam.org"}},
3939 /** Specifies a specific UDP port to use for DC search results. If
3940 * left unspecified, a port is allocated dynamically. Useful for
3941 * NAT routers (see also the net.visibleipv4 address for those
3943 {CONF_VAR_INT, "udpport", {.num = 0}},
3944 /** Specifies a specific TCP port to use for DC peer
3945 * connections. If left unspecified, a port is allocated
3946 * dynamically. Useful for NAT routers (see also the
3947 * net.visibleipv4 address for those cases). */
3948 {CONF_VAR_INT, "tcpport", {.num = 0}},
3949 /** If set to true, doldacond will do its best to emulate DC++
3950 * (currently v0.674). This should be left off if at all possible,
3951 * since turning it on will violate the rules of most hubs and
3952 * thus give hub owners an actual reason to kick you if it is
3953 * detected. It might be needed for some of the more bone-headed
3954 * hub owners, though. Note that DC++ emulation can also be turned
3955 * on or off for individual hubs, overriding this setting. */
3956 {CONF_VAR_BOOL, "dcppemu", {.num = 0}},
3957 /** Use for debugging. If set to true, doldacond will log all
3958 * unknown commands it receives, and their arguments, to
3959 * /tmp/dc-unimpl. */
3960 {CONF_VAR_BOOL, "logunimpl", {.num = 0}},
3961 /** If set to true, doldacond will hide its support for deflate
3962 * compression of transfers from other clients, so that they will
3963 * not request compressed uploads. Compressed transfers may
3964 * consume a non-trivial amount of CPU time on slower machines. */
3965 {CONF_VAR_BOOL, "hidedeflate", {.num = 0}},
3969 static struct module me =
3978 .terminate = terminate,