2 * Dolda Connect - Modular multiuser Direct Connect-style client
3 * Copyright (C) 2004 Fredrik Tolf <fredrik@dolda2000.com>
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 #include <netinet/in.h>
26 #include <arpa/inet.h>
43 #include "sysevents.h"
48 * The Direct Connect protocol is extremely ugly. Thus, this code must
49 * also be a bit ugly in certain places. Please forgive me. =/
51 * This also means that there might be some pieces of the code that
52 * look completely illogical to you, and you think that you may make
53 * them much neater/better. However, in many cases it might just be
54 * that it's required to cope with some oddity of the protocol, such
55 * as the amazingly ugly delayed key response in the peer protocol.
58 /* I assume this is the correct character set to use for DC,
59 * considering it was developed without i18n support under Windows */
60 #define DCCHARSET "windows-1252"
74 void (*handler)(struct socket *sk, void *data, char *cmd, char *args);
81 struct qcommand *next;
87 struct qcommand *f, *l;
95 size_t inbufdata, inbufsize;
96 struct qcmdqueue queue;
97 int extended, dcppemu;
106 struct dcexppeer *next, *prev;
109 struct timer *expire;
114 struct dcpeer *next, *prev;
118 size_t inbufdata, inbufsize;
119 off_t curread, totalsize;
121 struct timer *timeout;
122 struct qcmdqueue queue;
123 struct transfer *transfer;
125 int ptclose; /* Close after transfer is complete */
126 int accepted; /* If false, we connected, otherwise, we accepted */
127 int extended, dcppemu;
128 int direction; /* Using the constants from transfer.h */
130 int hascurpos, fetchingtthl, notthl;
131 struct tigertreehash tth;
140 static struct fnet dcnet;
141 static struct transferiface dctransfer;
142 static struct socket *udpsock = NULL;
143 static struct socket *tcpsock = NULL;
144 static struct dcpeer *peers = NULL;
146 static struct dcexppeer *expected = NULL;
147 static char *hmlistname = NULL;
148 static char *xmllistname = NULL;
149 static char *xmlbz2listname = NULL;
150 static struct timer *listwritetimer = NULL;
152 static void peerconnect(struct socket *sk, int err, struct fnetnode *fn);
153 static void freedcpeer(struct dcpeer *peer);
154 static void transread(struct socket *sk, struct dcpeer *peer);
155 static void transerr(struct socket *sk, int err, struct dcpeer *peer);
156 static void transwrite(struct socket *sk, struct dcpeer *peer);
157 static void updatehmlist(void);
158 static void updatexmllist(void);
159 static void updatexmlbz2list(void);
160 static void requestfile(struct dcpeer *peer);
161 static void updatelists(int now);
163 static int reservedchar(unsigned char c)
165 return((c == 0) || (c == 5) || (c == 124) || (c == 96) || (c == 126) || (c == 36));
168 /* Oh, how I despise having to do this... */
169 static char *dcmakekey(char *lock)
175 buf = smalloc(strlen(lock));
178 for(i = 0; lock[i]; i++)
180 buf[i] = lock[i] ^ save;
181 buf[i] = ((buf[i] & 0x0F) << 4) | ((buf[i] & 0xF0) >> 4);
183 if((i != 0) && reservedchar(buf[i]))
188 buf[0] ^= buf[i - 1];
189 if(reservedchar(buf[0]))
193 key = smalloc(len + 1);
195 for(i = 0; lock[i] != 0; i++)
197 if(reservedchar(buf[i]))
198 offset += sprintf(key + offset, "/%%DCN%03i%%/", buf[i]);
200 key[offset++] = buf[i];
207 static wchar_t *nmdc2path(char *nmdc, char *charset)
211 if((ret = icmbstowcs(nmdc, charset)) == NULL)
213 for(p = ret; *p != L'\0'; p++) {
220 static char *path2nmdc(wchar_t *path, char *charset)
224 if((ret = icwcstombs(path, charset)) == NULL)
226 for(p = ret; *p; p++) {
233 static wchar_t *adc2path(char *adc)
235 return(icmbstowcs(adc, "UTF-8"));
238 static char *path2adc(wchar_t *path)
240 return(icwcstombs(path, "UTF-8"));
243 static int isdchash(struct hash *hash)
245 if(wcscmp(hash->algo, L"TTH"))
253 * Uncomment when used!
255 static int hubsupports(struct dchub *hub, char *cap)
259 if(hub->supports == NULL)
261 for(p = hub->supports; *p != NULL; p++)
263 if(!strcasecmp(*p, cap))
270 static int supports(struct dcpeer *peer, char *cap)
274 if(peer->supports == NULL)
276 for(p = peer->supports; *p != NULL; p++)
278 if(!strcasecmp(*p, cap))
284 static void endcompress(struct dcpeer *peer)
286 if(peer->compress == CPRS_ZLIB)
288 deflateEnd(peer->cprsdata);
289 free(peer->cprsdata);
291 peer->compress = CPRS_NONE;
294 static void initcompress(struct dcpeer *peer, int algo)
299 peer->compress = algo;
300 if(algo == CPRS_ZLIB)
302 peer->cprsdata = smalloc(sizeof(z_stream));
303 memset(peer->cprsdata, 0, sizeof(z_stream));
304 if((ret = deflateInit(peer->cprsdata, 3)) != Z_OK)
306 flog(LOG_CRIT, "Aiya! zlib refuses to init (%i)!", ret);
312 static void unquote(wchar_t *in)
316 for(p = in; *p != L'\0'; p++)
320 for(p2 = p + 1; (*p2 != L'\0') && (*p2 != L';') && (*p2 != L'&'); p2++);
327 if(!wcscmp(p + 1, L"amp"))
330 } else if(p[1] == L'#') {
331 nc = ucptowc(wcstol(p + 2, NULL, 10));
340 memmove(p + 1, p2 + 1, (wcslen(p2 + 1) + 1) * sizeof(wchar_t));
345 static void freeexppeer(struct dcexppeer *ep)
348 ep->next->prev = ep->prev;
350 ep->prev->next = ep->next;
355 if(ep->expire != NULL)
356 canceltimer(ep->expire);
360 static void exppeerexpire(int cancelled, struct dcexppeer *ep)
367 static struct dcexppeer *expectpeer(char *nick, struct fnetnode *fn)
369 struct dcexppeer *ep;
371 ep = smalloc(sizeof(*ep));
372 ep->nick = sstrdup(nick);
373 getfnetnode(ep->fn = fn);
374 ep->expire = timercallback(ntime() + 300, (void (*)(int, void *))exppeerexpire, ep);
383 static struct qcommand *newqcmd(struct qcmdqueue *queue, char *string)
385 struct qcommand *new;
387 new = smalloc(sizeof(*new));
388 new->string = sstrdup(string);
393 queue->l->next = new;
399 static struct qcommand *ulqcmd(struct qcmdqueue *queue)
401 struct qcommand *qcmd;
403 if((qcmd = queue->f) == NULL)
405 if((queue->f = qcmd->next) == NULL)
411 static void freeqcmd(struct qcommand *qcmd)
417 static void hubrecvchat(struct socket *sk, struct fnetnode *fn, char *from, char *string)
419 wchar_t *chat, *wfrom, *wpeer;
421 struct fnetpeer *peer;
425 end = string + strlen(string);
426 while((p = strchr(string, 13)) != NULL)
427 memmove(p, p + 1, (end-- - p));
430 if((strlen(string) > strlen(from) + 2) && (*string == '<') && !memcmp(string + 1, from, strlen(from)) && (*(string + strlen(from) + 1) == '>'))
431 string += strlen(from) + 2;
432 if((wfrom = icmbstowcs(from, hub->charset)) == NULL)
434 wpeer = swcsdup(wfrom);
440 for(p = string + 1; *p; p++)
442 if((*p == ' ') || (*p == '>'))
450 if((wpeer = icmbstowcs(string + 1, hub->charset)) == NULL)
456 wpeer = swcsdup(L"");
458 if((chat = icmbstowcs(string, hub->charset)) == NULL)
468 if((peer = fnetfindpeer(fn, wfrom)) == NULL) /* Assume public chat */
469 fnethandlechat(fn, 1, wfrom, wpeer, chat);
471 fnethandlechat(fn, 0, wfrom, wpeer, chat);
473 fnethandlechat(fn, 1, L"", wpeer, chat);
481 static void peertimeout(int cancelled, struct dcpeer *peer)
483 peer->timeout = NULL;
489 static void sendadc(struct socket *sk, char *arg)
492 size_t bufsize, bufdata;
495 bufsize = bufdata = 0;
501 bufcat(buf, "\\s", 2);
502 } else if(*arg == '\n') {
503 bufcat(buf, "\\n", 2);
504 } else if(*arg == '\\') {
505 bufcat(buf, "\\\\", 2);
510 sockqueue(sk, buf, bufdata);
514 #if defined(__GNUC__)
515 static void __attribute__ ((format (printf, 2, 3))) sendadcf(struct socket *sk, char *arg, ...)
517 static void sendadcf(struct socket *sk, char *arg, ...)
524 buf = vsprintf2(arg, args);
532 static char **parseadc(char *args)
535 size_t retbufsize, retbufdata;
537 size_t bufsize, bufdata;
542 retbufsize = retbufdata = bufsize = bufdata = 0;
551 else if(*args != ' ')
555 if((*args == ' ') || (*args == 0))
558 addtobuf(retbuf, buf);
560 bufsize = bufdata = 0;
563 } else if(*args == '\\') {
566 addtobuf(buf, *args);
575 addtobuf(retbuf, NULL);
578 } else if((*args == 's') || (*args == ' ')) {
580 } else if(*args == 'n') {
582 } else if(*args == '\\') {
592 addtobuf(retbuf, NULL);
596 /* Macros useful in command handlers */
597 #define skipspace(s) ({if(((s) = strchr((s), ' ')) == NULL) return; else (s)++;})
598 #define qstr(sk, str) sockqueue(sk, str, strlen(str))
599 #define qstrf(sk, strandargs...) \
602 if((__buf__ = sprintf2(strandargs)) != NULL) { \
603 sockqueue(sk, __buf__, strlen(__buf__)); \
608 static char *tr(char *str, char *trans)
612 for(; *trans; trans += 2)
614 for(p = strchr(str, trans[0]); p != NULL; p = strchr(p, trans[0]))
620 static char *getadcid(struct dcpeer *peer)
627 if(!wcscmp(peer->transfer->path, L"files.xml") || !wcscmp(peer->transfer->path, L"files.xml.bz2") || !wcscmp(peer->transfer->path, L"MyList.DcLst"))
629 if(!isfilelist && (peer->transfer->hash != NULL) && isdchash(peer->transfer->hash) && supports(peer, "tthf"))
631 buf = base32encode(peer->transfer->hash->buf, 24);
632 ret = sprintf2("TTH/%.39s", buf);
635 ret = path2adc(peer->transfer->path);
641 static int trresumecb(struct transfer *transfer, wchar_t *cmd, wchar_t *arg, struct dcpeer *peer)
643 if(!wcscmp(cmd, L"resume"))
647 flog(LOG_WARNING, "filter returned no position for \"resume\" on transfer %i", transfer->id);
650 transfer->curpos = wcstoll(arg, NULL, 10);
659 static void sendmynick(struct dcpeer *peer)
665 qstrf(peer->sk, "$MyNick %s|", icswcstombs(confgetstr("cli", "defnick"), peer->charset, "DoldaConnectUser-IN"));
667 qstrf(peer->sk, "$MyNick %s|", icswcstombs(fn->mynick, peer->charset, "DoldaConnectUser-IN"));
670 static void sendpeerlock(struct dcpeer *peer)
673 qstrf(peer->sk, "$Lock EXTENDEDPROTOCOLABCABCABCABCABCABC Pk=DCPLUSPLUS0.674ABCABC|");
675 qstrf(peer->sk, "$Lock EXTENDEDPROTOCOLABCABCABCABCABCABC Pk=DOLDA%sABCABCABC|", VERSION);
678 static void sendsupports(struct dcpeer *peer)
681 qstr(peer->sk, "$Supports MiniSlots XmlBZList ADCGet TTHL TTHF GetZBlock ZLIG |");
683 qstr(peer->sk, "$Supports MiniSlots XmlBZList ADCGet TTHL TTHF");
684 if(!confgetint("dc", "hidedeflate"))
685 qstr(peer->sk, " GetZBlock ZLIG");
690 static void requestfile(struct dcpeer *peer)
694 if(peer->transfer->size == -1)
696 /* Use DCCHARSET for $Get paths until further researched... */
697 if((buf = path2nmdc(peer->transfer->path, DCCHARSET)) == NULL)
699 transferseterror(peer->transfer, TRNSE_NOTFOUND);
703 /* The transfer will be restarted later from
704 * cmd_filelength when it detects that the sizes
706 qstrf(peer->sk, "$Get %s$1|", buf);
710 if((peer->transfer->hash == NULL) && !peer->notthl)
712 if(supports(peer, "adcget") && supports(peer, "tthl"))
714 qstr(peer->sk, "$ADCGET");
715 sendadc(peer->sk, "tthl");
716 if((buf = getadcid(peer)) == NULL)
718 transferseterror(peer->transfer, TRNSE_NOTFOUND);
722 sendadc(peer->sk, buf);
724 sendadc(peer->sk, "0");
725 sendadc(peer->sk, "-1");
727 peer->fetchingtthl = 1;
733 if(forkfilter(peer->transfer))
735 flog(LOG_WARNING, "could not fork filter for transfer %i: %s", peer->transfer->id, strerror(errno));
739 CBREG(peer->transfer, trans_filterout, (int (*)(struct transfer *, wchar_t *, wchar_t *, void *))trresumecb, NULL, peer);
742 if(supports(peer, "adcget"))
744 qstr(peer->sk, "$ADCGET");
745 sendadc(peer->sk, "file");
746 if((buf = getadcid(peer)) == NULL)
748 transferseterror(peer->transfer, TRNSE_NOTFOUND);
752 sendadc(peer->sk, buf);
754 sendadcf(peer->sk, "%ji", (intmax_t)peer->transfer->curpos);
755 sendadcf(peer->sk, "%ji", (intmax_t)(peer->transfer->size - peer->transfer->curpos));
757 } else if(supports(peer, "xmlbzlist")) {
758 if((buf = path2nmdc(peer->transfer->path, "UTF-8")) == NULL)
760 transferseterror(peer->transfer, TRNSE_NOTFOUND);
764 qstrf(peer->sk, "$UGetBlock %ji %ji %s|", (intmax_t)peer->transfer->curpos, (intmax_t)(peer->transfer->size - peer->transfer->curpos), buf);
767 /* Use DCCHARSET for $Get paths until further researched... */
768 if((buf = path2nmdc(peer->transfer->path, DCCHARSET)) == NULL)
770 transferseterror(peer->transfer, TRNSE_NOTFOUND);
774 qstrf(peer->sk, "$Get %s$%ji|", buf, (intmax_t)peer->transfer->curpos + 1);
779 static void sendmyinfo(struct socket *sk, struct fnetnode *fn)
783 struct fnetnode *cfn;
787 qstrf(sk, "$MyINFO $ALL %s ", hub->nativenick);
788 buf = tr(icswcstombs(confgetstr("dc", "desc"), hub->charset, "Charset_conv_failure"), "$_|_");
789 qstrf(sk, "%s", buf);
791 for(cfn = fnetnodes; cfn != NULL; cfn = cfn->next)
793 if((cfn->state == FNN_EST) || (cfn->state == FNN_HS))
795 if(cfn->regstatus == FNNS_OP)
797 else if(cfn->regstatus == FNNS_REG)
803 qstrf(sk, "<%s V:%s,M:%c,H:%i/%i/%i,S:%i>",
804 (hub->dcppemu)?"++":"Dolda",
805 (hub->dcppemu)?"0.674":VERSION,
806 (tcpsock == NULL)?'P':'A',
808 confgetint("transfer", "slots")
811 buf = tr(icswcstombs(confgetstr("dc", "speedstring"), hub->charset, "Charset_conv_failure"), "$_|_");
812 qstrf(sk, "%s\x01$", buf);
813 buf = tr(icswcstombs(confgetstr("dc", "email"), hub->charset, "Charset_conv_failure"), "$_|_");
814 qstrf(sk, "%s$", buf);
815 qstrf(sk, "%llu$|", sharesize);
818 static void hubhandleaction(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
823 if(!strcmp(cmd, "$Lock"))
825 qstrf(sk, "$ValidateNick %s|", hub->nativenick);
826 } else if(!strcmp(cmd, "$Hello")) {
827 if(fn->state == FNN_HS)
829 qstrf(sk, "$Version 1,0091|");
830 qstrf(sk, "$GetNickList|");
832 fnetsetstate(fn, FNN_EST);
834 qstrf(sk, "$GetINFO %s %s|", args, hub->nativenick);
839 static void cmd_lock(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
846 if(!strncmp(args, "EXTENDEDPROTOCOL", 16))
848 if((p = strchr(args, ' ')) != NULL)
853 qstrf(sk, "$Supports UserCommand NoGetINFO NoHello UserIP2 TTHSearch GetZBlock |");
855 qstrf(sk, "$Supports UserCommand NoGetINFO NoHello UserIP2 TTHSearch");
856 if(!confgetint("dc", "hidedeflate"))
857 qstr(sk, " GetZBlock");
861 key = dcmakekey(args);
862 qstrf(sk, "$Key %s|", key);
864 hubhandleaction(sk, fn, cmd, args);
867 static void cmd_hubname(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
873 if(hub->nativename == NULL)
874 free(hub->nativename);
875 hub->nativename = sstrdup(args);
876 buf = icmbstowcs(args, hub->charset);
877 fnetsetname(fn, (buf == NULL)?L"Hubname conv error":buf);
880 hubhandleaction(sk, fn, cmd, args);
883 static void cmd_hello(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
889 if((nick = icmbstowcs(args, hub->charset)) == NULL)
891 if(strcmp(args, hub->nativenick) && (fnetfindpeer(fn, nick) == NULL))
892 fnetaddpeer(fn, nick, nick);
894 hubhandleaction(sk, fn, cmd, args);
897 static void cmd_quit(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
900 struct fnetpeer *peer;
904 if((nick = icmbstowcs(args, hub->charset)) == NULL)
906 if((peer = fnetfindpeer(fn, nick)) != NULL)
909 hubhandleaction(sk, fn, cmd, args);
912 static void cmd_nicklist(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
917 struct fnetpeer *peer;
920 for(peer = btreeiter(fn->peers); peer != NULL; peer = btreeiter(NULL))
921 peer->flags.b.delete = 1;
922 while((p = strstr(args, "$$")) != NULL)
925 if((buf = icmbstowcs(args, hub->charset)) != NULL)
927 if((peer = fnetfindpeer(fn, buf)) == NULL)
928 peer = fnetaddpeer(fn, buf, buf);
930 peer->flags.b.delete = 0;
932 qstrf(sk, "$GetINFO %s %s|", args, hub->nativenick);
937 hubhandleaction(sk, fn, cmd, args);
940 static void cmd_oplist(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
945 struct fnetpeer *peer;
948 for(peer = btreeiter(fn->peers); peer != NULL; peer = btreeiter(NULL))
949 peer->flags.b.op = 0;
950 while((p = strstr(args, "$$")) != NULL)
953 if((buf = icmbstowcs(args, hub->charset)) != NULL)
955 if((peer = fnetfindpeer(fn, buf)) != NULL)
956 peer->flags.b.op = 1;
961 hubhandleaction(sk, fn, cmd, args);
964 static void cmd_myinfo(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
967 wchar_t *buf, *wp, *wp2;
969 struct fnetpeer *peer;
974 if(strncmp(p, "$ALL ", 5))
977 if((p2 = strchr(p, ' ')) == NULL)
980 if((buf = icmbstowcs(p, hub->charset)) == NULL)
982 if((peer = fnetfindpeer(fn, buf)) == NULL)
983 peer = fnetaddpeer(fn, buf, buf);
986 if((p2 = strstr(p, "$ $")) == NULL)
989 if((buf = icmbstowcs(p, hub->charset)) == NULL)
991 if((wcslen(buf) > 0) && (buf[wcslen(buf) - 1] == L'>') && ((wp = wcsrchr(buf, L'<')) != NULL))
993 buf[wcslen(buf) - 1] = L'\0';
995 if((wp2 = wcschr(wp, L' ')) != NULL)
998 fnetpeersetstr(peer, L"dc-client", wp);
1002 if((wp2 = wcschr(wp, L',')) != NULL)
1006 swprintf(abuf, 10, L"dc-tag-%lc", wp[0]);
1007 fnetpeersetstr(peer, abuf, wp + 2);
1009 } while(wp2 != NULL);
1012 fnetpeersetstr(peer, L"descr", buf);
1015 if((p2 = strchr(p, '$')) == NULL)
1018 if((buf = icmbstowcs(p, hub->charset)) == NULL)
1020 fnetpeersetstr(peer, L"dc-speed", buf);
1023 if((p2 = strchr(p, '$')) == NULL)
1026 if((buf = icmbstowcs(p, hub->charset)) == NULL)
1028 fnetpeersetstr(peer, L"email", buf);
1033 fnetpeersetlnum(peer, L"share", strtoll(p, NULL, 10));
1034 hubhandleaction(sk, fn, cmd, args);
1037 /* I do not implement the fully in that I do not disconnect from the
1038 * old hub. I do this since I believe that if the hub owner really
1039 * wants to get rid of us, then it is his responsibility to disconnect
1041 static void cmd_forcemove(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1044 struct fnetnode *newfn;
1048 if(strchr(args, ':') == NULL)
1050 args = strcpy(smalloc(strlen(args) + 5), args);
1051 strcat(args, ":411");
1056 if((newfn = fnetinitconnect(L"dc", fn->owner, args, NULL)) != NULL)
1058 linkfnetnode(newfn);
1061 hubhandleaction(sk, fn, cmd, args);
1066 static char *getdcpath(struct sharecache *node, size_t *retlen, char *charset)
1071 if(node->parent == NULL)
1073 if(node->parent == shareroot)
1075 if((buf = icwcstombs(node->name, charset)) == NULL)
1078 *retlen = strlen(buf);
1081 if((buf2 = icwcstombs(node->name, charset)) == NULL)
1083 if((buf = getdcpath(node->parent, &len, charset)) == NULL)
1088 len2 = strlen(buf2);
1089 buf = srealloc(buf, len + 1 + len2 + 1);
1091 strcpy(buf + len, buf2);
1092 buf[len + len2] = 0;
1095 *retlen = len + len2;
1101 * This is the main share searching function for Direct Connect
1102 * peers. Feel free to optimize it if you feel the need for it. I
1103 * haven't ever seen it take any noticable CPU time anyway, so I
1104 * haven't felt that need.
1106 * It may feel dubious to just return the directory when all terms are
1107 * satisfied rather than all the files in it, but it really benefits
1108 * everyone: Less cycles used for us, less UDP squelching for active
1109 * searchers, and less bandwidth waste for hubs when serving passive
1112 static void cmd_search(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1117 char *prefix, *infix, *postfix, *buf, *buf2;
1119 struct sockaddr_in addr;
1120 struct sharecache *node;
1121 int minsize, maxsize;
1124 int termnum, satisfied, skipcheck;
1125 int level, tersat[32];
1130 if((p = strchr(args, ' ')) == NULL)
1134 memset(terms, 0, sizeof(terms));
1135 prefix = infix = postfix = NULL;
1139 if(!strncmp(args, "Hub:", 4))
1141 if(!strcmp(cmd, "$MultiSearch"))
1143 if(!strcmp(args + 4, hub->nativenick))
1145 prefix = sprintf2("$SR %s ", hub->nativenick);
1146 infix = sprintf2(" %i/%i\005", slotsleft(), confgetint("transfer", "slots"));
1147 postfix = sprintf2(" (%s)\005%s|", formataddress(hub->sk->remote, hub->sk->remotelen), args + 4);
1151 if((p2 = strchr(args, ':')) == NULL)
1154 addr.sin_family = AF_INET;
1155 if(!inet_aton(args, &addr.sin_addr))
1157 addr.sin_port = htons(atoi(p2));
1158 prefix = sprintf2("$SR %s ", hub->nativenick);
1159 infix = sprintf2(" %i/%i\005", slotsleft(), confgetint("transfer", "slots"));
1160 postfix = sprintf2(" (%s)|", formataddress(hub->sk->remote, hub->sk->remotelen));
1161 netdgramconn(dsk = netdupsock(udpsock), (struct sockaddr *)&addr, sizeof(addr));
1164 minsize = maxsize = -1;
1173 if((*(p++) == 'T') && (minsize == 0))
1180 if((p2 = strchr(p, '?')) == NULL)
1195 if((*p2 == 0) || (*p2 == '$'))
1203 if(!dotth && !strncmp(p, "TTH:", 4))
1206 if(((buf = base32decode(p + 4, &buflen)) == NULL) || (buflen != 24))
1211 memcpy(hashtth, buf, 24);
1214 if((terms[termnum] = icmbstowcs(p, hub->charset)) != NULL)
1225 node = shareroot->child;
1227 for(i = 0; i < termnum; i++)
1233 if(node->f.b.type == FILE_REG)
1235 if((minsize >= 0) && (node->size < minsize))
1237 if((maxsize >= 0) && (node->size > maxsize))
1240 if(!skipcheck && dotth)
1242 if((node->f.b.type != FILE_REG) || (node->f.b.hastth && memcmp(hashtth, node->hashtth, 24)))
1247 for(i = 0; i < termnum; i++)
1251 if(wcsexists(node->name, terms[i]))
1255 } else if(node->child == NULL) {
1260 if(!skipcheck && (satisfied == termnum))
1262 /* Use DCCHARSET in $Get paths until further researched... */
1263 if((buf = getdcpath(node, NULL, DCCHARSET)) != NULL)
1265 if(node->f.b.hastth)
1267 buf2 = base32encode(node->hashtth, 24);
1268 qstrf(dsk, "%s%s\005%ji%sTTH:%.39s%s", prefix, buf, (intmax_t)node->size, infix, buf2, postfix);
1271 qstrf(dsk, "%s%s\005%ji%s%s%s", prefix, buf, (intmax_t)node->size, infix, hub->nativename, postfix);
1276 if((!skipcheck && (satisfied == termnum)) || (node->child == NULL))
1278 while(node->next == NULL)
1280 if((node = node->parent) == shareroot)
1284 if(node == shareroot)
1286 for(i = 0; i < termnum; i++)
1288 if(tersat[i] >= level)
1301 hubhandleaction(sk, fn, cmd, args);
1312 for(i = 0; (i < 32) && (terms[i] != NULL); i++)
1316 static void cmd_connecttome(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1320 struct socket *newsk;
1321 struct sockaddr_in addr;
1324 if((p = strchr(args, ' ')) == NULL)
1327 if(strcmp(args, hub->nativenick))
1329 addr.sin_family = AF_INET;
1331 if((p = strchr(args, ':')) == NULL)
1334 addr.sin_port = htons(atoi(p));
1335 if(!inet_aton(args, &addr.sin_addr))
1337 newsk = netcsconn((struct sockaddr *)&addr, sizeof(addr), (void (*)(struct socket *, int, void *))peerconnect, fn);
1339 hubhandleaction(sk, fn, cmd, args);
1342 static void sendctm(struct socket *sk, char *nick)
1344 struct sockaddr *addr;
1349 if(sockgetremotename2(tcpsock, sk, &addr, &addrlen) < 0)
1351 if(addr->sa_family == AF_INET)
1352 qstrf(sk, "$ConnectToMe %s %s|", nick, formataddress(addr, addrlen));
1354 flog(LOG_WARNING, "Direct Connect TCP socket is suddenly not AF_INET, but %i", addr->sa_family);
1358 static void cmd_revconnecttome(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1364 if((p = strchr(args, ' ')) == NULL)
1367 if(strcmp(p, hub->nativenick))
1370 expectpeer(args, fn);
1371 hubhandleaction(sk, fn, cmd, args);
1374 static void cmd_getnetinfo(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1377 struct fnetnode *node;
1382 for(node = fnetnodes; node != NULL; node = node->next)
1384 if(node->state == FNN_EST)
1387 qstrf(sk, "$NetInfo %i$%i$%c$0|", confgetint("transfer", "slots"), numhubs, (tcpsock == NULL)?'P':'A');
1388 hubhandleaction(sk, fn, cmd, args);
1391 static void cmd_to(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1398 if((p2 = strchr(p, ' ')) == NULL)
1402 if((p2 = strchr(p, ' ')) == NULL)
1405 if(strcmp(p, "From:"))
1408 if((p2 = strstr(p, " $")) == NULL)
1412 hubrecvchat(hub->sk, fn, p, p2);
1413 hubhandleaction(sk, fn, cmd, args);
1416 static void cmd_sr(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1420 char *nick, *filename, *hubname;
1425 wchar_t *wnick, *wfile;
1429 if((p2 = strchr(p, ' ')) == NULL)
1434 if((p2 = strchr(p, 5)) == NULL)
1438 if((p2 = strchr(p, ' ')) == NULL)
1441 size = strtoll(p, NULL, 10);
1443 if((p2 = strchr(p, '/')) == NULL)
1448 if((p2 = strchr(p, 5)) == NULL)
1452 if((p2 = strstr(p, " (")) == NULL)
1455 if((wnick = icmbstowcs(nick, hub->charset)) == NULL)
1457 /* Use DCCHARSET in $Get paths until further researched... */
1458 if((wfile = nmdc2path(filename, DCCHARSET)) == NULL)
1463 sr = newsrchres(&dcnet, wfile, wnick);
1464 if(sr->peernick != NULL)
1466 sr->peernick = swcsdup(wnick);
1471 if(!strncmp(hubname, "TTH:", 4))
1473 if((buf = base32decode(hubname + 4, &buflen)) != NULL)
1476 sr->hash = newhash(L"TTH", 24, buf);
1480 getfnetnode(sr->fn = fn);
1483 hubhandleaction(sk, fn, cmd, args);
1486 static void cmd_usercommand(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1488 /* Do nothing for now. */
1491 static void cmd_getpass(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1498 pw = wpfind(fn->args, L"password");
1499 if((pw == NULL) || ((mbspw = icwcstombs(pw, hub->charset)) == NULL))
1504 qstrf(sk, "$MyPass %s|", mbspw);
1506 fn->regstatus = FNNS_REG;
1507 hubhandleaction(sk, fn, cmd, args);
1510 static void cmd_logedin(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1515 fn->regstatus = FNNS_OP;
1516 hubhandleaction(sk, fn, cmd, args);
1519 static void cmd_hubsupports(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1525 size_t arrsize, arrdata;
1528 if(hub->supports != NULL)
1530 for(i = 0; hub->supports[i] != NULL; i++)
1531 free(hub->supports[i]);
1532 free(hub->supports);
1535 arrsize = arrdata = 0;
1539 if((p2 = strchr(p, ' ')) != NULL)
1543 addtobuf(arr, sstrdup(p));
1544 } while((p = p2) != NULL);
1545 addtobuf(arr, NULL);
1546 hub->supports = arr;
1549 static void cmd_mynick(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1551 struct dcexppeer *expect;
1554 if(peer->nativename != NULL)
1555 free(peer->nativename);
1556 peer->nativename = sstrdup(args);
1557 if(peer->wcsname != NULL)
1558 free(peer->wcsname);
1559 if((peer->wcsname = icmbstowcs(peer->nativename, peer->charset)) == NULL)
1566 for(expect = expected; expect != NULL; expect = expect->next)
1568 if(!strcmp(expect->nick, args))
1575 hub = expect->fn->data;
1576 peer->fn = expect->fn;
1577 getfnetnode(peer->fn);
1578 peer->dcppemu = hub->dcppemu;
1579 freeexppeer(expect);
1584 static void cmd_direction(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1588 struct transfer *transfer;
1590 if((p = strchr(args, ' ')) == NULL)
1593 if(!strcmp(args, "Upload"))
1595 if(!strcmp(args, "Download"))
1599 if((peer->transfer == NULL) || (mydir != peer->direction))
1604 if(peer->direction == TRNSD_DOWN)
1607 if(peer->wcsname == NULL)
1612 peer->direction = mydir;
1613 if(peer->direction == TRNSD_UP)
1615 if(confgetint("transfer", "ulquota") && hasupload(&dcnet, peer->wcsname))
1620 transfer = newupload(peer->fn, &dcnet, peer->wcsname, &dctransfer, peer);
1622 if((transfer = finddownload(peer->wcsname)) == NULL)
1627 transferattach(transfer, &dctransfer, peer);
1628 transfersetstate(transfer, TRNS_HS);
1630 transfersetnick(transfer, peer->wcsname);
1631 peer->transfer = transfer;
1634 qstrf(sk, "$Direction %s %i|", (peer->direction == TRNSD_UP)?"Upload":"Download", rand() % 10000);
1635 if(peer->key != NULL)
1636 qstrf(sk, "$Key %s|", peer->key);
1637 if(peer->direction == TRNSD_DOWN)
1642 static void cmd_peerlock(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1645 struct transfer *transfer;
1647 if((p = strchr(args, ' ')) == NULL)
1650 if(!strncmp(args, "EXTENDEDPROTOCOL", 16))
1652 key = dcmakekey(args);
1655 if(peer->wcsname == NULL)
1664 if((transfer = finddownload(peer->wcsname)) == NULL)
1666 if(confgetint("transfer", "ulquota") && hasupload(&dcnet, peer->wcsname))
1671 peer->direction = TRNSD_UP;
1672 transfer = newupload(peer->fn, &dcnet, peer->wcsname, &dctransfer, peer);
1674 peer->direction = TRNSD_DOWN;
1675 transferattach(transfer, &dctransfer, peer);
1676 transfersetstate(transfer, TRNS_HS);
1678 transfersetnick(transfer, peer->wcsname);
1679 peer->transfer = transfer;
1680 qstrf(sk, "$Direction %s %i|", (peer->direction == TRNSD_UP)?"Upload":"Download", rand() % 10000);
1681 qstrf(sk, "$Key %s|", key);
1684 if(peer->key != NULL)
1690 static void cmd_key(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1695 static void startdl(struct dcpeer *peer)
1697 if(peer->timeout != NULL)
1698 canceltimer(peer->timeout);
1699 peer->state = PEER_TRNS;
1700 transferstartdl(peer->transfer, peer->sk);
1701 peer->sk->readcb = (void (*)(struct socket *, void *))transread;
1702 peer->sk->errcb = (void (*)(struct socket *, int, void *))transerr;
1705 static void startul(struct dcpeer *peer)
1707 if(peer->timeout != NULL)
1708 canceltimer(peer->timeout);
1709 peer->state = PEER_TRNS;
1710 transferstartul(peer->transfer, peer->sk);
1711 peer->sk->writecb = (void (*)(struct socket *, void *))transwrite;
1714 static void cmd_filelength(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1717 struct transfer *transfer;
1719 if(peer->transfer == NULL)
1724 size = strtoll(args, NULL, 10);
1725 if(peer->transfer->size != size)
1727 transfersetsize(peer->transfer, size);
1728 transfer = peer->transfer;
1730 resettransfer(transfer);
1731 trytransferbypeer(transfer->fnet, transfer->peerid);
1735 qstr(peer->sk, "$Send|");
1738 static void cmd_error(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1740 if(peer->fetchingtthl)
1742 peer->fetchingtthl = 0;
1747 if((peer->transfer != NULL) && (peer->transfer->dir == TRNSD_DOWN))
1749 transferseterror(peer->transfer, TRNSE_NOTFOUND);
1750 resettransfer(peer->transfer);
1756 static void cmd_maxedout(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1758 if((peer->transfer != NULL) && (peer->transfer->dir == TRNSD_DOWN))
1760 transferseterror(peer->transfer, TRNSE_NOSLOTS);
1761 resettransfer(peer->transfer);
1774 {"MyList.DcLst", &hmlistname, updatehmlist},
1775 {"files.xml", &xmllistname, updatexmllist},
1776 {"files.xml.bz2", &xmlbz2listname, updatexmlbz2list},
1780 static int openfilelist(char *name)
1785 for(i = 0; lists[i].name != NULL; i++)
1787 if(!strcmp(name, lists[i].name))
1791 if(lists[i].name == NULL)
1794 if((*lists[i].file == NULL) || ((fd = open(*lists[i].file, O_RDONLY)) < 0))
1796 if((fd < 0) && ((*lists[i].file == NULL) || ((fd = open(*lists[i].file, O_RDONLY)) < 0)))
1799 flog(LOG_ERR, "could not open filelist tempfile: %s", strerror(errno));
1806 static struct sharecache *findbytth(char *tth32)
1810 struct sharecache *node;
1812 if((buf = base32decode(tth32, &buflen)) == NULL)
1819 for(node = shareroot->child; node != NULL; node = nextscnode(node))
1821 if(node->f.b.hastth && !memcmp(node->hashtth, buf, 24))
1828 static struct sharecache *resdcpath(char *path, char *charset, char sep)
1830 struct sharecache *node;
1837 if((p2 = strchr(p, sep)) != NULL)
1839 if((node = findcache(node, icsmbstowcs(p, charset, L""))) == NULL)
1846 static void cmd_get(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1851 struct sharecache *node;
1852 struct socket *lesk;
1856 if(peer->transfer == NULL)
1861 if((p = strchr(args, '$')) == NULL)
1867 if((offset = (strtoll(p, NULL, 10) - 1)) < 0)
1872 if(((fd = openfilelist(args)) < 0) && (errno != 0))
1874 qstr(sk, "$Error Could not send file list|");
1877 } else if(fd >= 0) {
1878 if((buf2 = nmdc2path(args, DCCHARSET)) != NULL) {
1879 transfersetpath(peer->transfer, buf2);
1882 peer->transfer->flags.b.minislot = 1;
1886 /* Use DCCHARSET in $Get paths until further researched... */
1887 if((node = resdcpath(args, DCCHARSET, '\\')) == NULL)
1889 qstrf(sk, "$Error File not in share|");
1893 if((fd = opensharecache(node)) < 0)
1895 qstrf(sk, "$Error %s|", strerror(errno));
1899 buf = getfspath(node);
1900 if((buf2 = icsmbstowcs(buf, NULL, NULL)) == NULL)
1901 flog(LOG_WARNING, "could not convert native path into a wcs (%s): %s", buf, strerror(errno));
1903 transfersetpath(peer->transfer, buf2);
1906 if(fstat(fd, &sb) < 0)
1909 flog(LOG_WARNING, "could not stat file %ls: %s", node->name, strerror(errno));
1910 qstrf(sk, "$Error|");
1914 if(sb.st_size < 65536)
1915 peer->transfer->flags.b.minislot = 1;
1916 if(!peer->transfer->flags.b.minislot && (slotsleft() < 1)) {
1918 qstr(sk, "$MaxedOut|");
1922 if((offset != 0) && (lseek(fd, offset, SEEK_SET) < 0))
1925 qstrf(sk, "$Error Offset out of range|");
1929 lesk = wrapsock(fd);
1930 transferprepul(peer->transfer, sb.st_size, offset, -1, lesk);
1932 qstrf(sk, "$FileLength %ji|", (intmax_t)peer->transfer->size);
1935 static void cmd_send(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1937 if(peer->transfer == NULL)
1942 if(peer->transfer->localend == NULL)
1951 static void cmd_supports(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1956 size_t arrsize, arrdata;
1958 if(peer->supports != NULL)
1960 for(i = 0; peer->supports[i] != NULL; i++)
1961 free(peer->supports[i]);
1962 free(peer->supports);
1965 arrsize = arrdata = 0;
1969 if((p2 = strchr(p, ' ')) != NULL)
1973 addtobuf(arr, sstrdup(p));
1974 } while((p = p2) != NULL);
1975 addtobuf(arr, NULL);
1976 peer->supports = arr;
1979 static void cmd_getblock(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1983 off_t start, numbytes;
1984 char *charset, *buf;
1986 struct sharecache *node;
1988 struct socket *lesk;
1990 if(peer->transfer == NULL)
1996 if((p2 = strchr(p, ' ')) == NULL)
2002 start = strtoll(p, NULL, 10);
2004 if((p2 = strchr(p, ' ')) == NULL)
2010 numbytes = strtoll(p, NULL, 10);
2012 if(!strcmp(cmd, "$UGetBlock") || !strcmp(cmd, "$UGetZBlock"))
2015 /* Use DCCHARSET in $Get paths until further researched... */
2016 charset = DCCHARSET;
2017 if(!strcmp(cmd, "$GetZBlock") || !strcmp(cmd, "$UGetZBlock"))
2018 initcompress(peer, CPRS_ZLIB);
2019 if(((fd = openfilelist(p)) < 0) && (errno != 0))
2021 qstr(sk, "$Error Could not send file list|");
2023 } else if(fd >= 0) {
2024 if((buf2 = nmdc2path(args, charset)) != NULL) {
2025 transfersetpath(peer->transfer, buf2);
2028 peer->transfer->flags.b.minislot = 1;
2032 if((node = resdcpath(p, charset, '\\')) == NULL)
2034 qstr(sk, "$Error File not in cache|");
2037 if((fd = opensharecache(node)) < 0)
2039 qstrf(sk, "$Error %s|", strerror(errno));
2042 buf = getfspath(node);
2043 if((buf2 = icsmbstowcs(buf, NULL, NULL)) == NULL)
2044 flog(LOG_WARNING, "could not convert native path into a wcs (%s): %s", buf, strerror(errno));
2046 transfersetpath(peer->transfer, buf2);
2049 if(fstat(fd, &sb) < 0)
2052 flog(LOG_WARNING, "could not stat file %ls: %s", node->name, strerror(errno));
2053 qstr(sk, "$Error|");
2056 if(sb.st_size < 65536)
2057 peer->transfer->flags.b.minislot = 1;
2058 if(!peer->transfer->flags.b.minislot && (slotsleft() < 1)) {
2060 qstr(sk, "$MaxedOut|");
2063 if((start != 0) && ((start >= sb.st_size) || (lseek(fd, start, SEEK_SET) < 0)))
2066 qstr(sk, "$Error Offset out of range|");
2069 if((numbytes < 0) || (start + numbytes > sb.st_size))
2070 numbytes = sb.st_size - start;
2071 lesk = wrapsock(fd);
2072 transferprepul(peer->transfer, sb.st_size, start, start + numbytes, lesk);
2074 qstrf(sk, "$Sending %ji|", (intmax_t)numbytes);
2078 static void cmd_adcget(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2082 off_t start, numbytes;
2083 struct sharecache *node;
2085 struct socket *lesk;
2089 if(peer->transfer == NULL)
2094 if((argv = parseadc(args)) == NULL)
2099 if(parrlen(argv) < 4)
2104 start = strtoll(argv[2], NULL, 10);
2105 numbytes = strtoll(argv[3], NULL, 10);
2108 if(((fd = openfilelist(argv[1])) < 0) && (errno != 0))
2110 qstr(sk, "$Error Could not send file list|");
2112 } else if(fd >= 0) {
2113 if((wbuf = adc2path(argv[1])) != NULL)
2114 transfersetpath(peer->transfer, wbuf);
2115 peer->transfer->flags.b.minislot = 1;
2119 if(!strncmp(argv[1], "TTH/", 4))
2121 if((node = findbytth(argv[1] + 4)) == NULL)
2123 qstr(sk, "$Error File not in cache|");
2127 if((node = resdcpath((argv[1][0] == '/')?(argv[1] + 1):(argv[1]), "UTF-8", '/')) == NULL)
2129 qstr(sk, "$Error File not in cache|");
2133 if((fd = opensharecache(node)) < 0)
2135 qstrf(sk, "$Error %s|", strerror(errno));
2138 buf = getfspath(node);
2139 if((wbuf = icsmbstowcs(buf, NULL, NULL)) == NULL)
2140 flog(LOG_WARNING, "could not convert native path into a wcs (%s): %s", buf, strerror(errno));
2142 transfersetpath(peer->transfer, wbuf);
2145 if(!strcmp(argv[0], "file"))
2147 for(i = 4; argv[i] != NULL; i++)
2149 if(!strcmp(argv[i], "ZL1"))
2150 initcompress(peer, CPRS_ZLIB);
2152 if(fstat(fd, &sb) < 0)
2154 flog(LOG_WARNING, "could not stat file %ls: %s", node->name, strerror(errno));
2155 qstr(sk, "$Error|");
2158 if(sb.st_size < 65536)
2159 peer->transfer->flags.b.minislot = 1;
2160 if(!peer->transfer->flags.b.minislot && (slotsleft() < 1)) {
2161 qstr(sk, "$MaxedOut|");
2164 if((start != 0) && ((start >= sb.st_size) || (lseek(fd, start, SEEK_SET) < 0)))
2166 qstr(sk, "$Error Offset out of range|");
2169 if((numbytes < 0) || (start + numbytes > sb.st_size))
2170 numbytes = sb.st_size - start;
2171 lesk = wrapsock(fd);
2172 transferprepul(peer->transfer, sb.st_size, start, start + numbytes, lesk);
2175 qstr(sk, "$ADCSND");
2176 sendadc(sk, "file");
2177 sendadc(sk, argv[1]);
2178 sendadcf(sk, "%ji", (intmax_t)start);
2179 sendadcf(sk, "%ji", (intmax_t)numbytes);
2180 if(peer->compress == CPRS_ZLIB)
2184 } else if(!strcmp(argv[0], "tthl")) {
2186 * XXX: Implement full TTHL support.
2188 * In the meantime, this is better than nothing, since it at
2189 * least allows fetching of the TTH root if it isn't already
2194 qstr(sk, "$Error no TTHL data for virtual files|");
2197 qstr(sk, "$ADCSND");
2198 sendadc(sk, "tthl");
2199 sendadc(sk, argv[1]);
2203 sockqueue(sk, node->hashtth, 24);
2205 qstr(sk, "$Error Namespace not implemented|");
2215 static void handletthl(struct dcpeer *peer)
2219 while(peer->inbufdata >= 24)
2221 pushtigertree(&peer->tth, peer->inbuf);
2222 memmove(peer->inbuf, peer->inbuf + 24, peer->inbufdata -= 24);
2223 peer->curread += 24;
2225 if(peer->curread >= peer->totalsize)
2227 if(peer->timeout == NULL)
2228 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
2229 peer->state = PEER_CMD;
2230 synctigertree(&peer->tth);
2231 restigertree(&peer->tth, buf);
2232 transfersethash(peer->transfer, newhash(L"TTH", 24, buf));
2237 static void cmd_adcsnd(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2240 off_t start, numbytes;
2242 if(peer->transfer == NULL)
2247 if((argv = parseadc(args)) == NULL)
2252 if(parrlen(argv) < 4)
2257 start = strtoll(argv[2], NULL, 10);
2258 numbytes = strtoll(argv[3], NULL, 10);
2259 if(!strcmp(argv[0], "tthl"))
2261 if((start != 0) || (numbytes % 24 != 0))
2263 /* Weird. Bail out. */
2267 if(peer->timeout != NULL)
2268 canceltimer(peer->timeout);
2269 peer->state = PEER_TTHL;
2270 peer->totalsize = numbytes;
2272 peer->fetchingtthl = 0;
2273 inittigertree(&peer->tth);
2275 } else if(!strcmp(argv[0], "file")) {
2276 if(start != peer->transfer->curpos)
2281 if(start + numbytes != peer->transfer->size)
2283 transfersetsize(peer->transfer, start + numbytes);
2288 if(peer->inbufdata > 0)
2290 sockpushdata(sk, peer->inbuf, peer->inbufdata);
2291 peer->inbufdata = 0;
2292 transread(sk, peer);
2295 /* We certainly didn't request this...*/
2304 static void cmd_sending(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2308 if(peer->transfer == NULL)
2313 numbytes = strtoll(args, NULL, 10);
2314 if(peer->transfer->size - peer->transfer->curpos != numbytes)
2316 transfersetsize(peer->transfer, peer->transfer->curpos + numbytes);
2321 if(peer->inbufdata > 0)
2323 sockpushdata(sk, peer->inbuf, peer->inbufdata);
2324 peer->inbufdata = 0;
2325 transread(sk, peer);
2331 static void cmd_(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
2336 hubhandleaction(sk, fn, cmd, args);
2340 static void cmd_(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2346 static int hubreqconn(struct fnetpeer *peer)
2351 if((peer->fn->state != FNN_EST) || (peer->fn->fnet != &dcnet))
2356 if((hub = peer->fn->data) == NULL)
2361 if((mbsnick = icwcstombs(peer->id, hub->charset)) == NULL)
2362 return(1); /* Shouldn't happen, of course, but who knows... */
2365 sendctm(hub->sk, mbsnick);
2366 expectpeer(mbsnick, peer->fn);
2368 qstrf(hub->sk, "$RevConnectToMe %s %s|", hub->nativenick, mbsnick);
2374 static int hubsendchat(struct fnetnode *fn, int public, wchar_t *to, wchar_t *string)
2377 char *mbsstring, *mbsto;
2380 if((mbsto = icwcstombs(to, hub->charset)) == NULL)
2385 if((mbsstring = icwcstombs(string, hub->charset)) == NULL)
2390 if((strchr(mbsto, '|') != NULL) || (strchr(mbsto, ' ') != NULL))
2397 if(strchr(mbsstring, '|') != NULL)
2408 qstrf(hub->sk, "<%s> %s|", hub->nativenick, mbsstring);
2410 qstrf(hub->sk, "$To: %s From: %s $<%s> %s|", mbsto, hub->nativenick, hub->nativenick, mbsstring);
2413 qstrf(hub->sk, "$To: %s From: %s $<%s> %s|", mbsto, hub->nativenick, hub->nativenick, mbsstring);
2420 static void findsizelimit(struct sexpr *sexpr, int *min, int *max)
2422 int minl, maxl, minr, maxr, retmin, retmax;
2427 findsizelimit(sexpr->l, &minl, &maxl);
2428 findsizelimit(sexpr->r, &minr, &maxr);
2429 retmin = (minl > minr)?minl:minr;
2430 if((maxl != -1) && (maxr != -1))
2431 retmax = (maxl < maxr)?maxl:maxr;
2440 findsizelimit(sexpr->l, &minl, &maxl);
2441 findsizelimit(sexpr->r, &minr, &maxr);
2442 retmin = (minl < minr)?minl:minr;
2443 if((maxl == -1) || (maxr == -1))
2446 retmax = (maxl > maxr)?maxl:maxr;
2449 findsizelimit(sexpr->l, &minl, &maxl);
2450 if((minl == 0) && (maxl == -1)) /* Interval is unspecified */
2454 } else if((minl == 0) && (maxl != -1)) {
2457 } else if((minl != 0) && (maxl == -1)) {
2460 } else { /* This would yield two seperate intervals, which DC cannot handle */
2466 retmax = sexpr->d.n - 1;
2469 retmin = sexpr->d.n;
2470 retmax = sexpr->d.n;
2473 retmin = sexpr->d.n + 1;
2487 static struct hash *findsehash(struct sexpr *sexpr)
2489 struct hash *h1, *h2;
2494 if((h1 = findsehash(sexpr->l)) != NULL)
2496 if((h1 = findsehash(sexpr->r)) != NULL)
2500 if((h1 = findsehash(sexpr->l)) == NULL)
2502 if((h2 = findsehash(sexpr->r)) == NULL)
2508 if(!wcscmp(sexpr->d.hash->algo, L"TTH"))
2509 return(sexpr->d.hash);
2516 static int hubsearch(struct fnetnode *fn, struct search *srch, struct srchfnnlist *ln)
2519 struct wcslist *list, *cur;
2520 char *sstr, *buf, *p;
2521 size_t sstrsize, sstrdata;
2522 struct sockaddr *name;
2524 int minsize, maxsize;
2528 if((fn->state != FNN_EST) || (hub->sk == NULL) || (hub->sk->state != SOCK_EST))
2530 list = findsexprstrs(srch->sexpr);
2531 findsizelimit(srch->sexpr, &minsize, &maxsize);
2532 hash = findsehash(srch->sexpr);
2533 if((minsize != 0) && (maxsize != -1))
2535 /* Choose either minsize or maxsize by trying to determine
2536 * which choice will be most restrictive. The result can be
2537 * approximative at best anyway, so don't try too hard... */
2538 if((50000000 - maxsize) > (minsize - 50000000))
2544 sstrsize = sstrdata = 0;
2545 if((hash != NULL) && (hash->len == 24))
2547 /* Prioritize hash searches above all else */
2548 bufcat(sstr, "F?T?0?9?TTH:", 12);
2549 buf = base32encode(hash->buf, hash->len);
2551 bufcat(sstr, buf, 39);
2556 sizebuf2(sstr, sstrdata + 32, 1);
2557 sstrdata += snprintf(sstr + sstrdata, sstrsize - sstrdata, "T?F?%i?1?", minsize);
2558 } else if(maxsize != -1) {
2559 sizebuf2(sstr, sstrdata + 32, 1);
2560 sstrdata += snprintf(sstr + sstrdata, sstrsize - sstrdata, "T?T?%i?1?", maxsize);
2562 bufcat(sstr, "F?F?0?1?", 8);
2566 for(cur = list; cur != NULL; cur = cur->next)
2568 /* Use DCCHARSET in $Get paths until further researched... */
2569 if((buf = icwcstombs(cur->str, DCCHARSET)) == NULL)
2571 /* Can't find anything anyway if the search expression
2572 * requires characters outside DC's charset. There's
2573 * nothing technically wrong with the search itself,
2574 * however, so return success. This should be
2575 * considered as an optimization. */
2582 addtobuf(sstr, '$');
2584 * It probably doesn't hurt if buf contains any extra
2585 * dollar signs - it will just result in extra search
2586 * terms, and the extraneous results will be filtered by
2587 * the search layer anyway. It hurts if it contains any
2588 * pipes, though, so let's sell them for money.
2590 for(p = buf; *p; p++)
2595 bufcat(sstr, buf, strlen(buf));
2599 /* Will match all files... :-/ */
2600 addtobuf(sstr, '.');
2606 if(sockgetremotename2(udpsock, hub->sk, &name, &namelen) < 0)
2608 flog(LOG_WARNING, "cannot get address of UDP socket");
2610 qstrf(hub->sk, "$Search %s %s|", formataddress(name, namelen), sstr);
2614 qstrf(hub->sk, "$Search Hub:%s %s|", hub->nativenick, sstr);
2618 fn->lastsrch = time(NULL);
2626 #define cc(c) ((void (*)(struct socket *, void *, char *, char *))(c))
2627 static struct command hubcmds[] =
2629 {"$Lock", cc(cmd_lock)},
2630 {"$HubName", cc(cmd_hubname)},
2631 {"$Hello", cc(cmd_hello)},
2632 {"$Quit", cc(cmd_quit)},
2633 {"$NickList", cc(cmd_nicklist)},
2634 {"$OpList", cc(cmd_oplist)},
2635 {"$MyINFO", cc(cmd_myinfo)},
2636 {"$ForceMove", cc(cmd_forcemove)},
2637 {"$Search", cc(cmd_search), .limit = 100},
2638 {"$MultiSearch", cc(cmd_search), .limit = 50},
2639 {"$ConnectToMe", cc(cmd_connecttome), .limit = 200},
2640 {"$RevConnectToMe", cc(cmd_revconnecttome), .limit = 500},
2641 {"$GetNetInfo", cc(cmd_getnetinfo)},
2642 {"$To:", cc(cmd_to)},
2643 {"$SR", cc(cmd_sr)},
2644 {"$UserCommand", cc(cmd_usercommand)},
2645 {"$GetPass", cc(cmd_getpass)},
2646 {"$LogedIn", cc(cmd_logedin)}, /* sic */
2647 {"$Supports", cc(cmd_hubsupports)},
2651 static struct command peercmds[] =
2653 {"$MyNick", cc(cmd_mynick)},
2654 {"$Lock", cc(cmd_peerlock)},
2655 {"$Direction", cc(cmd_direction)},
2656 {"$Key", cc(cmd_key)},
2657 {"$FileLength", cc(cmd_filelength)},
2658 {"$Error", cc(cmd_error)},
2659 {"$MaxedOut", cc(cmd_maxedout)},
2660 {"$Get", cc(cmd_get)},
2661 {"$Send", cc(cmd_send)},
2662 {"$Supports", cc(cmd_supports)},
2663 {"$GetBlock", cc(cmd_getblock)},
2664 {"$UGetBlock", cc(cmd_getblock)},
2665 {"$GetZBlock", cc(cmd_getblock)},
2666 {"$UGetZBlock", cc(cmd_getblock)},
2667 {"$ADCGET", cc(cmd_adcget)},
2668 {"$ADCSND", cc(cmd_adcsnd), .stop = 1},
2669 {"$Sending", cc(cmd_sending), .stop = 1},
2674 static void dctransdetach(struct transfer *transfer, struct dcpeer *peer)
2676 CBUNREG(transfer, trans_filterout, peer);
2677 peer->transfer = NULL;
2681 static void dctransgotdata(struct transfer *transfer, struct dcpeer *peer)
2685 unsigned char outbuf[1024];
2689 if((peer->state == PEER_TRNS) || (peer->state == PEER_SYNC))
2691 if(sockqueuesize(peer->sk) < 65536)
2693 if((buf = transfergetdata(transfer, &bufsize)) != NULL)
2695 if(peer->compress == CPRS_NONE)
2697 sockqueue(peer->sk, buf, bufsize);
2698 } else if(peer->compress == CPRS_ZLIB) {
2699 cstr = peer->cprsdata;
2700 cstr->next_in = buf;
2701 cstr->avail_in = bufsize;
2702 while(cstr->avail_in > 0)
2704 cstr->next_out = outbuf;
2705 cstr->avail_out = sizeof(outbuf);
2706 if((ret = deflate(cstr, 0)) != Z_OK)
2708 flog(LOG_WARNING, "bug? deflate() did not return Z_OK (but rather %i)", ret);
2712 sockqueue(peer->sk, outbuf, sizeof(outbuf) - cstr->avail_out);
2717 if(peer->state == PEER_SYNC)
2719 if(peer->compress == CPRS_ZLIB)
2721 cstr = peer->cprsdata;
2722 cstr->next_in = NULL;
2726 cstr->next_out = outbuf;
2727 cstr->avail_out = sizeof(outbuf);
2728 ret = deflate(cstr, Z_FINISH);
2729 if((ret != Z_OK) && (ret != Z_STREAM_END))
2731 flog(LOG_WARNING, "bug? deflate(Z_FINISH) did not return Z_OK (but rather %i)", ret);
2735 sockqueue(peer->sk, outbuf, sizeof(outbuf) - cstr->avail_out);
2736 } while(ret != Z_STREAM_END);
2742 if(peer->timeout == NULL)
2743 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
2744 peer->state = PEER_CMD;
2746 transfersetstate(transfer, TRNS_HS);
2747 socksettos(peer->sk, confgetint("fnet", "fnptos"));
2748 transfer->flags.b.minislot = 0;
2749 peer->sk->writecb = NULL;
2756 static void dctransendofdata(struct transfer *transfer, struct dcpeer *peer)
2758 peer->state = PEER_SYNC;
2759 dctransgotdata(transfer, peer);
2762 static void dcwantdata(struct transfer *transfer, struct dcpeer *peer)
2764 if(transferdatasize(transfer) < 65536)
2765 peer->sk->ignread = 0;
2768 static void transread(struct socket *sk, struct dcpeer *peer)
2772 struct transfer *transfer;
2774 if((buf = sockgetinbuf(sk, &bufsize)) == NULL)
2776 if(peer->transfer == NULL)
2782 transferputdata(peer->transfer, buf, bufsize);
2784 if(peer->transfer->curpos >= peer->transfer->size)
2786 transfer = peer->transfer;
2787 transferdetach(transfer);
2788 transferendofdata(transfer);
2791 if(transferdatasize(peer->transfer) > 65535)
2795 static void transerr(struct socket *sk, int err, struct dcpeer *peer)
2797 struct transfer *transfer;
2799 if((transfer = peer->transfer) == NULL)
2804 transferdetach(transfer);
2805 transferendofdata(transfer);
2808 static void transwrite(struct socket *sk, struct dcpeer *peer)
2810 if((peer->state != PEER_TRNS) && (peer->state != PEER_SYNC))
2812 if(peer->transfer == NULL)
2817 dctransgotdata(peer->transfer, peer);
2820 static void udpread(struct socket *sk, void *data)
2822 char *buf, *p, *p2, *hashbuf;
2823 size_t buflen, hashlen;
2824 char *nick, *filename, *hubname;
2825 struct sockaddr_in hubaddr;
2828 struct fnetnode *fn, *myfn;
2831 wchar_t *wnick, *wfile;
2834 if((buf = sockgetinbuf(sk, &buflen)) == NULL)
2836 buf = srealloc(buf, buflen + 1);
2838 if(!strncmp(buf, "$SR ", 4))
2842 if((p2 = strchr(p, ' ')) == NULL)
2850 if((p2 = strchr(p, 5)) == NULL)
2857 if((p2 = strchr(p, ' ')) == NULL)
2863 size = strtoll(p, NULL, 10);
2865 if((p2 = strchr(p, '/')) == NULL)
2873 if((p2 = strchr(p, 5)) == NULL)
2880 if((p2 = strstr(p, " (")) == NULL)
2887 if((p2 = strchr(p, ':')) == NULL)
2893 hubaddr.sin_family = AF_INET;
2894 if(!inet_aton(p, &hubaddr.sin_addr))
2900 if((p2 = strchr(p, ')')) == NULL)
2906 hubaddr.sin_port = htons(atoi(p));
2907 /* Use DCCHARSET in $Get paths until further researched... */
2908 if((wfile = nmdc2path(filename, DCCHARSET)) == NULL)
2915 if(!strncmp(hubname, "TTH:", 4))
2917 if((hashbuf = base32decode(hubname + 4, &hashlen)) != NULL)
2920 hash = newhash(L"TTH", 24, hashbuf);
2924 for(fn = fnetnodes; fn != NULL; fn = fn->next)
2926 if((fn->fnet == &dcnet) && ((hub = fn->data) != NULL))
2928 if((hub->nativename != NULL) && !strcmp(hub->nativename, hubname))
2943 for(fn = fnetnodes; fn != NULL; fn = fn->next)
2945 if((fn->fnet == &dcnet) && ((hub = fn->data) != NULL))
2947 if((hub->sk != NULL) && addreq(hub->sk->remote, (struct sockaddr *)&hubaddr))
2958 if((wnick = icmbstowcs(nick, (hub == NULL)?DCCHARSET:(hub->charset))) == NULL)
2963 sr = newsrchres(&dcnet, wfile, wnick);
2964 if(sr->peernick != NULL)
2966 sr->peernick = swcsdup(wnick);
2972 getfnetnode(sr->fn = myfn);
2981 static void hubread(struct socket *sk, struct fnetnode *fn)
2984 struct command *cmd;
2986 size_t datalen, cnlen;
2989 hub = (struct dchub *)fn->data;
2990 if((newbuf = sockgetinbuf(sk, &datalen)) == NULL)
2992 if(hub->inbufdata > 500000) /* Discard possible malicious data */
2994 sizebuf2(hub->inbuf, hub->inbufdata + datalen, 1);
2995 memcpy(hub->inbuf + hub->inbufdata, newbuf, datalen);
2998 hub->inbufdata += datalen;
2999 while((p - hub->inbuf < hub->inbufdata) && ((p2 = memchr(p, '|', hub->inbufdata - (p - hub->inbuf))) != NULL))
3002 for(cmd = hubcmds; cmd->handler != NULL; cmd++)
3004 cnlen = strlen(cmd->name);
3005 if(!strncmp(p, cmd->name, cnlen) && ((p[cnlen] == ' ') || (p[cnlen] == 0)))
3008 if((cmd->limit == 0) || (hub->queue.size < cmd->limit))
3009 newqcmd(&hub->queue, p);
3012 memmove(hub->inbuf, p, hub->inbufdata -= p - hub->inbuf);
3013 if(hub->queue.size > 1000)
3017 static void huberr(struct socket *sk, int err, struct fnetnode *fn)
3022 static int hubsetnick(struct fnetnode *fn, wchar_t *newnick)
3028 if((buf = icwcstombs(newnick, (hub == NULL)?DCCHARSET:(hub->charset))) == NULL)
3030 if((strchr(buf, ' ') != NULL) || (strchr(buf, '|') != NULL) || (strchr(buf, '$') != NULL))
3035 if(hub == NULL) /* Not yet connected */
3040 if(hub->nativenick != NULL)
3041 free(hub->nativenick);
3042 hub->nativenick = buf;
3046 static struct dchub *newdchub(struct fnetnode *fn)
3053 new = smalloc(sizeof(*new));
3054 memset(new, 0, sizeof(*new));
3056 if(confgetint("dc", "dcppemu"))
3058 if((emu = wpfind(fn->args, L"dcppemu")) != NULL)
3066 if((wcharset = wpfind(fn->args, L"charset")) != NULL)
3068 if((charset = icwcstombs(wcharset, "US-ASCII")) != NULL)
3070 if(!havecharset(charset))
3078 new->charset = charset;
3080 new->charset = sstrdup(DCCHARSET);
3081 if(hubsetnick(fn, fn->mynick))
3082 fnetsetnick(fn, L"DoldaConnectUser-IN");
3083 /* IN as in Invalid Nick */
3087 static struct dcpeer *newdcpeer(struct socket *sk)
3091 new = smalloc(sizeof(*new));
3092 memset(new, 0, sizeof(*new));
3093 new->transfer = NULL;
3096 if(confgetint("dc", "dcppemu"))
3107 static void freedcpeer(struct dcpeer *peer)
3110 struct qcommand *qcmd;
3114 if(peer->next != NULL)
3115 peer->next->prev = peer->prev;
3116 if(peer->prev != NULL)
3117 peer->prev->next = peer->next;
3118 if(peer->transfer != NULL)
3120 if(peer->transfer->dir == TRNSD_UP)
3121 peer->transfer->close = 1;
3122 if(peer->transfer->dir == TRNSD_DOWN)
3123 resettransfer(peer->transfer);
3125 if(peer->timeout != NULL)
3126 canceltimer(peer->timeout);
3127 if(peer->sk->data == peer)
3128 peer->sk->data = NULL;
3129 peer->sk->readcb = NULL;
3130 peer->sk->writecb = NULL;
3131 peer->sk->errcb = NULL;
3134 if(peer->supports != NULL)
3136 for(i = 0; peer->supports[i] != NULL; i++)
3137 free(peer->supports[i]);
3138 free(peer->supports);
3140 if(peer->inbuf != NULL)
3142 if(peer->key != NULL)
3144 if(peer->wcsname != NULL)
3145 free(peer->wcsname);
3146 if(peer->nativename != NULL)
3147 free(peer->nativename);
3148 if(peer->charset != NULL)
3149 free(peer->charset);
3150 if(peer->fn != NULL)
3151 putfnetnode(peer->fn);
3152 while((qcmd = ulqcmd(&peer->queue)) != NULL)
3158 static void hubconnect(struct fnetnode *fn, struct socket *sk)
3162 sk->readcb = (void (*)(struct socket *, void *))hubread;
3163 sk->errcb = (void (*)(struct socket *, int, void *))huberr;
3164 fn->data = hub = newdchub(fn);
3166 getsock(hub->sk = sk);
3170 static void hubdestroy(struct fnetnode *fn)
3174 struct qcommand *qcmd;
3176 hub = (struct dchub *)fn->data;
3178 while((qcmd = ulqcmd(&hub->queue)) != NULL)
3180 if(hub->supports != NULL)
3182 for(i = 0; hub->supports[i] != NULL; i++)
3183 free(hub->supports[i]);
3184 free(hub->supports);
3186 if(hub->nativename != NULL)
3187 free(hub->nativename);
3188 if(hub->nativenick != NULL)
3189 free(hub->nativenick);
3190 if(hub->charset != NULL)
3192 if(hub->inbuf != NULL)
3197 static void hubkill(struct fnetnode *fn)
3201 hub = (struct dchub *)fn->data;
3205 static struct transferiface dctransfer =
3207 .detach = (void (*)(struct transfer *, void *))dctransdetach,
3208 .gotdata = (void (*)(struct transfer *, void *))dctransgotdata,
3209 .endofdata = (void (*)(struct transfer *, void *))dctransendofdata,
3210 .wantdata = (void (*)(struct transfer *, void *))dcwantdata
3213 static struct fnet dcnet =
3216 .connect = hubconnect,
3217 .destroy = hubdestroy,
3219 .setnick = hubsetnick,
3220 .reqconn = hubreqconn,
3221 .sendchat = hubsendchat,
3222 .search = hubsearch,
3225 static void peerread(struct socket *sk, struct dcpeer *peer)
3228 size_t datalen, cnlen;
3229 struct command *cmd;
3231 if((newbuf = sockgetinbuf(sk, &datalen)) == NULL)
3233 sizebuf2(peer->inbuf, peer->inbufdata + datalen, 1);
3234 memcpy(peer->inbuf + peer->inbufdata, newbuf, datalen);
3236 peer->inbufdata += datalen;
3237 if(peer->state == PEER_CMD)
3240 while((peer->inbufdata > 0) && (p = memchr(peer->inbuf, '|', peer->inbufdata)) != NULL)
3243 for(cmd = peercmds; cmd->handler != NULL; cmd++)
3245 cnlen = strlen(cmd->name);
3246 if(!strncmp(peer->inbuf, cmd->name, cnlen) && ((peer->inbuf[cnlen] == ' ') || (peer->inbuf[cnlen] == 0)))
3249 if((cmd->limit == 0) || (peer->queue.size < cmd->limit))
3250 newqcmd(&peer->queue, peer->inbuf);
3251 memmove(peer->inbuf, p, peer->inbufdata -= p - peer->inbuf);
3254 peer->state = PEER_STOP;
3257 if(peer->queue.size > 50)
3261 } else if(peer->state == PEER_TTHL) {
3264 if(peer->inbufdata > 500000)
3268 static void peererror(struct socket *sk, int err, struct dcpeer *peer)
3273 static void peerconnect(struct socket *sk, int err, struct fnetnode *fn)
3275 struct dcpeer *peer;
3285 peer = newdcpeer(sk);
3288 peer->dcppemu = hub->dcppemu;
3289 sk->readcb = (void (*)(struct socket *, void *))peerread;
3290 sk->errcb = (void (*)(struct socket *, int, void *))peererror;
3292 socksettos(sk, confgetint("fnet", "fnptos"));
3294 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
3299 static void peeraccept(struct socket *sk, struct socket *newsk, void *data)
3301 struct dcpeer *peer;
3303 peer = newdcpeer(newsk);
3305 newsk->readcb = (void (*)(struct socket *, void *))peerread;
3306 newsk->errcb = (void (*)(struct socket *, int, void *))peererror;
3308 socksettos(newsk, confgetint("fnet", "fnptos"));
3309 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
3312 static void updatehmlist(void)
3314 int i, lev, ic, ret;
3315 struct sharecache *node;
3316 char *buf, *buf2, numbuf[32];
3317 size_t bufsize, bufdata;
3321 buf = smalloc(bufsize = 65536);
3322 node = shareroot->child;
3327 /* Use DCCHARSET in $Get paths until further researched... */
3328 if((buf2 = icwcstombs(node->name, DCCHARSET)) != NULL)
3330 for(i = 0; i < lev; i++)
3332 bufcat(buf, buf2, strlen(buf2));
3334 if(node->f.b.type == FILE_REG)
3337 sprintf(numbuf, "%ji", (intmax_t)node->size);
3338 bufcat(buf, numbuf, strlen(numbuf));
3345 if((node->child != NULL) && !ic)
3349 } else if(node->next != NULL) {
3352 while(node->next == NULL)
3355 node = node->parent;
3356 if(node == shareroot)
3359 if(node == shareroot)
3364 if(hmlistname != NULL)
3369 hmlistname = sstrdup("/tmp/dc-filelist-hm-XXXXXX");
3370 if((fd = mkstemp(hmlistname)) < 0)
3372 flog(LOG_WARNING, "could not create HM file list tempfile: %s", strerror(errno));
3377 * I do not want to implement a good Huffman encoder, and it's not
3378 * like Huffman encoding actually yields any impressive results
3379 * for DC file lists anyway, so I'll just output a bogus
3380 * tree. Implement a good encoder if you want to.
3382 write(fd, "HE3\r\0", 5);
3383 write(fd, &bufdata, 4);
3385 write(fd, &ibuf, 2);
3387 for(i = 0; i < 256; i++)
3390 write(fd, &ibuf, 1);
3392 for(i = 0; i < 256; i++)
3394 for(buf2 = buf; bufdata > 0;)
3396 if((ret = write(fd, buf2, bufdata)) < 0)
3398 flog(LOG_WARNING, "could not write file list: %s", strerror(errno));
3409 static struct xmlent
3416 /* {L'\'', L"""}, Emulate DC++ escaping by omitting this. */
3420 static wchar_t *escapexml(wchar_t *src)
3422 static wchar_t *buf = NULL;;
3425 size_t bufsize, bufdata;
3431 bufsize = bufdata = 0;
3432 for(; *src != L'\0'; src++)
3435 if((c > 0) && (c < 32))
3437 bufcat(buf, L"&#", 2);
3438 ret = swprintf(nbuf, (sizeof(nbuf) / sizeof(*nbuf)), L"%i", c);
3439 bufcat(buf, nbuf, ret);
3440 addtobuf(buf, L';');
3442 for(ent = entities; ent->ent != NULL; ent++)
3446 bufcat(buf, ent->ent, wcslen(ent->ent));
3450 if(ent->ent == NULL)
3451 addtobuf(buf, *src);
3454 addtobuf(buf, L'\0');
3458 static void updatexmllist(void)
3462 char cidbuf[14], *namebuf;
3464 struct sharecache *node;
3466 if(xmllistname != NULL)
3468 unlink(xmllistname);
3471 xmllistname = sstrdup("/tmp/dc-filelist-dcxml-XXXXXX");
3472 if((fd = mkstemp(xmllistname)) < 0)
3474 flog(LOG_WARNING, "could not create XML file list tempfile: %s", strerror(errno));
3479 if((fs = fdopen(fd, "w")) == NULL)
3481 flog(LOG_WARNING, "could not fdopen XML list fd %i: %s", fd, strerror(errno));
3482 unlink(xmllistname);
3488 fprintf(fs, "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>\r\n");
3489 for(i = 0; i < sizeof(cidbuf) - 1; i++)
3490 cidbuf[i] = (rand() % ('Z' - 'A' + 1)) + 'A';
3492 if(confgetint("dc", "dcppemu"))
3493 fprintf(fs, "<FileListing Version=\"1\" CID=\"%s\" Base=\"/\" Generator=\"DC++ 0.674\">\r\n", cidbuf);
3495 fprintf(fs, "<FileListing Version=\"1\" CID=\"%s\" Base=\"/\" Generator=\"%s\">\r\n", cidbuf, "DoldaConnect" VERSION);
3497 node = shareroot->child;
3501 if((namebuf = icswcstombs(escapexml(node->name), "UTF-8", NULL)) != NULL)
3503 for(i = 0; i < lev; i++)
3505 if(node->child != NULL)
3507 fprintf(fs, "<Directory Name=\"%s\">\r\n", namebuf);
3512 fprintf(fs, "<File Name=\"%s\" Size=\"%ji\"", namebuf, (intmax_t)node->size);
3513 if(node->f.b.hastth)
3515 hashbuf = base32encode(node->hashtth, 24);
3516 fprintf(fs, " TTH=\"%.39s\"", hashbuf);
3519 fprintf(fs, "/>\r\n");
3521 while(node->next == NULL)
3523 node = node->parent;
3524 if(node == shareroot)
3529 for(i = 0; i < lev; i++)
3531 fprintf(fs, "</Directory>\r\n");
3534 if(node == shareroot)
3540 if(confgetint("dc", "dcppemu"))
3541 fprintf(fs, "</FileListing>");
3543 fprintf(fs, "</FileListing>\r\n");
3547 static void updatexmlbz2list(void)
3556 if(xmllistname == NULL)
3558 if((in = fopen(xmllistname, "r")) == NULL)
3560 flog(LOG_WARNING, "could not open XML file list for bzipping: %s", strerror(errno));
3563 if(xmlbz2listname != NULL)
3565 unlink(xmlbz2listname);
3566 free(xmlbz2listname);
3568 xmlbz2listname = sstrdup("/tmp/dc-filelist-dcxmlbz2-XXXXXX");
3569 if((fd = mkstemp(xmlbz2listname)) < 0)
3571 flog(LOG_WARNING, "could not create bzipped XML file list tempfile: %s", strerror(errno));
3572 free(xmlbz2listname);
3573 xmlbz2listname = NULL;
3577 if((real = fdopen(fd, "w")) == NULL)
3579 flog(LOG_WARNING, "could not fdopen bzipped XML list fd %i: %s", fd, strerror(errno));
3581 unlink(xmlbz2listname);
3582 free(xmlbz2listname);
3583 xmlbz2listname = NULL;
3587 out = BZ2_bzWriteOpen(&err, real, 9, 0, 0);
3590 flog(LOG_WARNING, "could not open bzip2 stream from XML list");
3592 unlink(xmlbz2listname);
3593 free(xmlbz2listname);
3594 xmlbz2listname = NULL;
3600 bufdata = fread(buf, 1, sizeof(buf), in);
3601 BZ2_bzWrite(&err, out, buf, bufdata);
3604 BZ2_bzWriteClose(&err, out, 0, NULL, NULL);
3608 static void listtimercb(int cancelled, void *uudata)
3610 listwritetimer = NULL;
3615 static void updatelists(int now)
3617 if((hmlistname == NULL) || (xmllistname == NULL) || (xmlbz2listname == NULL))
3621 if(listwritetimer == NULL)
3622 listwritetimer = timercallback(ntime() + confgetint("cli", "hashwritedelay"), listtimercb, NULL);
3625 if(listwritetimer != NULL)
3626 canceltimer(listwritetimer);
3632 static int shareupdate(unsigned long long uusharesize, void *data)
3638 static char *quotestr(char *str)
3642 size_t bufsize, bufdata;
3644 static char *enc = NULL;
3645 size_t encsize, encdata;
3648 bufsize = bufdata = 0;
3649 for(p = (unsigned char *)str; *p; p++)
3652 bufcat(buf, "\\b", 2);
3654 bufcat(buf, "\\t", 2);
3656 bufcat(buf, "\\n", 2);
3658 bufcat(buf, "\\r", 2);
3660 bufcat(buf, "\\\\", 2);
3664 bprintf(buf, "\\x%02x", *p);
3670 if((wbuf = icmbstowcs((char *)buf, DCCHARSET)) != NULL)
3672 enc = icwcstombs(wbuf, NULL);
3677 encsize = encdata = 0;
3678 for(p = buf; *p; p++) {
3682 bprintf(buf, "\\x%x", *p);
3689 static void logunimpl(char *list, char *cmd, char *args)
3693 if((log = fopen("/tmp/dc-unimpl", "a")) == NULL)
3695 flog(LOG_WARNING, "could not open unimpl log: %s", strerror(errno));
3700 fputs(quotestr(cmd), log);
3704 fputs(quotestr(args), log);
3710 static void dispatchcommand(struct qcommand *qcmd, struct command *cmdlist, struct socket *sk, void *data)
3713 struct command *cmd;
3715 if((p = strchr(qcmd->string, ' ')) != NULL)
3717 for(cmd = cmdlist; cmd->handler != NULL; cmd++)
3719 if(!strcmp(cmd->name, qcmd->string))
3722 if(cmd->handler != NULL)
3724 cmd->handler(sk, data, qcmd->string, p);
3725 } else if(confgetint("dc", "logunimpl")) {
3726 if(cmdlist == hubcmds)
3727 logunimpl("hub", qcmd->string, p);
3728 else if(cmdlist == peercmds)
3729 logunimpl("peer", qcmd->string, p);
3731 logunimpl("other?!", qcmd->string, p);
3735 static int run(void)
3737 struct fnetnode *fn, *nextfn;
3739 struct dcpeer *peer, *nextpeer;
3740 struct qcommand *qcmd;
3745 for(fn = fnetnodes; fn != NULL; fn = nextfn)
3748 if(fn->fnet != &dcnet)
3750 if(fn->data == NULL)
3752 hub = (struct dchub *)fn->data;
3753 while((quota > 0) && ((qcmd = ulqcmd(&hub->queue)) != NULL))
3755 if(*qcmd->string == '$')
3757 if((hub->sk != NULL) && (hub->sk->state == SOCK_EST))
3758 dispatchcommand(qcmd, hubcmds, hub->sk, fn);
3759 } else if(*qcmd->string != 0) {
3760 hubrecvchat(hub->sk, fn, NULL, qcmd->string);
3766 if(hub->queue.size < 1000)
3767 hub->sk->ignread = 0;
3772 for(peer = peers; peer != NULL; peer = peer->next)
3774 while(!peer->close && (quota > 0) && ((qcmd = ulqcmd(&peer->queue)) != NULL))
3776 if(peer->timeout != NULL)
3777 canceltimer(peer->timeout);
3778 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
3779 if(*qcmd->string == '$')
3780 dispatchcommand(qcmd, peercmds, peer->sk, peer);
3785 if((peer->queue.size < 50) && (peer->inbufdata < 500000))
3786 peer->sk->ignread = 0;
3790 for(peer = peers; peer != NULL; peer = nextpeer)
3792 nextpeer = peer->next;
3799 static void preinit(int hup)
3806 static int updateudpport(struct configvar *var, void *uudata)
3808 struct sockaddr_in addr;
3809 struct socket *newsock;
3811 memset(&addr, 0, sizeof(addr));
3812 addr.sin_family = AF_INET;
3813 addr.sin_port = htons(var->val.num);
3814 if((newsock = netcsdgram((struct sockaddr *)&addr, sizeof(addr))) == NULL)
3816 flog(LOG_WARNING, "could not create new DC UDP socket, reverting to old: %s", strerror(errno));
3819 newsock->readcb = udpread;
3826 static int updatetcpport(struct configvar *var, void *uudata)
3828 struct sockaddr_in addr;
3829 struct socket *newsock;
3831 memset(&addr, 0, sizeof(addr));
3832 addr.sin_family = AF_INET;
3833 addr.sin_port = htons(var->val.num);
3834 if((newsock = netcslisten(SOCK_STREAM, (struct sockaddr *)&addr, sizeof(addr), peeraccept, NULL)) == NULL)
3835 flog(LOG_INFO, "could not listen to a remote address, going into passive mode");
3842 static int init(int hup)
3844 struct sockaddr_in addr;
3848 GCBREG(sharechangecb, shareupdate, NULL);
3853 addr.sin_family = AF_INET;
3854 memset(&addr.sin_addr, 0, sizeof(addr.sin_addr));
3855 addr.sin_port = htons(confgetint("dc", "udpport"));
3856 if((udpsock = netcsdgram((struct sockaddr *)&addr, sizeof(addr))) == NULL)
3858 flog(LOG_CRIT, "could not create DC UDP socket: %s", strerror(errno));
3861 udpsock->readcb = udpread;
3862 addr.sin_port = htons(confgetint("dc", "tcpport"));
3863 if((tcpsock = netcslisten(SOCK_STREAM, (struct sockaddr *)&addr, sizeof(addr), peeraccept, NULL)) == NULL)
3864 flog(LOG_INFO, "could not listen to a remote address, going into passive mode");
3865 CBREG(confgetvar("dc", "udpport"), conf_update, updateudpport, NULL, NULL);
3866 CBREG(confgetvar("dc", "tcpport"), conf_update, updatetcpport, NULL, NULL);
3867 CBREG(confgetvar("net", "mode"), conf_update, updatetcpport, NULL, NULL);
3872 static void terminate(void)
3874 if(hmlistname != NULL)
3879 if(xmllistname != NULL)
3881 unlink(xmllistname);
3884 if(xmlbz2listname != NULL)
3886 unlink(xmlbz2listname);
3887 free(xmlbz2listname);
3891 static struct configvar myvars[] =
3893 /** Specifies the share description reported to other DC users. */
3894 {CONF_VAR_STRING, "desc", {.str = L""}},
3895 /** Specifies the speed reported to other DC users. Normal values
3896 * are 28.8Kbps, 33.6Kbps, 56Kbps, Satellite, ISDN, DSL, Cable,
3897 * LAN(T1) or LAN(T3)*/
3898 {CONF_VAR_STRING, "speedstring", {.str = L"LAN(T1)"}},
3899 /** The e-mail address to report to other DC users. */
3900 {CONF_VAR_STRING, "email", {.str = L"spam@spam.org"}},
3901 /** Specifies a specific UDP port to use for DC search results. If
3902 * left unspecified, a port is allocated dynamically. Useful for
3903 * NAT routers (see also the net.visibleipv4 address for those
3905 {CONF_VAR_INT, "udpport", {.num = 0}},
3906 /** Specifies a specific TCP port to use for DC peer
3907 * connections. If left unspecified, a port is allocated
3908 * dynamically. Useful for NAT routers (see also the
3909 * net.visibleipv4 address for those cases). */
3910 {CONF_VAR_INT, "tcpport", {.num = 0}},
3911 /** If set to true, doldacond will do its best to emulate DC++
3912 * (currently v0.674). This should be left off if at all possible,
3913 * since turning it on will violate the rules of most hubs and
3914 * thus give hub owners an actual reason to kick you if it is
3915 * detected. It might be needed for some of the more bone-headed
3916 * hub owners, though. Note that DC++ emulation can also be turned
3917 * on or off for individual hubs, overriding this setting. */
3918 {CONF_VAR_BOOL, "dcppemu", {.num = 0}},
3919 /** Use for debugging. If set to true, doldacond will log all
3920 * unknown commands it receives, and their arguments, to
3921 * /tmp/dc-unimpl. */
3922 {CONF_VAR_BOOL, "logunimpl", {.num = 0}},
3923 /** If set to true, doldacond will hide its support for deflate
3924 * compression of transfers from other clients, so that they will
3925 * not request compressed uploads. Compressed transfers may
3926 * consume a non-trivial amount of CPU time on slower machines. */
3927 {CONF_VAR_BOOL, "hidedeflate", {.num = 0}},
3931 static struct module me =
3940 .terminate = terminate,