2 * Dolda Connect - Modular multiuser Direct Connect-style client
3 * Copyright (C) 2004 Fredrik Tolf <fredrik@dolda2000.com>
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 #include <netinet/in.h>
26 #include <arpa/inet.h>
43 #include "sysevents.h"
48 * The Direct Connect protocol is extremely ugly. Thus, this code must
49 * also be a bit ugly in certain places. Please forgive me. =/
51 * This also means that there might be some pieces of the code that
52 * look completely illogical to you, and you think that you may make
53 * them much neater/better. However, in many cases it might just be
54 * that it's required to cope with some oddity of the protocol, such
55 * as the amazingly ugly delayed key response in the peer protocol.
58 /* I assume this is the correct character set to use for DC,
59 * considering it was developed without i18n support under Windows */
60 #define DCCHARSET "windows-1252"
62 #ifdef DCPP_MASQUERADE
64 * I honestly don't want to pretend being a client that I'm not, but
65 * there are so many hubs that simply do not accept any clients
66 * outside their whitelists, for no obvious reasons, so I feel that I
67 * am left with little choice. Anyhow, as long as I actually support
68 * all the features that my faked DC++ version does, there should be
69 * very little harm done.
72 #define DCIDTAGV "0.674"
73 #define DCIDFULL "DC++ 0.674"
75 #define DCIDTAG "Dolda"
76 #define DCIDTAGV VERSION
77 #define DCIDFULL "DoldaConnect " VERSION
92 void (*handler)(struct socket *sk, void *data, char *cmd, char *args);
98 struct qcommand *next;
105 size_t inbufdata, inbufsize;
106 struct qcommand *queue;
107 int extended, dcppemu;
116 struct dcexppeer *next, *prev;
119 struct timer *expire;
124 struct dcpeer *next, *prev;
128 size_t inbufdata, inbufsize;
129 size_t curread, totalsize;
131 struct timer *timeout;
132 struct qcommand *queue;
133 struct transfer *transfer;
135 int ptclose; /* Close after transfer is complete */
136 int accepted; /* If false, we connected, otherwise, we accepted */
137 int extended, dcppemu;
138 int direction; /* Using the constants from transfer.h */
140 int hascurpos, fetchingtthl, notthl;
141 struct tigertreehash tth;
150 static struct fnet dcnet;
151 static struct transferiface dctransfer;
152 static struct socket *udpsock = NULL;
153 static struct socket *tcpsock = NULL;
154 static struct dcpeer *peers = NULL;
156 static struct dcexppeer *expected = NULL;
157 static char *hmlistname = NULL;
158 static char *xmllistname = NULL;
159 static char *xmlbz2listname = NULL;
160 static struct timer *listwritetimer = NULL;
162 static void peerconnect(struct socket *sk, int err, struct fnetnode *fn);
163 static void freedcpeer(struct dcpeer *peer);
164 static void transread(struct socket *sk, struct dcpeer *peer);
165 static void transerr(struct socket *sk, int err, struct dcpeer *peer);
166 static void transwrite(struct socket *sk, struct dcpeer *peer);
167 static void updatehmlist(void);
168 static void updatexmllist(void);
169 static void updatexmlbz2list(void);
170 static void requestfile(struct dcpeer *peer);
171 static void updatelists(int now);
173 static int reservedchar(unsigned char c)
175 return((c == 0) || (c == 5) || (c == 124) || (c == 96) || (c == 126) || (c == 36));
178 /* Oh, how I despise having to do this... */
179 static char *dcmakekey(char *lock)
185 buf = smalloc(strlen(lock));
188 for(i = 0; lock[i]; i++)
190 buf[i] = lock[i] ^ save;
191 buf[i] = ((buf[i] & 0x0F) << 4) | ((buf[i] & 0xF0) >> 4);
193 if((i != 0) && reservedchar(buf[i]))
198 buf[0] ^= buf[i - 1];
199 if(reservedchar(buf[0]))
203 key = smalloc(len + 1);
205 for(i = 0; lock[i] != 0; i++)
207 if(reservedchar(buf[i]))
208 offset += sprintf(key + offset, "/%%DCN%03i%%/", buf[i]);
210 key[offset++] = buf[i];
217 static char *pathnmdc2adc(char *path)
220 size_t retsize, retdata;
222 if(!strcmp(path, "files.xml") || !strcmp(path, "files.xml.bz2") || !strcmp(path, "MyList.DcLst"))
223 return(sstrdup(path));
225 retsize = retdata = 0;
232 addtobuf(ret, *path);
238 static int isdchash(struct hash *hash)
240 if(wcscmp(hash->algo, L"TTH"))
248 * Uncomment when used!
250 static int hubsupports(struct dchub *hub, char *cap)
254 if(hub->supports == NULL)
256 for(p = hub->supports; *p != NULL; p++)
258 if(!strcasecmp(*p, cap))
265 static int supports(struct dcpeer *peer, char *cap)
269 if(peer->supports == NULL)
271 for(p = peer->supports; *p != NULL; p++)
273 if(!strcasecmp(*p, cap))
279 static void endcompress(struct dcpeer *peer)
281 if(peer->compress == CPRS_ZLIB)
283 deflateEnd(peer->cprsdata);
284 free(peer->cprsdata);
286 peer->compress = CPRS_NONE;
289 static void initcompress(struct dcpeer *peer, int algo)
294 peer->compress = algo;
295 if(algo == CPRS_ZLIB)
297 peer->cprsdata = smalloc(sizeof(z_stream));
298 memset(peer->cprsdata, 0, sizeof(z_stream));
299 if((ret = deflateInit(peer->cprsdata, 3)) != Z_OK)
301 flog(LOG_CRIT, "Aiya! zlib refuses to init (%i)!", ret);
307 static void unquote(wchar_t *in)
311 for(p = in; *p != L'\0'; p++)
315 for(p2 = p + 1; (*p2 != L'\0') && (*p2 != L';') && (*p2 != L'&'); p2++);
322 if(!wcscmp(p + 1, L"amp"))
325 } else if(p[1] == L'#') {
326 nc = ucptowc(wcstol(p + 2, NULL, 10));
335 memmove(p + 1, p2 + 1, (wcslen(p2 + 1) + 1) * sizeof(wchar_t));
340 static void freeexppeer(struct dcexppeer *ep)
343 ep->next->prev = ep->prev;
345 ep->prev->next = ep->next;
350 if(ep->expire != NULL)
351 canceltimer(ep->expire);
355 static void exppeerexpire(int cancelled, struct dcexppeer *ep)
362 static struct dcexppeer *expectpeer(char *nick, struct fnetnode *fn)
364 struct dcexppeer *ep;
366 ep = smalloc(sizeof(*ep));
367 ep->nick = sstrdup(nick);
368 getfnetnode(ep->fn = fn);
369 ep->expire = timercallback(ntime() + 300, (void (*)(int, void *))exppeerexpire, ep);
378 static struct qcommand *newqcmd(struct qcommand **queue, char *string)
380 struct qcommand *new;
382 while(*queue != NULL)
383 queue = &(*queue)->next;
384 new = smalloc(sizeof(*new));
385 new->string = sstrdup(string);
391 static struct qcommand *ulqcmd(struct qcommand **queue)
393 struct qcommand *qcmd;
395 if((qcmd = *queue) == NULL)
401 static void freeqcmd(struct qcommand *qcmd)
407 static void hubrecvchat(struct socket *sk, struct fnetnode *fn, char *from, char *string)
409 wchar_t *chat, *wfrom, *wpeer;
411 struct fnetpeer *peer;
415 end = string + strlen(string);
416 while((p = strchr(string, 13)) != NULL)
417 memmove(p, p + 1, (end-- - p));
420 if((strlen(string) > strlen(from) + 2) && (*string == '<') && !memcmp(string + 1, from, strlen(from)) && (*(string + strlen(from) + 1) == '>'))
421 string += strlen(from) + 2;
422 if((wfrom = icmbstowcs(from, hub->charset)) == NULL)
424 wpeer = swcsdup(wfrom);
430 for(p = string + 1; *p; p++)
432 if((*p == ' ') || (*p == '>'))
440 if((wpeer = icmbstowcs(string + 1, hub->charset)) == NULL)
446 wpeer = swcsdup(L"");
448 if((chat = icmbstowcs(string, hub->charset)) == NULL)
458 if((peer = fnetfindpeer(fn, wfrom)) == NULL) /* Assume public chat */
459 fnethandlechat(fn, 1, wfrom, wpeer, chat);
461 fnethandlechat(fn, 0, wfrom, wpeer, chat);
463 fnethandlechat(fn, 1, L"", wpeer, chat);
471 static void peertimeout(int cancelled, struct dcpeer *peer)
473 peer->timeout = NULL;
479 static void sendadc(struct socket *sk, char *arg)
482 size_t bufsize, bufdata;
485 bufsize = bufdata = 0;
491 bufcat(buf, "\\s", 2);
492 } else if(*arg == '\n') {
493 bufcat(buf, "\\n", 2);
494 } else if(*arg == '\\') {
495 bufcat(buf, "\\\\", 2);
500 sockqueue(sk, buf, bufdata);
504 static void sendadcf(struct socket *sk, char *arg, ...)
510 buf = vsprintf2(arg, args);
518 static char **parseadc(char *args)
521 size_t retbufsize, retbufdata;
523 size_t bufsize, bufdata;
528 retbufsize = retbufdata = bufsize = bufdata = 0;
537 else if(*args != ' ')
541 if((*args == ' ') || (*args == 0))
544 addtobuf(retbuf, buf);
546 bufsize = bufdata = 0;
549 } else if(*args == '\\') {
552 addtobuf(buf, *args);
561 addtobuf(retbuf, NULL);
564 } else if((*args == 's') || (*args == ' ')) {
566 } else if(*args == 'n') {
568 } else if(*args == '\\') {
578 addtobuf(retbuf, NULL);
582 /* Macros useful in command handlers */
583 #define skipspace(s) ({if(((s) = strchr((s), ' ')) == NULL) return; else (s)++;})
584 #define qstr(sk, str) sockqueue(sk, str, strlen(str))
585 #define qstrf(sk, strandargs...) \
588 if((__buf__ = sprintf2(strandargs)) != NULL) { \
589 sockqueue(sk, __buf__, strlen(__buf__)); \
594 static char *tr(char *str, char *trans)
598 for(; *trans; trans += 2)
600 for(p = strchr(str, trans[0]); p != NULL; p = strchr(p, trans[0]))
606 static char *getadcid(struct dcpeer *peer)
613 if(!wcscmp(peer->transfer->path, L"files.xml") || !wcscmp(peer->transfer->path, L"files.xml.bz2") || !wcscmp(peer->transfer->path, L"MyList.DcLst"))
615 if(!isfilelist && (peer->transfer->hash != NULL) && isdchash(peer->transfer->hash) && supports(peer, "tthf"))
617 buf = base32encode(peer->transfer->hash->buf, 24);
618 ret = sprintf2("TTH/%.39s", buf);
621 if((buf = icwcstombs(peer->transfer->path, "UTF-8")) == NULL)
623 ret = pathnmdc2adc(buf);
630 static int trresumecb(struct transfer *transfer, wchar_t *cmd, wchar_t *arg, struct dcpeer *peer)
632 if(!wcscmp(cmd, L"resume"))
636 flog(LOG_WARNING, "filter returned no position for \"resume\" on transfer %i", transfer->id);
639 transfer->curpos = wcstol(arg, NULL, 10);
648 static void sendmynick(struct dcpeer *peer)
654 qstrf(peer->sk, "$MyNick %s|", icswcstombs(confgetstr("cli", "defnick"), peer->charset, "DoldaConnectUser-IN"));
656 qstrf(peer->sk, "$MyNick %s|", icswcstombs(fn->mynick, peer->charset, "DoldaConnectUser-IN"));
659 static void sendpeerlock(struct dcpeer *peer)
662 qstrf(peer->sk, "$Lock EXTENDEDPROTOCOLABCABCABCABCABCABC Pk=DCPLUSPLUS0.674ABCABC|");
664 qstrf(peer->sk, "$Lock EXTENDEDPROTOCOLABCABCABCABCABCABC Pk=DOLDA%sABCABCABC|", VERSION);
667 static void sendsupports(struct dcpeer *peer)
670 qstr(peer->sk, "$Supports MiniSlots XmlBZList ADCGet TTHL TTHF GetZBlock ZLIG |");
672 qstr(peer->sk, "$Supports MiniSlots XmlBZList ADCGet TTHL TTHF GetZBlock ZLIG|");
675 static void requestfile(struct dcpeer *peer)
679 if(peer->transfer->size == -1)
681 /* Use DCCHARSET for $Get paths until further researched... */
682 if((buf = icswcstombs(peer->transfer->path, DCCHARSET, NULL)) == NULL)
684 transferseterror(peer->transfer, TRNSE_NOTFOUND);
688 /* The transfer will be restarted later from
689 * cmd_filelength when it detects that the sizes
691 qstrf(peer->sk, "$Get %s$1|", buf);
694 if((peer->transfer->hash == NULL) && !peer->notthl)
696 if(supports(peer, "adcget") && supports(peer, "tthl"))
698 qstr(peer->sk, "$ADCGET");
699 sendadc(peer->sk, "tthl");
700 if((buf = getadcid(peer)) == NULL)
702 transferseterror(peer->transfer, TRNSE_NOTFOUND);
706 sendadc(peer->sk, buf);
708 sendadc(peer->sk, "0");
709 sendadc(peer->sk, "-1");
711 peer->fetchingtthl = 1;
717 if(forkfilter(peer->transfer))
719 flog(LOG_WARNING, "could not fork filter for transfer %i: %s", peer->transfer->id, strerror(errno));
723 CBREG(peer->transfer, trans_filterout, (int (*)(struct transfer *, wchar_t *, wchar_t *, void *))trresumecb, NULL, peer);
726 if(supports(peer, "adcget"))
728 qstr(peer->sk, "$ADCGET");
729 sendadc(peer->sk, "file");
730 if((buf = getadcid(peer)) == NULL)
732 transferseterror(peer->transfer, TRNSE_NOTFOUND);
736 sendadc(peer->sk, buf);
738 sendadcf(peer->sk, "%i", peer->transfer->curpos);
739 sendadcf(peer->sk, "%i", peer->transfer->size - peer->transfer->curpos);
741 } else if(supports(peer, "xmlbzlist")) {
742 if((buf = icswcstombs(peer->transfer->path, "UTF-8", NULL)) == NULL)
744 transferseterror(peer->transfer, TRNSE_NOTFOUND);
748 qstrf(peer->sk, "$UGetBlock %zi %zi %s|", peer->transfer->curpos, peer->transfer->size - peer->transfer->curpos, buf);
750 /* Use DCCHARSET for $Get paths until further researched... */
751 if((buf = icswcstombs(peer->transfer->path, DCCHARSET, NULL)) == NULL)
753 transferseterror(peer->transfer, TRNSE_NOTFOUND);
757 qstrf(peer->sk, "$Get %s$%zi|", buf, peer->transfer->curpos + 1);
761 static void sendmyinfo(struct socket *sk, struct fnetnode *fn)
765 struct fnetnode *cfn;
769 qstrf(sk, "$MyINFO $ALL %s ", hub->nativenick);
770 buf = tr(icswcstombs(confgetstr("dc", "desc"), hub->charset, "Charset_conv_failure"), "$_|_");
771 qstrf(sk, "%s", buf);
773 for(cfn = fnetnodes; cfn != NULL; cfn = cfn->next)
775 if((cfn->state == FNN_EST) || (cfn->state == FNN_HS))
777 if(cfn->regstatus == FNNS_OP)
779 else if(cfn->regstatus == FNNS_REG)
785 qstrf(sk, "<%s V:%s,M:%c,H:%i/%i/%i,S:%i>",
786 (hub->dcppemu)?"++":"Dolda",
787 (hub->dcppemu)?"0.674":VERSION,
788 (tcpsock == NULL)?'P':'A',
790 confgetint("transfer", "slots")
793 buf = tr(icswcstombs(confgetstr("dc", "speedstring"), hub->charset, "Charset_conv_failure"), "$_|_");
794 qstrf(sk, "%s\x01$", buf);
795 buf = tr(icswcstombs(confgetstr("dc", "email"), hub->charset, "Charset_conv_failure"), "$_|_");
796 qstrf(sk, "%s$", buf);
797 qstrf(sk, "%llu$|", sharesize);
800 static void hubhandleaction(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
805 if(!strcmp(cmd, "$Lock"))
807 qstrf(sk, "$ValidateNick %s|", hub->nativenick);
808 } else if(!strcmp(cmd, "$Hello")) {
809 if(fn->state == FNN_HS)
811 qstrf(sk, "$Version 1,0091|");
812 qstrf(sk, "$GetNickList|");
814 fnetsetstate(fn, FNN_EST);
816 qstrf(sk, "$GetINFO %s %s|", args, hub->nativenick);
821 static void cmd_lock(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
828 if(!strncmp(args, "EXTENDEDPROTOCOL", 16))
830 if((p = strchr(args, ' ')) != NULL)
835 qstrf(sk, "$Supports UserCommand NoGetINFO NoHello UserIP2 TTHSearch GetZBlock |");
837 qstrf(sk, "$Supports UserCommand NoGetINFO NoHello UserIP2 TTHSearch GetZBlock|");
839 key = dcmakekey(args);
840 qstrf(sk, "$Key %s|", key);
842 hubhandleaction(sk, fn, cmd, args);
845 static void cmd_hubname(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
851 if(hub->nativename == NULL)
852 free(hub->nativename);
853 hub->nativename = sstrdup(args);
854 buf = icmbstowcs(args, hub->charset);
855 fnetsetname(fn, (buf == NULL)?L"Hubname conv error":buf);
858 hubhandleaction(sk, fn, cmd, args);
861 static void cmd_hello(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
867 if((nick = icmbstowcs(args, hub->charset)) == NULL)
869 if(strcmp(args, hub->nativenick) && (fnetfindpeer(fn, nick) == NULL))
870 fnetaddpeer(fn, nick, nick);
872 hubhandleaction(sk, fn, cmd, args);
875 static void cmd_quit(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
878 struct fnetpeer *peer;
882 if((nick = icmbstowcs(args, hub->charset)) == NULL)
884 if((peer = fnetfindpeer(fn, nick)) != NULL)
887 hubhandleaction(sk, fn, cmd, args);
890 static void cmd_nicklist(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
895 struct fnetpeer *peer, *npeer;
898 for(peer = fn->peers; peer != NULL; peer = peer->next)
899 peer->flags.b.delete = 1;
900 while((p = strstr(args, "$$")) != NULL)
903 if((buf = icmbstowcs(args, hub->charset)) != NULL)
905 if((peer = fnetfindpeer(fn, buf)) == NULL)
906 peer = fnetaddpeer(fn, buf, buf);
908 peer->flags.b.delete = 0;
910 qstrf(sk, "$GetINFO %s %s|", args, hub->nativenick);
914 for(peer = fn->peers; peer != NULL; peer = npeer)
917 if(peer->flags.b.delete)
920 hubhandleaction(sk, fn, cmd, args);
923 static void cmd_oplist(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
928 struct fnetpeer *peer;
931 for(peer = fn->peers; peer != NULL; peer = peer->next)
932 peer->flags.b.op = 0;
933 while((p = strstr(args, "$$")) != NULL)
936 if((buf = icmbstowcs(args, hub->charset)) != NULL)
938 if((peer = fnetfindpeer(fn, buf)) != NULL)
939 peer->flags.b.op = 1;
944 hubhandleaction(sk, fn, cmd, args);
947 static void cmd_myinfo(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
950 wchar_t *buf, *wp, *wp2;
952 struct fnetpeer *peer;
957 if(strncmp(p, "$ALL ", 5))
960 if((p2 = strchr(p, ' ')) == NULL)
963 if((buf = icmbstowcs(p, hub->charset)) == NULL)
965 if((peer = fnetfindpeer(fn, buf)) == NULL)
966 peer = fnetaddpeer(fn, buf, buf);
969 if((p2 = strstr(p, "$ $")) == NULL)
972 if((buf = icmbstowcs(p, hub->charset)) == NULL)
974 if((wcslen(buf) > 0) && (buf[wcslen(buf) - 1] == L'>') && ((wp = wcsrchr(buf, L'<')) != NULL))
976 buf[wcslen(buf) - 1] = L'\0';
978 if((wp2 = wcschr(wp, L' ')) != NULL)
981 fnetpeersetstr(peer, L"dc-client", wp);
985 if((wp2 = wcschr(wp, L',')) != NULL)
989 swprintf(abuf, 10, L"dc-tag-%lc", wp[0]);
990 fnetpeersetstr(peer, abuf, wp + 2);
992 } while(wp2 != NULL);
995 fnetpeersetstr(peer, L"descr", buf);
998 if((p2 = strchr(p, '$')) == NULL)
1001 if((buf = icmbstowcs(p, hub->charset)) == NULL)
1003 fnetpeersetstr(peer, L"dc-speed", buf);
1006 if((p2 = strchr(p, '$')) == NULL)
1009 if((buf = icmbstowcs(p, hub->charset)) == NULL)
1011 fnetpeersetstr(peer, L"email", buf);
1016 fnetpeersetlnum(peer, L"share", strtoll(p, NULL, 10));
1017 hubhandleaction(sk, fn, cmd, args);
1020 /* I do not implement the fully in that I do not disconnect from the
1021 * old hub. I do this since I believe that if the hub owner really
1022 * wants to get rid of us, then it is his responsibility to disconnect
1024 static void cmd_forcemove(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1027 struct fnetnode *newfn;
1031 if(strchr(args, ':') == NULL)
1033 args = strcpy(smalloc(strlen(args) + 5), args);
1034 strcat(args, ":411");
1039 if((newfn = fnetinitconnect(L"dc", fn->owner, args, NULL)) != NULL)
1041 linkfnetnode(newfn);
1044 hubhandleaction(sk, fn, cmd, args);
1049 static char *getdcpath(struct sharecache *node, size_t *retlen, char *charset)
1054 if(node->parent == NULL)
1056 if(node->parent == shareroot)
1058 if((buf = icwcstombs(node->name, charset)) == NULL)
1061 *retlen = strlen(buf);
1064 if((buf2 = icwcstombs(node->name, charset)) == NULL)
1066 if((buf = getdcpath(node->parent, &len, charset)) == NULL)
1071 len2 = strlen(buf2);
1072 buf = srealloc(buf, len + 1 + len2 + 1);
1074 strcpy(buf + len, buf2);
1075 buf[len + len2] = 0;
1078 *retlen = len + len2;
1084 * This is the main share searching function for Direct Connect
1085 * peers. Feel free to optimize it if you feel the need for it. I
1086 * haven't ever seen it take any noticable CPU time anyway, so I
1087 * haven't felt that need.
1089 * It may feel dubious to just return the directory when all terms are
1090 * satisfied rather than all the files in it, but it really benefits
1091 * everyone: Less cycles used for us, less UDP squelching for active
1092 * searchers, and less bandwidth waste for hubs when serving passive
1095 static void cmd_search(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1100 char *prefix, *infix, *postfix, *buf, *buf2;
1102 struct sockaddr_in addr;
1103 struct sharecache *node;
1104 int minsize, maxsize;
1107 int termnum, satisfied, skipcheck;
1108 int level, tersat[32];
1113 if((p = strchr(args, ' ')) == NULL)
1117 memset(terms, 0, sizeof(terms));
1118 prefix = infix = postfix = NULL;
1122 if(!strncmp(args, "Hub:", 4))
1124 if(!strcmp(cmd, "$MultiSearch"))
1126 if(!strcmp(args + 4, hub->nativenick))
1128 prefix = sprintf2("$SR %s ", hub->nativenick);
1129 infix = sprintf2(" %i/%i\005", slotsleft(), confgetint("transfer", "slots"));
1130 postfix = sprintf2(" (%s)\005%s|", formataddress(fn->sk->remote, fn->sk->remotelen), args + 4);
1134 if((p2 = strchr(args, ':')) == NULL)
1137 addr.sin_family = AF_INET;
1138 if(!inet_aton(args, &addr.sin_addr))
1140 addr.sin_port = htons(atoi(p2));
1141 prefix = sprintf2("$SR %s ", hub->nativenick);
1142 infix = sprintf2(" %i/%i\005", slotsleft(), confgetint("transfer", "slots"));
1143 postfix = sprintf2(" (%s)|", formataddress(fn->sk->remote, fn->sk->remotelen));
1144 netdgramconn(dsk = netdupsock(udpsock), (struct sockaddr *)&addr, sizeof(addr));
1147 minsize = maxsize = -1;
1156 if((*(p++) == 'T') && (minsize == 0))
1163 if((p2 = strchr(p, '?')) == NULL)
1178 if((*p2 == 0) || (*p2 == '$'))
1186 if(!dotth && !strncmp(p, "TTH:", 4))
1189 if(((buf = base32decode(p + 4, &buflen)) == NULL) || (buflen != 24))
1194 memcpy(hashtth, buf, 24);
1197 if((terms[termnum] = icmbstowcs(p, hub->charset)) != NULL)
1208 node = shareroot->child;
1210 for(i = 0; i < termnum; i++)
1216 if(node->f.b.type == FILE_REG)
1218 if((minsize >= 0) && (node->size < minsize))
1220 if((maxsize >= 0) && (node->size > maxsize))
1223 if(!skipcheck && dotth)
1225 if((node->f.b.type != FILE_REG) || (node->f.b.hastth && memcmp(hashtth, node->hashtth, 24)))
1230 for(i = 0; i < termnum; i++)
1234 if(wcsexists(node->name, terms[i]))
1238 } else if(node->child == NULL) {
1243 if(!skipcheck && (satisfied == termnum))
1245 /* Use DCCHARSET in $Get paths until further researched... */
1246 if((buf = getdcpath(node, NULL, DCCHARSET)) != NULL)
1248 if(node->f.b.hastth)
1250 buf2 = base32encode(node->hashtth, 24);
1251 qstrf(dsk, "%s%s\005%zi%sTTH:%.39s%s", prefix, buf, node->size, infix, buf2, postfix);
1254 qstrf(dsk, "%s%s\005%zi%s%s%s", prefix, buf, node->size, infix, hub->nativename, postfix);
1259 if((!skipcheck && (satisfied == termnum)) || (node->child == NULL))
1261 while(node->next == NULL)
1263 if((node = node->parent) == shareroot)
1267 if(node == shareroot)
1269 for(i = 0; i < termnum; i++)
1271 if(tersat[i] >= level)
1284 hubhandleaction(sk, fn, cmd, args);
1295 for(i = 0; (i < 32) && (terms[i] != NULL); i++)
1299 static void cmd_connecttome(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1303 struct socket *newsk;
1304 struct sockaddr_in addr;
1307 if((p = strchr(args, ' ')) == NULL)
1310 if(strcmp(args, hub->nativenick))
1312 addr.sin_family = AF_INET;
1314 if((p = strchr(args, ':')) == NULL)
1317 addr.sin_port = htons(atoi(p));
1318 if(!inet_aton(args, &addr.sin_addr))
1320 newsk = netcsconn((struct sockaddr *)&addr, sizeof(addr), (void (*)(struct socket *, int, void *))peerconnect, fn);
1322 hubhandleaction(sk, fn, cmd, args);
1325 static void sendctm(struct socket *sk, char *nick)
1327 struct sockaddr *addr;
1332 if(sockgetremotename2(tcpsock, sk, &addr, &addrlen) < 0)
1334 if(addr->sa_family == AF_INET)
1335 qstrf(sk, "$ConnectToMe %s %s|", nick, formataddress(addr, addrlen));
1337 flog(LOG_WARNING, "Direct Connect TCP socket is suddenly not AF_INET, but %i", addr->sa_family);
1341 static void cmd_revconnecttome(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1347 if((p = strchr(args, ' ')) == NULL)
1350 if(strcmp(p, hub->nativenick))
1353 expectpeer(args, fn);
1354 hubhandleaction(sk, fn, cmd, args);
1357 static void cmd_getnetinfo(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1360 struct fnetnode *node;
1365 for(node = fnetnodes; node != NULL; node = node->next)
1367 if(node->state == FNN_EST)
1370 qstrf(sk, "$NetInfo %i$%i$%c$0|", confgetint("transfer", "slots"), numhubs, (tcpsock == NULL)?'P':'A');
1371 hubhandleaction(sk, fn, cmd, args);
1374 static void cmd_to(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1381 if((p2 = strchr(p, ' ')) == NULL)
1385 if((p2 = strchr(p, ' ')) == NULL)
1388 if(strcmp(p, "From:"))
1391 if((p2 = strstr(p, " $")) == NULL)
1395 hubrecvchat(fn->sk, fn, p, p2);
1396 hubhandleaction(sk, fn, cmd, args);
1399 static void cmd_sr(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1403 char *nick, *filename, *hubname;
1407 wchar_t *wnick, *wfile;
1411 if((p2 = strchr(p, ' ')) == NULL)
1416 if((p2 = strchr(p, 5)) == NULL)
1420 if((p2 = strchr(p, ' ')) == NULL)
1425 if((p2 = strchr(p, '/')) == NULL)
1430 if((p2 = strchr(p, 5)) == NULL)
1434 if((p2 = strstr(p, " (")) == NULL)
1437 if((wnick = icmbstowcs(nick, hub->charset)) == NULL)
1439 /* Use DCCHARSET in $Get paths until further researched... */
1440 if((wfile = icmbstowcs(filename, DCCHARSET)) == NULL)
1445 sr = newsrchres(&dcnet, wfile, wnick);
1446 if(sr->peernick != NULL)
1448 sr->peernick = swcsdup(wnick);
1453 if(!strncmp(hubname, "TTH:", 4))
1455 if((buf = base32decode(hubname + 4, &buflen)) != NULL)
1458 sr->hash = newhash(L"TTH", 24, buf);
1462 getfnetnode(sr->fn = fn);
1465 hubhandleaction(sk, fn, cmd, args);
1468 static void cmd_usercommand(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1470 /* Do nothing for now. */
1473 static void cmd_getpass(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1480 pw = wpfind(fn->args, L"password");
1481 if((pw == NULL) || ((mbspw = icwcstombs(pw, hub->charset)) == NULL))
1486 qstrf(sk, "$MyPass %s|", mbspw);
1488 fn->regstatus = FNNS_REG;
1489 hubhandleaction(sk, fn, cmd, args);
1492 static void cmd_logedin(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1497 fn->regstatus = FNNS_OP;
1498 hubhandleaction(sk, fn, cmd, args);
1501 static void cmd_hubsupports(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1507 size_t arrsize, arrdata;
1510 if(hub->supports != NULL)
1512 for(i = 0; hub->supports[i] != NULL; i++)
1513 free(hub->supports[i]);
1514 free(hub->supports);
1517 arrsize = arrdata = 0;
1521 if((p2 = strchr(p, ' ')) != NULL)
1525 addtobuf(arr, sstrdup(p));
1526 } while((p = p2) != NULL);
1527 addtobuf(arr, NULL);
1528 hub->supports = arr;
1531 static void cmd_mynick(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1533 struct dcexppeer *expect;
1536 if(peer->nativename != NULL)
1537 free(peer->nativename);
1538 peer->nativename = sstrdup(args);
1539 if(peer->wcsname != NULL)
1540 free(peer->wcsname);
1541 if((peer->wcsname = icmbstowcs(peer->nativename, peer->charset)) == NULL)
1548 for(expect = expected; expect != NULL; expect = expect->next)
1550 if(!strcmp(expect->nick, args))
1557 hub = expect->fn->data;
1558 peer->fn = expect->fn;
1559 getfnetnode(peer->fn);
1560 peer->dcppemu = hub->dcppemu;
1561 freeexppeer(expect);
1566 static void cmd_direction(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1570 struct transfer *transfer;
1572 if((p = strchr(args, ' ')) == NULL)
1575 if(!strcmp(args, "Upload"))
1577 if(!strcmp(args, "Download"))
1581 if((peer->transfer == NULL) || (mydir != peer->direction))
1586 if(peer->direction == TRNSD_DOWN)
1589 if(peer->wcsname == NULL)
1594 peer->direction = mydir;
1595 if(peer->direction == TRNSD_UP)
1597 if(confgetint("transfer", "ulquota") && hasupload(&dcnet, peer->wcsname))
1602 transfer = newupload(peer->fn, &dcnet, peer->wcsname, &dctransfer, peer);
1604 if((transfer = finddownload(peer->wcsname)) == NULL)
1609 transferattach(transfer, &dctransfer, peer);
1610 transfersetstate(transfer, TRNS_HS);
1612 transfersetnick(transfer, peer->wcsname);
1613 peer->transfer = transfer;
1616 qstrf(sk, "$Direction %s %i|", (peer->direction == TRNSD_UP)?"Upload":"Download", rand() % 10000);
1617 if(peer->key != NULL)
1618 qstrf(sk, "$Key %s|", peer->key);
1619 if(peer->direction == TRNSD_DOWN)
1624 static void cmd_peerlock(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1627 struct transfer *transfer;
1629 if((p = strchr(args, ' ')) == NULL)
1632 if(!strncmp(args, "EXTENDEDPROTOCOL", 16))
1634 key = dcmakekey(args);
1637 if(peer->wcsname == NULL)
1646 if((transfer = finddownload(peer->wcsname)) == NULL)
1648 if(confgetint("transfer", "ulquota") && hasupload(&dcnet, peer->wcsname))
1653 peer->direction = TRNSD_UP;
1654 transfer = newupload(peer->fn, &dcnet, peer->wcsname, &dctransfer, peer);
1656 peer->direction = TRNSD_DOWN;
1657 transferattach(transfer, &dctransfer, peer);
1658 transfersetstate(transfer, TRNS_HS);
1660 transfersetnick(transfer, peer->wcsname);
1661 peer->transfer = transfer;
1662 qstrf(sk, "$Direction %s %i|", (peer->direction == TRNSD_UP)?"Upload":"Download", rand() % 10000);
1663 qstrf(sk, "$Key %s|", key);
1666 if(peer->key != NULL)
1672 static void cmd_key(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1677 static void startdl(struct dcpeer *peer)
1679 if(peer->timeout != NULL)
1680 canceltimer(peer->timeout);
1681 peer->state = PEER_TRNS;
1682 transferstartdl(peer->transfer, peer->sk);
1683 peer->sk->readcb = (void (*)(struct socket *, void *))transread;
1684 peer->sk->errcb = (void (*)(struct socket *, int, void *))transerr;
1687 static void startul(struct dcpeer *peer)
1689 if(peer->timeout != NULL)
1690 canceltimer(peer->timeout);
1691 peer->state = PEER_TRNS;
1692 transferstartul(peer->transfer, peer->sk);
1693 peer->sk->writecb = (void (*)(struct socket *, void *))transwrite;
1696 static void cmd_filelength(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1699 struct transfer *transfer;
1701 if(peer->transfer == NULL)
1707 if(peer->transfer->size != size)
1709 transfersetsize(peer->transfer, size);
1710 transfer = peer->transfer;
1712 trytransferbypeer(transfer->fnet, transfer->peerid);
1716 qstr(peer->sk, "$Send|");
1719 static void cmd_error(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1721 if(peer->fetchingtthl)
1723 peer->fetchingtthl = 0;
1728 if((peer->transfer != NULL) && (peer->transfer->dir == TRNSD_DOWN))
1730 transferseterror(peer->transfer, TRNSE_NOTFOUND);
1731 resettransfer(peer->transfer);
1737 static void cmd_maxedout(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1739 if((peer->transfer != NULL) && (peer->transfer->dir == TRNSD_DOWN))
1741 transferseterror(peer->transfer, TRNSE_NOSLOTS);
1742 resettransfer(peer->transfer);
1755 {"MyList.DcLst", &hmlistname, updatehmlist},
1756 {"files.xml", &xmllistname, updatexmllist},
1757 {"files.xml.bz2", &xmlbz2listname, updatexmlbz2list},
1761 static int openfilelist(char *name)
1766 for(i = 0; lists[i].name != NULL; i++)
1768 if(!strcmp(name, lists[i].name))
1772 if(lists[i].name == NULL)
1775 if((*lists[i].file == NULL) || ((fd = open(*lists[i].file, O_RDONLY)) < 0))
1777 if((fd < 0) && ((*lists[i].file == NULL) || ((fd = open(*lists[i].file, O_RDONLY)) < 0)))
1780 flog(LOG_ERR, "could not open filelist tempfile: %s", strerror(errno));
1787 static struct sharecache *findbytth(char *tth32)
1791 struct sharecache *node;
1793 if((buf = base32decode(tth32, &buflen)) == NULL)
1800 for(node = shareroot->child; node != NULL; node = nextscnode(node))
1802 if(node->f.b.hastth && !memcmp(node->hashtth, buf, 24))
1809 static struct sharecache *resdcpath(char *path, char *charset, char sep)
1811 struct sharecache *node;
1818 if((p2 = strchr(p, sep)) != NULL)
1820 if((node = findcache(node, icsmbstowcs(p, charset, L""))) == NULL)
1827 static void cmd_get(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1832 struct sharecache *node;
1833 struct socket *lesk;
1837 if(peer->transfer == NULL)
1842 if((p = strchr(args, '$')) == NULL)
1848 if((offset = (atoi(p) - 1)) < 0)
1853 if(((fd = openfilelist(args)) < 0) && (errno != 0))
1855 qstr(sk, "$Error Could not send file list|");
1858 } else if(fd >= 0) {
1859 if((buf2 = icsmbstowcs(args, DCCHARSET, NULL)) != NULL)
1860 transfersetpath(peer->transfer, buf2);
1861 peer->transfer->flags.b.minislot = 1;
1865 /* Use DCCHARSET in $Get paths until further researched... */
1866 if((node = resdcpath(args, DCCHARSET, '\\')) == NULL)
1868 qstrf(sk, "$Error File not in share|");
1872 if((fd = opensharecache(node)) < 0)
1874 qstrf(sk, "$Error %s|", strerror(errno));
1878 buf = getfspath(node);
1879 if((buf2 = icsmbstowcs(buf, NULL, NULL)) == NULL)
1880 flog(LOG_WARNING, "could not convert native path into a wcs (%s): %s", buf, strerror(errno));
1882 transfersetpath(peer->transfer, buf2);
1885 if(fstat(fd, &sb) < 0)
1888 flog(LOG_WARNING, "could not stat file %ls: %s", node->name, strerror(errno));
1889 qstrf(sk, "$Error|");
1893 if(sb.st_size < 65536)
1894 peer->transfer->flags.b.minislot = 1;
1895 if(!peer->transfer->flags.b.minislot && (slotsleft() < 1)) {
1897 qstr(sk, "$MaxedOut|");
1901 if((offset != 0) && (lseek(fd, offset, SEEK_SET) < 0))
1904 qstrf(sk, "$Error Offset out of range|");
1908 lesk = wrapsock(fd);
1909 transferprepul(peer->transfer, sb.st_size, offset, -1, lesk);
1911 qstrf(sk, "$FileLength %zi|", peer->transfer->size);
1914 static void cmd_send(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1916 if(peer->transfer == NULL)
1921 if(peer->transfer->localend == NULL)
1930 static void cmd_supports(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1935 size_t arrsize, arrdata;
1937 if(peer->supports != NULL)
1939 for(i = 0; peer->supports[i] != NULL; i++)
1940 free(peer->supports[i]);
1941 free(peer->supports);
1944 arrsize = arrdata = 0;
1948 if((p2 = strchr(p, ' ')) != NULL)
1952 addtobuf(arr, sstrdup(p));
1953 } while((p = p2) != NULL);
1954 addtobuf(arr, NULL);
1955 peer->supports = arr;
1958 static void cmd_getblock(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1962 int start, numbytes;
1963 char *charset, *buf;
1965 struct sharecache *node;
1967 struct socket *lesk;
1969 if(peer->transfer == NULL)
1975 if((p2 = strchr(p, ' ')) == NULL)
1983 if((p2 = strchr(p, ' ')) == NULL)
1991 if(!strcmp(cmd, "$UGetBlock") || !strcmp(cmd, "$UGetZBlock"))
1994 /* Use DCCHARSET in $Get paths until further researched... */
1995 charset = DCCHARSET;
1996 if(!strcmp(cmd, "$GetZBlock") || !strcmp(cmd, "$UGetZBlock"))
1997 initcompress(peer, CPRS_ZLIB);
1998 if(((fd = openfilelist(p)) < 0) && (errno != 0))
2000 qstr(sk, "$Error Could not send file list|");
2002 } else if(fd >= 0) {
2003 if((buf2 = icsmbstowcs(args, charset, NULL)) != NULL)
2004 transfersetpath(peer->transfer, buf2);
2005 peer->transfer->flags.b.minislot = 1;
2009 if((node = resdcpath(p, charset, '\\')) == NULL)
2011 qstr(sk, "$Error File not in cache|");
2014 if((fd = opensharecache(node)) < 0)
2016 qstrf(sk, "$Error %s|", strerror(errno));
2019 buf = getfspath(node);
2020 if((buf2 = icsmbstowcs(buf, NULL, NULL)) == NULL)
2021 flog(LOG_WARNING, "could not convert native path into a wcs (%s): %s", buf, strerror(errno));
2023 transfersetpath(peer->transfer, buf2);
2026 if(fstat(fd, &sb) < 0)
2029 flog(LOG_WARNING, "could not stat file %ls: %s", node->name, strerror(errno));
2030 qstr(sk, "$Error|");
2033 if(sb.st_size < 65536)
2034 peer->transfer->flags.b.minislot = 1;
2035 if(!peer->transfer->flags.b.minislot && (slotsleft() < 1)) {
2037 qstr(sk, "$MaxedOut|");
2040 if((start != 0) && ((start >= sb.st_size) || (lseek(fd, start, SEEK_SET) < 0)))
2043 qstr(sk, "$Error Offset out of range|");
2046 if((numbytes < 0) || (start + numbytes > sb.st_size))
2047 numbytes = sb.st_size - start;
2048 lesk = wrapsock(fd);
2049 transferprepul(peer->transfer, sb.st_size, start, start + numbytes, lesk);
2051 qstrf(sk, "$Sending %i|", numbytes);
2055 static void cmd_adcget(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2059 int start, numbytes;
2060 struct sharecache *node;
2062 struct socket *lesk;
2066 if(peer->transfer == NULL)
2071 if((argv = parseadc(args)) == NULL)
2076 if(parrlen(argv) < 4)
2081 start = atoi(argv[2]);
2082 numbytes = atoi(argv[3]);
2085 if(((fd = openfilelist(argv[1])) < 0) && (errno != 0))
2087 qstr(sk, "$Error Could not send file list|");
2089 } else if(fd >= 0) {
2090 if((wbuf = icsmbstowcs(argv[1], "UTF-8", NULL)) != NULL)
2091 transfersetpath(peer->transfer, wbuf);
2092 peer->transfer->flags.b.minislot = 1;
2096 if(!strncmp(argv[1], "TTH/", 4))
2098 if((node = findbytth(argv[1] + 4)) == NULL)
2100 qstr(sk, "$Error File not in cache|");
2104 if((node = resdcpath((argv[1][0] == '/')?(argv[1] + 1):(argv[1]), "UTF-8", '/')) == NULL)
2106 qstr(sk, "$Error File not in cache|");
2110 if((fd = opensharecache(node)) < 0)
2112 qstrf(sk, "$Error %s|", strerror(errno));
2115 buf = getfspath(node);
2116 if((wbuf = icsmbstowcs(buf, NULL, NULL)) == NULL)
2117 flog(LOG_WARNING, "could not convert native path into a wcs (%s): %s", buf, strerror(errno));
2119 transfersetpath(peer->transfer, wbuf);
2122 if(!strcmp(argv[0], "file"))
2124 for(i = 4; argv[i] != NULL; i++)
2126 if(!strcmp(argv[i], "ZL1"))
2127 initcompress(peer, CPRS_ZLIB);
2129 if(fstat(fd, &sb) < 0)
2131 flog(LOG_WARNING, "could not stat file %ls: %s", node->name, strerror(errno));
2132 qstr(sk, "$Error|");
2135 if(sb.st_size < 65536)
2136 peer->transfer->flags.b.minislot = 1;
2137 if(!peer->transfer->flags.b.minislot && (slotsleft() < 1)) {
2138 qstr(sk, "$MaxedOut|");
2141 if((start != 0) && ((start >= sb.st_size) || (lseek(fd, start, SEEK_SET) < 0)))
2143 qstr(sk, "$Error Offset out of range|");
2146 if((numbytes < 0) || (start + numbytes > sb.st_size))
2147 numbytes = sb.st_size - start;
2148 lesk = wrapsock(fd);
2149 transferprepul(peer->transfer, sb.st_size, start, start + numbytes, lesk);
2152 qstr(sk, "$ADCSND");
2153 sendadc(sk, "file");
2154 sendadc(sk, argv[1]);
2155 sendadcf(sk, "%i", start);
2156 sendadcf(sk, "%i", numbytes);
2157 if(peer->compress == CPRS_ZLIB)
2161 } else if(!strcmp(argv[0], "tthl")) {
2163 * XXX: Implement full TTHL support.
2165 * In the meantime, this is better than nothing, since it at
2166 * least allows fetching of the TTH root if it isn't already
2171 qstr(sk, "$Error no TTHL data for virtual files|");
2174 qstr(sk, "$ADCSND");
2175 sendadc(sk, "tthl");
2176 sendadc(sk, argv[1]);
2180 sockqueue(sk, node->hashtth, 24);
2182 qstr(sk, "$Error Namespace not implemented|");
2192 static void handletthl(struct dcpeer *peer)
2196 while(peer->inbufdata >= 24)
2198 pushtigertree(&peer->tth, peer->inbuf);
2199 memmove(peer->inbuf, peer->inbuf + 24, peer->inbufdata -= 24);
2200 peer->curread += 24;
2202 if(peer->curread >= peer->totalsize)
2204 if(peer->timeout == NULL)
2205 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
2206 peer->state = PEER_CMD;
2207 synctigertree(&peer->tth);
2208 restigertree(&peer->tth, buf);
2209 transfersethash(peer->transfer, newhash(L"TTH", 24, buf));
2214 static void cmd_adcsnd(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2217 int start, numbytes;
2219 if(peer->transfer == NULL)
2224 if((argv = parseadc(args)) == NULL)
2229 if(parrlen(argv) < 4)
2234 start = atoi(argv[2]);
2235 numbytes = atoi(argv[3]);
2236 if(!strcmp(argv[0], "tthl"))
2238 if((start != 0) || (numbytes % 24 != 0))
2240 /* Weird. Bail out. */
2244 if(peer->timeout != NULL)
2245 canceltimer(peer->timeout);
2246 peer->state = PEER_TTHL;
2247 peer->totalsize = numbytes;
2249 peer->fetchingtthl = 0;
2250 inittigertree(&peer->tth);
2252 } else if(!strcmp(argv[0], "file")) {
2253 if(start != peer->transfer->curpos)
2258 if(start + numbytes != peer->transfer->size)
2260 transfersetsize(peer->transfer, start + numbytes);
2265 if(peer->inbufdata > 0)
2267 sockpushdata(sk, peer->inbuf, peer->inbufdata);
2268 peer->inbufdata = 0;
2269 transread(sk, peer);
2272 /* We certainly didn't request this...*/
2281 static void cmd_sending(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2285 if(peer->transfer == NULL)
2290 numbytes = atoi(args);
2291 if(peer->transfer->size - peer->transfer->curpos != numbytes)
2293 transfersetsize(peer->transfer, peer->transfer->curpos + numbytes);
2298 if(peer->inbufdata > 0)
2300 sockpushdata(sk, peer->inbuf, peer->inbufdata);
2301 peer->inbufdata = 0;
2302 transread(sk, peer);
2308 static void cmd_(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
2313 hubhandleaction(sk, fn, cmd, args);
2317 static void cmd_(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2323 static int hubreqconn(struct fnetpeer *peer)
2328 if((peer->fn->state != FNN_EST) || (peer->fn->fnet != &dcnet))
2333 if((hub = peer->fn->data) == NULL)
2338 if((mbsnick = icwcstombs(peer->id, hub->charset)) == NULL)
2339 return(1); /* Shouldn't happen, of course, but who knows... */
2342 sendctm(peer->fn->sk, mbsnick);
2343 expectpeer(mbsnick, peer->fn);
2345 qstrf(peer->fn->sk, "$RevConnectToMe %s %s|", hub->nativenick, mbsnick);
2351 static int hubsendchat(struct fnetnode *fn, int public, wchar_t *to, wchar_t *string)
2354 char *mbsstring, *mbsto;
2357 if((mbsto = icwcstombs(to, hub->charset)) == NULL)
2362 if((mbsstring = icwcstombs(string, hub->charset)) == NULL)
2367 if((strchr(mbsto, '|') != NULL) || (strchr(mbsto, ' ') != NULL))
2374 if(strchr(mbsstring, '|') != NULL)
2385 qstrf(fn->sk, "<%s> %s|", hub->nativenick, mbsstring);
2387 qstrf(fn->sk, "$To: %s From: %s $<%s> %s|", mbsto, hub->nativenick, hub->nativenick, mbsstring);
2390 qstrf(fn->sk, "$To: %s From: %s $<%s> %s|", mbsto, hub->nativenick, hub->nativenick, mbsstring);
2397 static void findsizelimit(struct sexpr *sexpr, int *min, int *max)
2399 int minl, maxl, minr, maxr, retmin, retmax;
2404 findsizelimit(sexpr->l, &minl, &maxl);
2405 findsizelimit(sexpr->r, &minr, &maxr);
2406 retmin = (minl > minr)?minl:minr;
2407 if((maxl != -1) && (maxr != -1))
2408 retmax = (maxl < maxr)?maxl:maxr;
2417 findsizelimit(sexpr->l, &minl, &maxl);
2418 findsizelimit(sexpr->r, &minr, &maxr);
2419 retmin = (minl < minr)?minl:minr;
2420 if((maxl == -1) || (maxr == -1))
2423 retmax = (maxl > maxr)?maxl:maxr;
2426 findsizelimit(sexpr->l, &minl, &maxl);
2427 if((minl == 0) && (maxl == -1)) /* Interval is unspecified */
2431 } else if((minl == 0) && (maxl != -1)) {
2434 } else if((minl != 0) && (maxl == -1)) {
2437 } else { /* This would yield two seperate intervals, which DC cannot handle */
2443 retmax = sexpr->d.n - 1;
2446 retmin = sexpr->d.n;
2447 retmax = sexpr->d.n;
2450 retmin = sexpr->d.n + 1;
2464 static struct hash *findsehash(struct sexpr *sexpr)
2466 struct hash *h1, *h2;
2471 if((h1 = findsehash(sexpr->l)) != NULL)
2473 if((h1 = findsehash(sexpr->r)) != NULL)
2477 if((h1 = findsehash(sexpr->l)) == NULL)
2479 if((h2 = findsehash(sexpr->r)) == NULL)
2485 if(!wcscmp(sexpr->d.hash->algo, L"TTH"))
2486 return(sexpr->d.hash);
2493 static int hubsearch(struct fnetnode *fn, struct search *srch, struct srchfnnlist *ln)
2496 struct wcslist *list, *cur;
2497 char *sstr, *buf, *p;
2498 size_t sstrsize, sstrdata;
2499 struct sockaddr *name;
2501 int minsize, maxsize;
2505 if((fn->state != FNN_EST) || (fn->sk == NULL) || (fn->sk->state != SOCK_EST))
2507 list = findsexprstrs(srch->sexpr);
2508 findsizelimit(srch->sexpr, &minsize, &maxsize);
2509 hash = findsehash(srch->sexpr);
2510 if((minsize != 0) && (maxsize != -1))
2512 /* Choose either minsize or maxsize by trying to determine
2513 * which choice will be most restrictive. The result can be
2514 * approximative at best anyway, so don't try too hard... */
2515 if((50000000 - maxsize) > (minsize - 50000000))
2521 sstrsize = sstrdata = 0;
2522 if((hash != NULL) && (hash->len == 24))
2524 /* Prioritize hash searches above all else */
2525 bufcat(sstr, "F?T?0?9?TTH:", 12);
2526 buf = base32encode(hash->buf, hash->len);
2528 bufcat(sstr, buf, 39);
2533 sizebuf2(sstr, sstrdata + 32, 1);
2534 sstrdata += snprintf(sstr + sstrdata, sstrsize - sstrdata, "T?F?%i?1?", minsize);
2535 } else if(maxsize != -1) {
2536 sizebuf2(sstr, sstrdata + 32, 1);
2537 sstrdata += snprintf(sstr + sstrdata, sstrsize - sstrdata, "T?T?%i?1?", maxsize);
2539 bufcat(sstr, "F?F?0?1?", 8);
2543 for(cur = list; cur != NULL; cur = cur->next)
2545 /* Use DCCHARSET in $Get paths until further researched... */
2546 if((buf = icwcstombs(cur->str, DCCHARSET)) == NULL)
2548 /* Can't find anything anyway if the search expression
2549 * requires characters outside DC's charset. There's
2550 * nothing technically wrong with the search itself,
2551 * however, so return success. This should be
2552 * considered as an optimization. */
2559 addtobuf(sstr, '$');
2561 * It probably doesn't hurt if buf contains any extra
2562 * dollar signs - it will just result in extra search
2563 * terms, and the extraneous results will be filtered by
2564 * the search layer anyway. It hurts if it contains any
2565 * pipes, though, so let's sell them for money.
2567 for(p = buf; *p; p++)
2572 bufcat(sstr, buf, strlen(buf));
2576 /* Will match all files... :-/ */
2577 addtobuf(sstr, '.');
2583 if(sockgetremotename2(udpsock, fn->sk, &name, &namelen) < 0)
2585 flog(LOG_WARNING, "cannot get address of UDP socket");
2587 qstrf(fn->sk, "$Search %s %s|", formataddress(name, namelen), sstr);
2591 qstrf(fn->sk, "$Search Hub:%s %s|", hub->nativenick, sstr);
2595 fn->lastsrch = time(NULL);
2603 #define cc(c) ((void (*)(struct socket *, void *, char *, char *))(c))
2604 static struct command hubcmds[] =
2606 {"$Lock", cc(cmd_lock)},
2607 {"$HubName", cc(cmd_hubname)},
2608 {"$Hello", cc(cmd_hello)},
2609 {"$Quit", cc(cmd_quit)},
2610 {"$NickList", cc(cmd_nicklist)},
2611 {"$OpList", cc(cmd_oplist)},
2612 {"$MyINFO", cc(cmd_myinfo)},
2613 {"$ForceMove", cc(cmd_forcemove)},
2614 {"$Search", cc(cmd_search)},
2615 {"$MultiSearch", cc(cmd_search)},
2616 {"$ConnectToMe", cc(cmd_connecttome)},
2617 {"$RevConnectToMe", cc(cmd_revconnecttome)},
2618 {"$GetNetInfo", cc(cmd_getnetinfo)},
2619 {"$To:", cc(cmd_to)},
2620 {"$SR", cc(cmd_sr)},
2621 {"$UserCommand", cc(cmd_usercommand)},
2622 {"$GetPass", cc(cmd_getpass)},
2623 {"$LogedIn", cc(cmd_logedin)}, /* sic */
2624 {"$Supports", cc(cmd_hubsupports)},
2628 static struct command peercmds[] =
2630 {"$MyNick", cc(cmd_mynick)},
2631 {"$Lock", cc(cmd_peerlock)},
2632 {"$Direction", cc(cmd_direction)},
2633 {"$Key", cc(cmd_key)},
2634 {"$FileLength", cc(cmd_filelength)},
2635 {"$Error", cc(cmd_error)},
2636 {"$MaxedOut", cc(cmd_maxedout)},
2637 {"$Get", cc(cmd_get)},
2638 {"$Send", cc(cmd_send)},
2639 {"$Supports", cc(cmd_supports)},
2640 {"$GetBlock", cc(cmd_getblock)},
2641 {"$UGetBlock", cc(cmd_getblock)},
2642 {"$GetZBlock", cc(cmd_getblock)},
2643 {"$UGetZBlock", cc(cmd_getblock)},
2644 {"$ADCGET", cc(cmd_adcget)},
2645 {"$ADCSND", cc(cmd_adcsnd), 1},
2646 {"$Sending", cc(cmd_sending), 1},
2651 static void dctransdetach(struct transfer *transfer, struct dcpeer *peer)
2653 CBUNREG(transfer, trans_filterout, peer);
2656 peer->transfer = NULL;
2660 static void dctransgotdata(struct transfer *transfer, struct dcpeer *peer)
2664 unsigned char outbuf[1024];
2668 if((peer->state == PEER_TRNS) || (peer->state == PEER_SYNC))
2670 if(sockqueuesize(peer->sk) < 65536)
2672 if((buf = transfergetdata(transfer, &bufsize)) != NULL)
2674 if(peer->compress == CPRS_NONE)
2676 sockqueue(peer->sk, buf, bufsize);
2677 } else if(peer->compress == CPRS_ZLIB) {
2678 cstr = peer->cprsdata;
2679 cstr->next_in = buf;
2680 cstr->avail_in = bufsize;
2681 while(cstr->avail_in > 0)
2683 cstr->next_out = outbuf;
2684 cstr->avail_out = sizeof(outbuf);
2685 if((ret = deflate(cstr, 0)) != Z_OK)
2687 flog(LOG_WARNING, "bug? deflate() did not return Z_OK (but rather %i)", ret);
2691 sockqueue(peer->sk, outbuf, sizeof(outbuf) - cstr->avail_out);
2696 if(peer->state == PEER_SYNC)
2698 if(peer->compress == CPRS_ZLIB)
2700 cstr = peer->cprsdata;
2701 cstr->next_in = NULL;
2705 cstr->next_out = outbuf;
2706 cstr->avail_out = sizeof(outbuf);
2707 ret = deflate(cstr, Z_FINISH);
2708 if((ret != Z_OK) && (ret != Z_STREAM_END))
2710 flog(LOG_WARNING, "bug? deflate(Z_FINISH) did not return Z_OK (but rather %i)", ret);
2714 sockqueue(peer->sk, outbuf, sizeof(outbuf) - cstr->avail_out);
2715 } while(ret != Z_STREAM_END);
2721 if(peer->timeout == NULL)
2722 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
2723 peer->state = PEER_CMD;
2725 transfersetstate(transfer, TRNS_HS);
2726 socksettos(peer->sk, confgetint("fnet", "fnptos"));
2727 transfer->flags.b.minislot = 0;
2728 peer->sk->writecb = NULL;
2735 static void dctransendofdata(struct transfer *transfer, struct dcpeer *peer)
2737 peer->state = PEER_SYNC;
2738 dctransgotdata(transfer, peer);
2741 static void dcwantdata(struct transfer *transfer, struct dcpeer *peer)
2743 if(transferdatasize(transfer) < 65536)
2744 peer->sk->ignread = 0;
2747 static void transread(struct socket *sk, struct dcpeer *peer)
2751 struct transfer *transfer;
2753 if((buf = sockgetinbuf(sk, &bufsize)) == NULL)
2755 if(peer->transfer == NULL)
2761 transferputdata(peer->transfer, buf, bufsize);
2763 if(peer->transfer->curpos >= peer->transfer->size)
2765 transfer = peer->transfer;
2766 transferdetach(transfer);
2767 transferendofdata(transfer);
2770 if(transferdatasize(peer->transfer) > 65535)
2774 static void transerr(struct socket *sk, int err, struct dcpeer *peer)
2776 struct transfer *transfer;
2778 if((transfer = peer->transfer) == NULL)
2783 transferdetach(transfer);
2784 transferendofdata(transfer);
2787 static void transwrite(struct socket *sk, struct dcpeer *peer)
2789 if((peer->state != PEER_TRNS) && (peer->state != PEER_SYNC))
2791 if(peer->transfer == NULL)
2796 dctransgotdata(peer->transfer, peer);
2799 static void udpread(struct socket *sk, void *data)
2801 char *buf, *p, *p2, *hashbuf;
2802 size_t buflen, hashlen;
2803 char *nick, *filename, *hubname;
2804 struct sockaddr_in hubaddr;
2806 struct fnetnode *fn, *myfn;
2809 wchar_t *wnick, *wfile;
2812 if((buf = sockgetinbuf(sk, &buflen)) == NULL)
2814 buf = srealloc(buf, buflen + 1);
2816 if(!strncmp(buf, "$SR ", 4))
2820 if((p2 = strchr(p, ' ')) == NULL)
2828 if((p2 = strchr(p, 5)) == NULL)
2835 if((p2 = strchr(p, ' ')) == NULL)
2843 if((p2 = strchr(p, '/')) == NULL)
2851 if((p2 = strchr(p, 5)) == NULL)
2858 if((p2 = strstr(p, " (")) == NULL)
2865 if((p2 = strchr(p, ':')) == NULL)
2871 hubaddr.sin_family = AF_INET;
2872 if(!inet_aton(p, &hubaddr.sin_addr))
2878 if((p2 = strchr(p, ')')) == NULL)
2884 hubaddr.sin_port = htons(atoi(p));
2885 /* Use DCCHARSET in $Get paths until further researched... */
2886 if((wfile = icmbstowcs(filename, DCCHARSET)) == NULL)
2893 if(!strncmp(hubname, "TTH:", 4))
2895 if((hashbuf = base32decode(hubname + 4, &hashlen)) != NULL)
2898 hash = newhash(L"TTH", 24, hashbuf);
2902 for(fn = fnetnodes; fn != NULL; fn = fn->next)
2904 if((fn->fnet == &dcnet) && ((hub = fn->data) != NULL))
2906 if((hub->nativename != NULL) && !strcmp(hub->nativename, hubname))
2921 for(fn = fnetnodes; fn != NULL; fn = fn->next)
2923 if((fn->fnet == &dcnet) && (fn->sk != NULL) && addreq(fn->sk->remote, (struct sockaddr *)&hubaddr))
2933 if((wnick = icmbstowcs(nick, (hub == NULL)?DCCHARSET:(hub->charset))) == NULL)
2938 sr = newsrchres(&dcnet, wfile, wnick);
2939 if(sr->peernick != NULL)
2941 sr->peernick = swcsdup(wnick);
2947 getfnetnode(sr->fn = myfn);
2956 static void hubread(struct socket *sk, struct fnetnode *fn)
2963 hub = (struct dchub *)fn->data;
2964 if((newbuf = sockgetinbuf(sk, &datalen)) == NULL)
2966 if(hub->inbufdata > 500000) /* Discard possible malicious data */
2968 sizebuf2(hub->inbuf, hub->inbufdata + datalen, 1);
2969 memcpy(hub->inbuf + hub->inbufdata, newbuf, datalen);
2971 p = hub->inbuf + hub->inbufdata;
2972 hub->inbufdata += datalen;
2973 while((datalen > 0) && ((p = memchr(p, '|', datalen)) != NULL))
2976 newqcmd(&hub->queue, hub->inbuf);
2977 memmove(hub->inbuf, p, hub->inbufdata -= p - hub->inbuf);
2978 datalen = hub->inbufdata;
2983 static void huberr(struct socket *sk, int err, struct fnetnode *fn)
2988 static int hubsetnick(struct fnetnode *fn, wchar_t *newnick)
2994 if((buf = icwcstombs(newnick, (hub == NULL)?DCCHARSET:(hub->charset))) == NULL)
2996 if((strchr(buf, ' ') != NULL) || (strchr(buf, '|') != NULL) || (strchr(buf, '$') != NULL))
3001 if(hub == NULL) /* Not yet connected */
3006 if(hub->nativenick != NULL)
3007 free(hub->nativenick);
3008 hub->nativenick = buf;
3012 static struct dchub *newdchub(struct fnetnode *fn)
3019 new = smalloc(sizeof(*new));
3020 memset(new, 0, sizeof(*new));
3022 if(confgetint("dc", "dcppemu"))
3024 if((emu = wpfind(fn->args, L"dcppemu")) != NULL)
3032 if((wcharset = wpfind(fn->args, L"charset")) != NULL)
3034 if((charset = icwcstombs(wcharset, "US-ASCII")) != NULL)
3036 if(!havecharset(charset))
3044 new->charset = charset;
3046 new->charset = sstrdup(DCCHARSET);
3047 if(hubsetnick(fn, fn->mynick))
3048 fnetsetnick(fn, L"DoldaConnectUser-IN");
3049 /* IN as in Invalid Nick */
3053 static struct dcpeer *newdcpeer(struct socket *sk)
3057 new = smalloc(sizeof(*new));
3058 memset(new, 0, sizeof(*new));
3059 new->transfer = NULL;
3062 if(confgetint("dc", "dcppemu"))
3073 static void freedcpeer(struct dcpeer *peer)
3076 struct qcommand *qcmd;
3081 if(peer->next != NULL)
3082 peer->next->prev = peer->prev;
3083 if(peer->prev != NULL)
3084 peer->prev->next = peer->next;
3085 if(peer->transfer != NULL)
3087 if(peer->transfer->dir == TRNSD_UP)
3088 peer->transfer->close = 1;
3089 if(peer->transfer->dir == TRNSD_DOWN)
3090 resettransfer(peer->transfer);
3091 transferdetach(peer->transfer);
3093 if(peer->timeout != NULL)
3094 canceltimer(peer->timeout);
3095 if(peer->sk->data == peer)
3096 peer->sk->data = NULL;
3097 peer->sk->readcb = NULL;
3098 peer->sk->writecb = NULL;
3099 peer->sk->errcb = NULL;
3102 if(peer->supports != NULL)
3104 for(i = 0; peer->supports[i] != NULL; i++)
3105 free(peer->supports[i]);
3106 free(peer->supports);
3108 if(peer->inbuf != NULL)
3110 if(peer->key != NULL)
3112 if(peer->wcsname != NULL)
3113 free(peer->wcsname);
3114 if(peer->nativename != NULL)
3115 free(peer->nativename);
3116 if(peer->charset != NULL)
3117 free(peer->charset);
3118 if(peer->fn != NULL)
3119 putfnetnode(peer->fn);
3120 while((qcmd = ulqcmd(&peer->queue)) != NULL)
3126 static void hubconnect(struct fnetnode *fn)
3128 fn->sk->readcb = (void (*)(struct socket *, void *))hubread;
3129 fn->sk->errcb = (void (*)(struct socket *, int, void *))huberr;
3131 fn->data = newdchub(fn);
3136 static void hubdestroy(struct fnetnode *fn)
3140 struct qcommand *qcmd;
3142 hub = (struct dchub *)fn->data;
3143 if((fn->sk != NULL) && (fn->sk->data == fn))
3145 fn->sk->data = NULL;
3146 fn->sk->readcb = NULL;
3147 fn->sk->errcb = NULL;
3152 while((qcmd = ulqcmd(&hub->queue)) != NULL)
3154 if(hub->supports != NULL)
3156 for(i = 0; hub->supports[i] != NULL; i++)
3157 free(hub->supports[i]);
3158 free(hub->supports);
3160 if(hub->nativename != NULL)
3161 free(hub->nativename);
3162 if(hub->nativenick != NULL)
3163 free(hub->nativenick);
3164 if(hub->charset != NULL)
3166 if(hub->inbuf != NULL)
3171 static wchar_t *dcbasename(wchar_t *filename)
3175 if((ret = wcsrchr(filename, L'\\')) != NULL)
3180 static struct transferiface dctransfer =
3182 .detach = (void (*)(struct transfer *, void *))dctransdetach,
3183 .gotdata = (void (*)(struct transfer *, void *))dctransgotdata,
3184 .endofdata = (void (*)(struct transfer *, void *))dctransendofdata,
3185 .wantdata = (void (*)(struct transfer *, void *))dcwantdata
3188 static struct fnet dcnet =
3191 .connect = hubconnect,
3192 .destroy = hubdestroy,
3193 .setnick = hubsetnick,
3194 .reqconn = hubreqconn,
3195 .sendchat = hubsendchat,
3196 .search = hubsearch,
3197 .filebasename = dcbasename
3200 static void peerread(struct socket *sk, struct dcpeer *peer)
3204 struct command *cmd;
3206 if((newbuf = sockgetinbuf(sk, &datalen)) == NULL)
3208 sizebuf2(peer->inbuf, peer->inbufdata + datalen, 1);
3209 memcpy(peer->inbuf + peer->inbufdata, newbuf, datalen);
3211 peer->inbufdata += datalen;
3212 if(peer->state == PEER_CMD)
3215 while((peer->inbufdata > 0) && (p = memchr(peer->inbuf, '|', peer->inbufdata)) != NULL)
3218 newqcmd(&peer->queue, peer->inbuf);
3219 for(cmd = peercmds; cmd->handler != NULL; cmd++)
3221 if(!memcmp(peer->inbuf, cmd->name, strlen(cmd->name)) && ((peer->inbuf[strlen(cmd->name)] == ' ') || (peer->inbuf[strlen(cmd->name)] == '|')))
3224 memmove(peer->inbuf, p, peer->inbufdata -= p - peer->inbuf);
3227 peer->state = PEER_STOP;
3231 } else if(peer->state == PEER_TTHL) {
3236 static void peererror(struct socket *sk, int err, struct dcpeer *peer)
3241 static void peerconnect(struct socket *sk, int err, struct fnetnode *fn)
3243 struct dcpeer *peer;
3253 peer = newdcpeer(sk);
3256 peer->dcppemu = hub->dcppemu;
3257 sk->readcb = (void (*)(struct socket *, void *))peerread;
3258 sk->errcb = (void (*)(struct socket *, int, void *))peererror;
3260 socksettos(sk, confgetint("fnet", "fnptos"));
3262 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
3267 static void peeraccept(struct socket *sk, struct socket *newsk, void *data)
3269 struct dcpeer *peer;
3271 peer = newdcpeer(newsk);
3273 newsk->readcb = (void (*)(struct socket *, void *))peerread;
3274 newsk->errcb = (void (*)(struct socket *, int, void *))peererror;
3276 socksettos(newsk, confgetint("fnet", "fnptos"));
3277 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
3280 static void updatehmlist(void)
3282 int i, lev, ic, ret;
3283 struct sharecache *node;
3284 char *buf, *buf2, numbuf[32];
3285 size_t bufsize, bufdata;
3289 buf = smalloc(bufsize = 65536);
3290 node = shareroot->child;
3295 /* Use DCCHARSET in $Get paths until further researched... */
3296 if((buf2 = icwcstombs(node->name, DCCHARSET)) != NULL)
3298 for(i = 0; i < lev; i++)
3300 bufcat(buf, buf2, strlen(buf2));
3302 if(node->f.b.type == FILE_REG)
3305 sprintf(numbuf, "%zi", node->size);
3306 bufcat(buf, numbuf, strlen(numbuf));
3313 if((node->child != NULL) && !ic)
3317 } else if(node->next != NULL) {
3320 while(node->next == NULL)
3323 node = node->parent;
3324 if(node == shareroot)
3327 if(node == shareroot)
3332 if(hmlistname != NULL)
3337 hmlistname = sstrdup("/tmp/dc-filelist-hm-XXXXXX");
3338 if((fd = mkstemp(hmlistname)) < 0)
3340 flog(LOG_WARNING, "could not create HM file list tempfile: %s", strerror(errno));
3345 * I do not want to implement a good Huffman encoder, and it's not
3346 * like Huffman encoding actually yields any impressive results
3347 * for DC file lists anyway, so I'll just output a bogus
3348 * tree. Implement a good encoder if you want to.
3350 write(fd, "HE3\r\0", 5);
3351 write(fd, &bufdata, 4);
3353 write(fd, &ibuf, 2);
3355 for(i = 0; i < 256; i++)
3358 write(fd, &ibuf, 1);
3360 for(i = 0; i < 256; i++)
3362 for(buf2 = buf; bufdata > 0;)
3364 if((ret = write(fd, buf2, bufdata)) < 0)
3366 flog(LOG_WARNING, "could not write file list: %s", strerror(errno));
3377 static struct xmlent
3384 /* {L'\'', L"""}, Emulate DC++ escaping by omitting this. */
3388 static wchar_t *escapexml(wchar_t *src)
3390 static wchar_t *buf = NULL;;
3393 size_t bufsize, bufdata;
3399 bufsize = bufdata = 0;
3400 for(; *src != L'\0'; src++)
3403 if((c > 0) && (c < 32))
3405 bufcat(buf, L"&#", 2);
3406 ret = swprintf(nbuf, (sizeof(nbuf) / sizeof(*nbuf)), L"%i", c);
3407 bufcat(buf, nbuf, ret);
3408 addtobuf(buf, L';');
3410 for(ent = entities; ent->ent != NULL; ent++)
3414 bufcat(buf, ent->ent, wcslen(ent->ent));
3418 if(ent->ent == NULL)
3419 addtobuf(buf, *src);
3422 addtobuf(buf, L'\0');
3426 static void updatexmllist(void)
3430 char cidbuf[14], *namebuf;
3432 struct sharecache *node;
3434 if(xmllistname != NULL)
3436 unlink(xmllistname);
3439 xmllistname = sstrdup("/tmp/dc-filelist-dcxml-XXXXXX");
3440 if((fd = mkstemp(xmllistname)) < 0)
3442 flog(LOG_WARNING, "could not create XML file list tempfile: %s", strerror(errno));
3447 if((fs = fdopen(fd, "w")) == NULL)
3449 flog(LOG_WARNING, "could not fdopen XML list fd %i: %s", fd, strerror(errno));
3450 unlink(xmllistname);
3456 fprintf(fs, "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>\r\n");
3457 for(i = 0; i < sizeof(cidbuf) - 1; i++)
3458 cidbuf[i] = (rand() % ('Z' - 'A' + 1)) + 'A';
3460 if(confgetint("dc", "dcppemu"))
3461 fprintf(fs, "<FileListing Version=\"1\" CID=\"%s\" Base=\"/\" Generator=\"DC++ 0.674\">\r\n", cidbuf);
3463 fprintf(fs, "<FileListing Version=\"1\" CID=\"%s\" Base=\"/\" Generator=\"%s\">\r\n", cidbuf, "DoldaConnect" VERSION);
3465 node = shareroot->child;
3469 if((namebuf = icswcstombs(escapexml(node->name), "UTF-8", NULL)) != NULL)
3471 for(i = 0; i < lev; i++)
3473 if(node->child != NULL)
3475 fprintf(fs, "<Directory Name=\"%s\">\r\n", namebuf);
3480 fprintf(fs, "<File Name=\"%s\" Size=\"%zi\"", namebuf, node->size);
3481 if(node->f.b.hastth)
3483 hashbuf = base32encode(node->hashtth, 24);
3484 fprintf(fs, " TTH=\"%.39s\"", hashbuf);
3487 fprintf(fs, "/>\r\n");
3489 while(node->next == NULL)
3491 node = node->parent;
3492 if(node == shareroot)
3497 for(i = 0; i < lev; i++)
3499 fprintf(fs, "</Directory>\r\n");
3502 if(node == shareroot)
3508 if(confgetint("dc", "dcppemu"))
3509 fprintf(fs, "</FileListing>");
3511 fprintf(fs, "</FileListing>\r\n");
3515 static void updatexmlbz2list(void)
3524 if(xmllistname == NULL)
3526 if((in = fopen(xmllistname, "r")) == NULL)
3528 flog(LOG_WARNING, "could not open XML file list for bzipping: %s", strerror(errno));
3531 if(xmlbz2listname != NULL)
3533 unlink(xmlbz2listname);
3534 free(xmlbz2listname);
3536 xmlbz2listname = sstrdup("/tmp/dc-filelist-dcxmlbz2-XXXXXX");
3537 if((fd = mkstemp(xmlbz2listname)) < 0)
3539 flog(LOG_WARNING, "could not create bzipped XML file list tempfile: %s", strerror(errno));
3540 free(xmlbz2listname);
3541 xmlbz2listname = NULL;
3545 if((real = fdopen(fd, "w")) == NULL)
3547 flog(LOG_WARNING, "could not fdopen bzipped XML list fd %i: %s", fd, strerror(errno));
3549 unlink(xmlbz2listname);
3550 free(xmlbz2listname);
3551 xmlbz2listname = NULL;
3555 out = BZ2_bzWriteOpen(&err, real, 9, 0, 0);
3558 flog(LOG_WARNING, "could not open bzip2 stream from XML list");
3560 unlink(xmlbz2listname);
3561 free(xmlbz2listname);
3562 xmlbz2listname = NULL;
3568 bufdata = fread(buf, 1, sizeof(buf), in);
3569 BZ2_bzWrite(&err, out, buf, bufdata);
3572 BZ2_bzWriteClose(&err, out, 0, NULL, NULL);
3576 static void listtimercb(int cancelled, void *uudata)
3578 listwritetimer = NULL;
3583 static void updatelists(int now)
3585 if((hmlistname == NULL) || (xmllistname == NULL) || (xmlbz2listname == NULL))
3589 if(listwritetimer == NULL)
3590 listwritetimer = timercallback(ntime() + confgetint("cli", "hashwritedelay"), listtimercb, NULL);
3593 if(listwritetimer != NULL)
3594 canceltimer(listwritetimer);
3600 static int shareupdate(unsigned long long uusharesize, void *data)
3606 static char *quotestr(char *str)
3610 size_t bufsize, bufdata;
3612 static char *enc = NULL;
3613 size_t encsize, encdata;
3616 bufsize = bufdata = 0;
3617 for(p = (unsigned char *)str; *p; p++)
3620 bufcat(buf, "\\b", 2);
3622 bufcat(buf, "\\t", 2);
3624 bufcat(buf, "\\n", 2);
3626 bufcat(buf, "\\r", 2);
3628 bufcat(buf, "\\\\", 2);
3632 bprintf(buf, "\\x%02x", *p);
3638 if((wbuf = icmbstowcs((char *)buf, DCCHARSET)) != NULL)
3640 enc = icwcstombs(wbuf, NULL);
3645 encsize = encdata = 0;
3646 for(p = buf; *p; p++) {
3650 bprintf(buf, "\\x%x", *p);
3657 static void logunimpl(char *list, char *cmd, char *args)
3661 if((log = fopen("/tmp/dc-unimpl", "a")) == NULL)
3663 flog(LOG_WARNING, "could not open unimpl log: %s", strerror(errno));
3668 fputs(quotestr(cmd), log);
3672 fputs(quotestr(args), log);
3678 static void dispatchcommand(struct qcommand *qcmd, struct command *cmdlist, struct socket *sk, void *data)
3681 struct command *cmd;
3683 if((p = strchr(qcmd->string, ' ')) != NULL)
3685 for(cmd = cmdlist; cmd->handler != NULL; cmd++)
3687 if(!strcmp(cmd->name, qcmd->string))
3690 if(cmd->handler != NULL)
3692 cmd->handler(sk, data, qcmd->string, p);
3693 } else if(confgetint("dc", "logunimpl")) {
3694 if(cmdlist == hubcmds)
3695 logunimpl("hub", qcmd->string, p);
3696 else if(cmdlist == peercmds)
3697 logunimpl("peer", qcmd->string, p);
3699 logunimpl("other?!", qcmd->string, p);
3703 static int run(void)
3705 struct fnetnode *fn, *nextfn;
3707 struct dcpeer *peer, *nextpeer;
3708 struct qcommand *qcmd;
3712 for(fn = fnetnodes; fn != NULL; fn = nextfn)
3715 if(fn->fnet != &dcnet)
3717 if(fn->data == NULL)
3719 hub = (struct dchub *)fn->data;
3720 if((qcmd = ulqcmd(&hub->queue)) != NULL)
3722 if(*qcmd->string == '$')
3724 if((fn->sk != NULL) && (fn->sk->state == SOCK_EST))
3725 dispatchcommand(qcmd, hubcmds, fn->sk, fn);
3726 } else if(*qcmd->string != 0) {
3727 hubrecvchat(fn->sk, fn, NULL, qcmd->string);
3734 for(peer = peers; peer != NULL; peer = nextpeer)
3736 nextpeer = peer->next;
3737 if((qcmd = ulqcmd(&peer->queue)) != NULL)
3739 if(peer->timeout != NULL)
3740 canceltimer(peer->timeout);
3741 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
3742 if(*qcmd->string == '$')
3743 dispatchcommand(qcmd, peercmds, peer->sk, peer);
3752 static void preinit(int hup)
3759 static int updateudpport(struct configvar *var, void *uudata)
3761 struct sockaddr_in addr;
3762 struct socket *newsock;
3764 memset(&addr, 0, sizeof(addr));
3765 addr.sin_family = AF_INET;
3766 addr.sin_port = htons(var->val.num);
3767 if((newsock = netcsdgram((struct sockaddr *)&addr, sizeof(addr))) == NULL)
3769 flog(LOG_WARNING, "could not create new DC UDP socket, reverting to old: %s", strerror(errno));
3772 newsock->readcb = udpread;
3779 static int updatetcpport(struct configvar *var, void *uudata)
3781 struct sockaddr_in addr;
3782 struct socket *newsock;
3784 memset(&addr, 0, sizeof(addr));
3785 addr.sin_family = AF_INET;
3786 addr.sin_port = htons(var->val.num);
3787 if((newsock = netcslisten(SOCK_STREAM, (struct sockaddr *)&addr, sizeof(addr), peeraccept, NULL)) == NULL)
3788 flog(LOG_INFO, "could not listen to a remote address, going into passive mode");
3795 static int init(int hup)
3797 struct sockaddr_in addr;
3801 GCBREG(sharechangecb, shareupdate, NULL);
3806 addr.sin_family = AF_INET;
3807 memset(&addr.sin_addr, 0, sizeof(addr.sin_addr));
3808 addr.sin_port = htons(confgetint("dc", "udpport"));
3809 if((udpsock = netcsdgram((struct sockaddr *)&addr, sizeof(addr))) == NULL)
3811 flog(LOG_CRIT, "could not create DC UDP socket: %s", strerror(errno));
3814 udpsock->readcb = udpread;
3815 addr.sin_port = htons(confgetint("dc", "tcpport"));
3816 if((tcpsock = netcslisten(SOCK_STREAM, (struct sockaddr *)&addr, sizeof(addr), peeraccept, NULL)) == NULL)
3817 flog(LOG_INFO, "could not listen to a remote address, going into passive mode");
3818 CBREG(confgetvar("dc", "udpport"), conf_update, updateudpport, NULL, NULL);
3819 CBREG(confgetvar("dc", "tcpport"), conf_update, updatetcpport, NULL, NULL);
3820 CBREG(confgetvar("net", "mode"), conf_update, updatetcpport, NULL, NULL);
3825 static void terminate(void)
3827 if(hmlistname != NULL)
3832 if(xmllistname != NULL)
3834 unlink(xmllistname);
3837 if(xmlbz2listname != NULL)
3839 unlink(xmlbz2listname);
3840 free(xmlbz2listname);
3844 static struct configvar myvars[] =
3846 /** Specifies the share description reported to other DC users. */
3847 {CONF_VAR_STRING, "desc", {.str = L""}},
3848 /** Specifies the speed reported to other DC users. Normal values
3849 * are 28.8Kbps, 33.6Kbps, 56Kbps, Satellite, ISDN, DSL, Cable,
3850 * LAN(T1) or LAN(T3)*/
3851 {CONF_VAR_STRING, "speedstring", {.str = L"LAN(T1)"}},
3852 /** The e-mail address to report to other DC users. */
3853 {CONF_VAR_STRING, "email", {.str = L"spam@spam.org"}},
3854 /** Specifies a specific UDP port to use for DC search results. If
3855 * left unspecified, a port is allocated dynamically. Useful for
3856 * NAT routers (see also the net.visibleipv4 address for those
3858 {CONF_VAR_INT, "udpport", {.num = 0}},
3859 /** Specifies a specific TCP port to use for DC peer
3860 * connections. If left unspecified, a port is allocated
3861 * dynamically. Useful for NAT routers (see also the
3862 * net.visibleipv4 address for those cases). */
3863 {CONF_VAR_INT, "tcpport", {.num = 0}},
3864 /** If set to true, doldacond will do its best to emulate DC++
3865 * (currently v0.674). This should be left off if at all possible,
3866 * since turning it on will violate the rules of most hubs and
3867 * thus give hub owners an actual reason to kick you if it is
3868 * detected. It might be needed for some of the more bone-headed
3869 * hub owners, though. Note that DC++ emulation can also be turned
3870 * on or off for individual hubs, overriding this setting. */
3871 {CONF_VAR_BOOL, "dcppemu", {.num = 0}},
3872 /** Use for debugging. If set to true, doldacond will log all
3873 * unknown commands it receives, and their arguments, to
3874 * /tmp/dc-unimpl. */
3875 {CONF_VAR_BOOL, "logunimpl", {.num = 0}},
3879 static struct module me =
3888 .terminate = terminate,