2 * Dolda Connect - Modular multiuser Direct Connect-style client
3 * Copyright (C) 2004 Fredrik Tolf (fredrik@dolda2000.com)
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 #include <netinet/in.h>
26 #include <arpa/inet.h>
44 #include "sysevents.h"
49 * The Direct Connect protocol is extremely ugly. Thus, this code must
50 * also be a bit ugly in certain places. Please forgive me. =/
52 * This also means that there might be some pieces of the code that
53 * look completely illogical to you, and you think that you may make
54 * them much neater/better. However, in many cases it might just be
55 * that it's required to cope with some oddity of the protocol, such
56 * as the amazingly ugly delayed key response in the peer protocol.
59 /* I assume this is the correct character set to use for DC,
60 * considering it was developed without i18n support under Windows */
61 #define DCCHARSET "windows-1252"
63 #ifdef DCPP_MASQUERADE
65 * I honestly don't want to pretend being a client that I'm not, but
66 * there are so many hubs that simply do not accept any clients
67 * outside their whitelists, for no obvious reasons, so I feel that I
68 * am left with little choice. Anyhow, as long as I actually support
69 * all the features that my faked DC++ version does, there should be
70 * very little harm done.
73 #define DCIDTAGV "0.674"
74 #define DCIDFULL "DC++ 0.674"
76 #define DCIDTAG "Dolda"
77 #define DCIDTAGV VERSION
78 #define DCIDFULL "DoldaConnect " VERSION
93 void (*handler)(struct socket *sk, void *data, char *cmd, char *args);
99 struct qcommand *next;
106 size_t inbufdata, inbufsize;
107 struct qcommand *queue;
108 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"))
247 static int supports(struct dcpeer *peer, char *cap)
251 if(peer->supports == NULL)
253 for(p = peer->supports; *p != NULL; p++)
255 if(!strcasecmp(*p, cap))
261 static void endcompress(struct dcpeer *peer)
263 if(peer->compress == CPRS_ZLIB)
265 deflateEnd(peer->cprsdata);
266 free(peer->cprsdata);
268 peer->compress = CPRS_NONE;
271 static void initcompress(struct dcpeer *peer, int algo)
276 peer->compress = algo;
277 if(algo == CPRS_ZLIB)
279 peer->cprsdata = smalloc(sizeof(z_stream));
280 memset(peer->cprsdata, 0, sizeof(z_stream));
281 if((ret = deflateInit(peer->cprsdata, 3)) != Z_OK)
283 flog(LOG_CRIT, "Aiya! zlib refuses to init (%i)!", ret);
289 static void unquote(wchar_t *in)
293 for(p = in; *p != L'\0'; p++)
297 for(p2 = p + 1; (*p2 != L'\0') && (*p2 != L';') && (*p2 != L'&'); p2++);
304 if(!wcscmp(p + 1, L"amp"))
307 } else if(p[1] == L'#') {
308 nc = ucptowc(wcstol(p + 2, NULL, 10));
317 memmove(p + 1, p2 + 1, (wcslen(p2 + 1) + 1) * sizeof(wchar_t));
322 static void freeexppeer(struct dcexppeer *ep)
325 ep->next->prev = ep->prev;
327 ep->prev->next = ep->next;
332 if(ep->expire != NULL)
333 canceltimer(ep->expire);
337 static void exppeerexpire(int cancelled, struct dcexppeer *ep)
344 static struct dcexppeer *expectpeer(char *nick, struct fnetnode *fn)
346 struct dcexppeer *ep;
348 ep = smalloc(sizeof(*ep));
349 ep->nick = sstrdup(nick);
350 getfnetnode(ep->fn = fn);
351 ep->expire = timercallback(ntime() + 300, (void (*)(int, void *))exppeerexpire, ep);
360 static struct qcommand *newqcmd(struct qcommand **queue, char *string)
362 struct qcommand *new;
364 while(*queue != NULL)
365 queue = &(*queue)->next;
366 new = smalloc(sizeof(*new));
367 new->string = sstrdup(string);
373 static struct qcommand *ulqcmd(struct qcommand **queue)
375 struct qcommand *qcmd;
377 if((qcmd = *queue) == NULL)
383 static void freeqcmd(struct qcommand *qcmd)
389 static void hubrecvchat(struct socket *sk, struct fnetnode *fn, char *from, char *string)
391 wchar_t *chat, *wfrom, *wpeer;
393 struct fnetpeer *peer;
397 end = string + strlen(string);
398 while((p = strchr(string, 13)) != NULL)
399 memmove(p, p + 1, (end-- - p));
402 if((strlen(string) > strlen(from) + 2) && (*string == '<') && !memcmp(string + 1, from, strlen(from)) && (*(string + strlen(from) + 1) == '>'))
403 string += strlen(from) + 2;
404 if((wfrom = icmbstowcs(from, hub->charset)) == NULL)
406 wpeer = swcsdup(wfrom);
412 for(p = string + 1; *p; p++)
414 if((*p == ' ') || (*p == '>'))
422 if((wpeer = icmbstowcs(string + 1, hub->charset)) == NULL)
428 wpeer = swcsdup(L"");
430 if((chat = icmbstowcs(string, hub->charset)) == NULL)
440 if((peer = fnetfindpeer(fn, wfrom)) == NULL) /* Assume public chat */
441 fnethandlechat(fn, 1, wfrom, wpeer, chat);
443 fnethandlechat(fn, 0, wfrom, wpeer, chat);
445 fnethandlechat(fn, 1, L"", wpeer, chat);
453 static void peertimeout(int cancelled, struct dcpeer *peer)
455 peer->timeout = NULL;
461 static void sendadc(struct socket *sk, char *arg)
464 size_t bufsize, bufdata;
467 bufsize = bufdata = 0;
473 bufcat(buf, "\\s", 2);
474 } else if(*arg == '\n') {
475 bufcat(buf, "\\n", 2);
476 } else if(*arg == '\\') {
477 bufcat(buf, "\\\\", 2);
482 sockqueue(sk, buf, bufdata);
486 static void sendadcf(struct socket *sk, char *arg, ...)
492 buf = vsprintf2(arg, args);
500 static char **parseadc(char *args)
503 size_t retbufsize, retbufdata;
505 size_t bufsize, bufdata;
510 retbufsize = retbufdata = bufsize = bufdata = 0;
519 else if(*args != ' ')
523 if((*args == ' ') || (*args == 0))
526 addtobuf(retbuf, buf);
528 bufsize = bufdata = 0;
531 } else if(*args == '\\') {
534 addtobuf(buf, *args);
543 addtobuf(retbuf, NULL);
546 } else if((*args == 's') || (*args == ' ')) {
548 } else if(*args == 'n') {
550 } else if(*args == '\\') {
560 addtobuf(retbuf, NULL);
564 /* Macros useful in command handlers */
565 #define skipspace(s) ({if(((s) = strchr((s), ' ')) == NULL) return; else (s)++;})
566 #define qstr(sk, str) sockqueue(sk, str, strlen(str))
567 #define qstrf(sk, strandargs...) \
570 if((__buf__ = sprintf2(strandargs)) != NULL) { \
571 sockqueue(sk, __buf__, strlen(__buf__)); \
576 static char *tr(char *str, char *trans)
580 for(; *trans; trans += 2)
582 for(p = strchr(str, trans[0]); p != NULL; p = strchr(p, trans[0]))
588 static char *getadcid(struct dcpeer *peer)
595 if(!wcscmp(peer->transfer->path, L"files.xml") || !wcscmp(peer->transfer->path, L"files.xml.bz2") || !wcscmp(peer->transfer->path, L"MyList.DcLst"))
597 if(!isfilelist && (peer->transfer->hash != NULL) && isdchash(peer->transfer->hash) && supports(peer, "tthf"))
599 buf = base32encode(peer->transfer->hash->buf, 24);
600 ret = sprintf2("TTH/%.39s", buf);
603 if((buf = icwcstombs(peer->transfer->path, "UTF-8")) == NULL)
605 ret = pathnmdc2adc(buf);
612 static int trresumecb(struct transfer *transfer, wchar_t *cmd, wchar_t *arg, struct dcpeer *peer)
614 if(!wcscmp(cmd, L"resume"))
618 flog(LOG_WARNING, "filter returned no position for \"resume\" on transfer %i", transfer->id);
621 transfer->curpos = wcstol(arg, NULL, 10);
630 static void sendmynick(struct dcpeer *peer)
636 qstrf(peer->sk, "$MyNick %s|", icswcstombs(confgetstr("cli", "defnick"), peer->charset, "DoldaConnectUser-IN"));
638 qstrf(peer->sk, "$MyNick %s|", icswcstombs(fn->mynick, peer->charset, "DoldaConnectUser-IN"));
641 static void sendpeerlock(struct dcpeer *peer)
644 qstrf(peer->sk, "$Lock EXTENDEDPROTOCOLABCABCABCABCABCABC Pk=DCPLUSPLUS0.674ABCABC|");
646 qstrf(peer->sk, "$Lock EXTENDEDPROTOCOLABCABCABCABCABCABC Pk=DOLDA%sABCABCABC|", VERSION);
649 static void sendsupports(struct dcpeer *peer)
652 qstr(peer->sk, "$Supports MiniSlots XmlBZList ADCGet TTHL TTHF GetZBlock ZLIG |");
654 qstr(peer->sk, "$Supports MiniSlots XmlBZList ADCGet TTHL TTHF GetZBlock ZLIG|");
657 static void requestfile(struct dcpeer *peer)
661 if(peer->transfer->size == -1)
663 /* Use DCCHARSET for $Get paths until further researched... */
664 if((buf = icswcstombs(peer->transfer->path, DCCHARSET, NULL)) == NULL)
666 transferseterror(peer->transfer, TRNSE_NOTFOUND);
670 /* The transfer will be restarted later from
671 * cmd_filelength when it detects that the sizes
673 qstrf(peer->sk, "$Get %s$1|", buf);
676 if((peer->transfer->hash == NULL) && !peer->notthl)
678 if(supports(peer, "adcget") && supports(peer, "tthl"))
680 qstr(peer->sk, "$ADCGET");
681 sendadc(peer->sk, "tthl");
682 if((buf = getadcid(peer)) == NULL)
684 transferseterror(peer->transfer, TRNSE_NOTFOUND);
688 sendadc(peer->sk, buf);
690 sendadc(peer->sk, "0");
691 sendadc(peer->sk, "-1");
693 peer->fetchingtthl = 1;
699 if(forkfilter(peer->transfer))
701 flog(LOG_WARNING, "could not fork filter for transfer %i: %s", peer->transfer->id, strerror(errno));
705 CBREG(peer->transfer, trans_filterout, (int (*)(struct transfer *, wchar_t *, wchar_t *, void *))trresumecb, NULL, peer);
708 if(supports(peer, "adcget"))
710 qstr(peer->sk, "$ADCGET");
711 sendadc(peer->sk, "file");
712 if((buf = getadcid(peer)) == NULL)
714 transferseterror(peer->transfer, TRNSE_NOTFOUND);
718 sendadc(peer->sk, buf);
720 sendadcf(peer->sk, "%i", peer->transfer->curpos);
721 sendadcf(peer->sk, "%i", peer->transfer->size - peer->transfer->curpos);
723 } else if(supports(peer, "xmlbzlist")) {
724 if((buf = icswcstombs(peer->transfer->path, "UTF-8", NULL)) == NULL)
726 transferseterror(peer->transfer, TRNSE_NOTFOUND);
730 qstrf(peer->sk, "$UGetBlock %i %i %s|", peer->transfer->curpos, peer->transfer->size - peer->transfer->curpos, buf);
732 /* Use DCCHARSET for $Get paths until further researched... */
733 if((buf = icswcstombs(peer->transfer->path, DCCHARSET, NULL)) == NULL)
735 transferseterror(peer->transfer, TRNSE_NOTFOUND);
739 qstrf(peer->sk, "$Get %s$%i|", buf, peer->transfer->curpos + 1);
743 static void sendmyinfo(struct socket *sk, struct fnetnode *fn)
747 struct fnetnode *cfn;
751 qstrf(sk, "$MyINFO $ALL %s ", hub->nativenick);
752 buf = tr(icswcstombs(confgetstr("dc", "desc"), hub->charset, "Charset_conv_failure"), "$_|_");
753 qstrf(sk, "%s", buf);
755 for(cfn = fnetnodes; cfn != NULL; cfn = cfn->next)
757 if((cfn->state == FNN_EST) || (cfn->state == FNN_HS))
759 if(cfn->regstatus == FNNS_OP)
761 else if(cfn->regstatus == FNNS_REG)
767 qstrf(sk, "<%s V:%s,M:%c,H:%i/%i/%i,S:%i>",
768 (hub->dcppemu)?"++":"Dolda",
769 (hub->dcppemu)?"0.674":VERSION,
770 (tcpsock == NULL)?'P':'A',
772 confgetint("transfer", "slots")
775 buf = tr(icswcstombs(confgetstr("dc", "speedstring"), hub->charset, "Charset_conv_failure"), "$_|_");
776 qstrf(sk, "%s\x01$", buf);
777 buf = tr(icswcstombs(confgetstr("dc", "email"), hub->charset, "Charset_conv_failure"), "$_|_");
778 qstrf(sk, "%s$", buf);
779 qstrf(sk, "%llu$|", sharesize);
782 static void hubhandleaction(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
787 if(!strcmp(cmd, "$Lock"))
789 qstrf(sk, "$ValidateNick %s|", hub->nativenick);
790 } else if(!strcmp(cmd, "$Hello")) {
791 if(fn->state == FNN_HS)
793 qstrf(sk, "$Version 1,0091|");
794 qstrf(sk, "$GetNickList|");
796 fnetsetstate(fn, FNN_EST);
798 qstrf(sk, "$GetINFO %s %s|", args, hub->nativenick);
803 static void cmd_lock(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
810 if(!strncmp(args, "EXTENDEDPROTOCOL", 16))
812 if((p = strchr(args, ' ')) != NULL)
817 qstrf(sk, "$Supports UserCommand NoGetINFO NoHello UserIP2 TTHSearch GetZBlock |");
819 qstrf(sk, "$Supports UserCommand NoGetINFO NoHello UserIP2 TTHSearch GetZBlock|");
821 key = dcmakekey(args);
822 qstrf(sk, "$Key %s|", key);
824 hubhandleaction(sk, fn, cmd, args);
827 static void cmd_hubname(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
833 if(hub->nativename == NULL)
834 free(hub->nativename);
835 hub->nativename = sstrdup(args);
836 buf = icmbstowcs(args, hub->charset);
837 fnetsetname(fn, (buf == NULL)?L"Hubname conv error":buf);
840 hubhandleaction(sk, fn, cmd, args);
843 static void cmd_hello(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
849 if((nick = icmbstowcs(args, hub->charset)) == NULL)
851 if(strcmp(args, hub->nativenick) && (fnetfindpeer(fn, nick) == NULL))
852 fnetaddpeer(fn, nick, nick);
854 hubhandleaction(sk, fn, cmd, args);
857 static void cmd_quit(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
860 struct fnetpeer *peer;
864 if((nick = icmbstowcs(args, hub->charset)) == NULL)
866 if((peer = fnetfindpeer(fn, nick)) != NULL)
869 hubhandleaction(sk, fn, cmd, args);
872 static void cmd_nicklist(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
877 struct fnetpeer *peer, *npeer;
880 for(peer = fn->peers; peer != NULL; peer = peer->next)
881 peer->flags.b.delete = 1;
882 while((p = strstr(args, "$$")) != NULL)
885 if((buf = icmbstowcs(args, hub->charset)) != NULL)
887 if((peer = fnetfindpeer(fn, buf)) == NULL)
888 peer = fnetaddpeer(fn, buf, buf);
890 peer->flags.b.delete = 0;
892 qstrf(sk, "$GetINFO %s %s|", args, hub->nativenick);
896 for(peer = fn->peers; peer != NULL; peer = npeer)
899 if(peer->flags.b.delete)
902 hubhandleaction(sk, fn, cmd, args);
905 static void cmd_oplist(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
910 struct fnetpeer *peer;
913 for(peer = fn->peers; peer != NULL; peer = peer->next)
914 peer->flags.b.op = 0;
915 while((p = strstr(args, "$$")) != NULL)
918 if((buf = icmbstowcs(args, hub->charset)) != NULL)
920 if((peer = fnetfindpeer(fn, buf)) != NULL)
921 peer->flags.b.op = 1;
926 hubhandleaction(sk, fn, cmd, args);
929 static void cmd_myinfo(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
932 wchar_t *buf, *wp, *wp2;
934 struct fnetpeer *peer;
939 if(strncmp(p, "$ALL ", 5))
942 if((p2 = strchr(p, ' ')) == NULL)
945 if((buf = icmbstowcs(p, hub->charset)) == NULL)
947 if((peer = fnetfindpeer(fn, buf)) == NULL)
948 peer = fnetaddpeer(fn, buf, buf);
951 if((p2 = strstr(p, "$ $")) == NULL)
954 if((buf = icmbstowcs(p, hub->charset)) == NULL)
956 if((wcslen(buf) > 0) && (buf[wcslen(buf) - 1] == L'>') && ((wp = wcsrchr(buf, L'<')) != NULL))
958 buf[wcslen(buf) - 1] = L'\0';
960 if((wp2 = wcschr(wp, L' ')) != NULL)
963 fnetpeersetstr(peer, L"dc-client", wp);
967 if((wp2 = wcschr(wp, L',')) != NULL)
971 swprintf(abuf, 10, L"dc-tag-%lc", wp[0]);
972 fnetpeersetstr(peer, abuf, wp + 2);
974 } while(wp2 != NULL);
977 fnetpeersetstr(peer, L"descr", buf);
980 if((p2 = strchr(p, '$')) == NULL)
983 if((buf = icmbstowcs(p, hub->charset)) == NULL)
985 fnetpeersetstr(peer, L"dc-speed", buf);
988 if((p2 = strchr(p, '$')) == NULL)
991 if((buf = icmbstowcs(p, hub->charset)) == NULL)
993 fnetpeersetstr(peer, L"email", buf);
998 fnetpeersetlnum(peer, L"share", strtoll(p, NULL, 10));
999 hubhandleaction(sk, fn, cmd, args);
1002 /* I do not implement the fully in that I do not disconnect from the
1003 * old hub. I do this since I believe that if the hub owner really
1004 * wants to get rid of us, then it is his responsibility to disconnect
1006 static void cmd_forcemove(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1009 struct fnetnode *newfn;
1013 if(strchr(args, ':') == NULL)
1015 args = strcpy(smalloc(strlen(args) + 5), args);
1016 strcat(args, ":411");
1021 if((newfn = fnetinitconnect(L"dc", fn->owner, args, NULL)) != NULL)
1023 linkfnetnode(newfn);
1026 hubhandleaction(sk, fn, cmd, args);
1031 static char *getdcpath(struct sharecache *node, size_t *retlen, char *charset)
1036 if(node->parent == NULL)
1038 if(node->parent == shareroot)
1040 if((buf = icwcstombs(node->name, charset)) == NULL)
1043 *retlen = strlen(buf);
1046 if((buf2 = icwcstombs(node->name, charset)) == NULL)
1048 if((buf = getdcpath(node->parent, &len, charset)) == NULL)
1053 len2 = strlen(buf2);
1054 buf = srealloc(buf, len + 1 + len2 + 1);
1056 strcpy(buf + len, buf2);
1057 buf[len + len2] = 0;
1060 *retlen = len + len2;
1066 * This is the main share searching function for Direct Connect
1067 * peers. Feel free to optimize it if you feel the need for it. I
1068 * haven't ever seen it take any noticable CPU time anyway, so I
1069 * haven't felt that need.
1071 * It may feel dubious to just return the directory when all terms are
1072 * satisfied rather than all the files in it, but it really benefits
1073 * everyone: Less cycles used for us, less UDP squelching for active
1074 * searchers, and less bandwidth waste for hubs when serving passive
1077 static void cmd_search(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1082 char *prefix, *infix, *postfix, *buf, *buf2;
1084 struct sockaddr_in addr;
1085 struct sharecache *node;
1086 int minsize, maxsize;
1089 int termnum, satisfied, skipcheck;
1090 int level, tersat[32];
1095 if((p = strchr(args, ' ')) == NULL)
1099 memset(terms, 0, sizeof(terms));
1100 prefix = infix = postfix = NULL;
1104 if(!strncmp(args, "Hub:", 4))
1106 if(!strcmp(cmd, "$MultiSearch"))
1108 if(!strcmp(args + 4, hub->nativenick))
1110 prefix = sprintf2("$SR %s ", hub->nativenick);
1111 infix = sprintf2(" %i/%i\005", slotsleft(), confgetint("transfer", "slots"));
1112 postfix = sprintf2(" (%s)\005%s|", formataddress(fn->sk->remote, fn->sk->remotelen), args + 4);
1116 if((p2 = strchr(args, ':')) == NULL)
1119 addr.sin_family = AF_INET;
1120 if(!inet_aton(args, &addr.sin_addr))
1122 addr.sin_port = htons(atoi(p2));
1123 prefix = sprintf2("$SR %s ", hub->nativenick);
1124 infix = sprintf2(" %i/%i\005", slotsleft(), confgetint("transfer", "slots"));
1125 postfix = sprintf2(" (%s)|", formataddress(fn->sk->remote, fn->sk->remotelen));
1126 netdgramconn(dsk = netdupsock(udpsock), (struct sockaddr *)&addr, sizeof(addr));
1129 minsize = maxsize = -1;
1138 if((*(p++) == 'T') && (minsize == 0))
1145 if((p2 = strchr(p, '?')) == NULL)
1160 if((*p2 == 0) || (*p2 == '$'))
1168 if(!dotth && !strncmp(p, "TTH:", 4))
1171 if(((buf = base32decode(p + 4, &buflen)) == NULL) || (buflen != 24))
1176 memcpy(hashtth, buf, 24);
1179 if((terms[termnum] = icmbstowcs(p, hub->charset)) != NULL)
1190 node = shareroot->child;
1192 for(i = 0; i < termnum; i++)
1198 if(node->f.b.type == FILE_REG)
1200 if((minsize >= 0) && (node->size < minsize))
1202 if((maxsize >= 0) && (node->size > maxsize))
1205 if(!skipcheck && dotth)
1207 if((node->f.b.type != FILE_REG) || (node->f.b.hastth && memcmp(hashtth, node->hashtth, 24)))
1212 for(i = 0; i < termnum; i++)
1216 if(wcsexists(node->name, terms[i]))
1220 } else if(node->child == NULL) {
1225 if(!skipcheck && (satisfied == termnum))
1227 /* Use DCCHARSET in $Get paths until further researched... */
1228 if((buf = getdcpath(node, NULL, DCCHARSET)) != NULL)
1230 if(node->f.b.hastth)
1232 buf2 = base32encode(node->hashtth, 24);
1233 qstrf(dsk, "%s%s\005%i%sTTH:%.39s%s", prefix, buf, node->size, infix, buf2, postfix);
1236 qstrf(dsk, "%s%s\005%i%s%s%s", prefix, buf, node->size, infix, hub->nativename, postfix);
1241 if((!skipcheck && (satisfied == termnum)) || (node->child == NULL))
1243 while(node->next == NULL)
1245 if((node = node->parent) == shareroot)
1249 if(node == shareroot)
1251 for(i = 0; i < termnum; i++)
1253 if(tersat[i] >= level)
1266 hubhandleaction(sk, fn, cmd, args);
1277 for(i = 0; (i < 32) && (terms[i] != NULL); i++)
1281 static void cmd_connecttome(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1285 struct socket *newsk;
1286 struct sockaddr_in addr;
1289 if((p = strchr(args, ' ')) == NULL)
1292 if(strcmp(args, hub->nativenick))
1294 addr.sin_family = AF_INET;
1296 if((p = strchr(args, ':')) == NULL)
1299 addr.sin_port = htons(atoi(p));
1300 if(!inet_aton(args, &addr.sin_addr))
1302 newsk = netcsconn((struct sockaddr *)&addr, sizeof(addr), (void (*)(struct socket *, int, void *))peerconnect, fn);
1304 hubhandleaction(sk, fn, cmd, args);
1307 static void sendctm(struct socket *sk, char *nick)
1309 struct sockaddr *addr;
1314 if(sockgetremotename2(tcpsock, sk, &addr, &addrlen) < 0)
1316 if(addr->sa_family == AF_INET)
1317 qstrf(sk, "$ConnectToMe %s %s|", nick, formataddress(addr, addrlen));
1319 flog(LOG_WARNING, "Direct Connect TCP socket is suddenly not AF_INET, but %i", addr->sa_family);
1323 static void cmd_revconnecttome(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1329 if((p = strchr(args, ' ')) == NULL)
1332 if(strcmp(p, hub->nativenick))
1335 expectpeer(args, fn);
1336 hubhandleaction(sk, fn, cmd, args);
1339 static void cmd_getnetinfo(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1342 struct fnetnode *node;
1347 for(node = fnetnodes; node != NULL; node = node->next)
1349 if(node->state == FNN_EST)
1352 qstrf(sk, "$NetInfo %i$%i$%c$0|", confgetint("transfer", "slots"), numhubs, (tcpsock == NULL)?'P':'A');
1353 hubhandleaction(sk, fn, cmd, args);
1356 static void cmd_to(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1363 if((p2 = strchr(p, ' ')) == NULL)
1367 if((p2 = strchr(p, ' ')) == NULL)
1370 if(strcmp(p, "From:"))
1373 if((p2 = strstr(p, " $")) == NULL)
1377 hubrecvchat(fn->sk, fn, p, p2);
1378 hubhandleaction(sk, fn, cmd, args);
1381 static void cmd_sr(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1385 char *nick, *filename, *hubname;
1389 wchar_t *wnick, *wfile;
1393 if((p2 = strchr(p, ' ')) == NULL)
1398 if((p2 = strchr(p, 5)) == NULL)
1402 if((p2 = strchr(p, ' ')) == NULL)
1407 if((p2 = strchr(p, '/')) == NULL)
1412 if((p2 = strchr(p, 5)) == NULL)
1416 if((p2 = strstr(p, " (")) == NULL)
1419 if((wnick = icmbstowcs(nick, hub->charset)) == NULL)
1421 /* Use DCCHARSET in $Get paths until further researched... */
1422 if((wfile = icmbstowcs(filename, DCCHARSET)) == NULL)
1427 sr = newsrchres(&dcnet, wfile, wnick);
1428 if(sr->peernick != NULL)
1430 sr->peernick = swcsdup(wnick);
1435 if(!strncmp(hubname, "TTH:", 4))
1437 if((buf = base32decode(hubname + 4, &buflen)) != NULL)
1440 sr->hash = newhash(L"TTH", 24, buf);
1444 getfnetnode(sr->fn = fn);
1447 hubhandleaction(sk, fn, cmd, args);
1450 static void cmd_usercommand(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1452 /* Do nothing for now. */
1455 static void cmd_getpass(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1462 pw = wpfind(fn->args, L"password");
1463 if((pw == NULL) || ((mbspw = icwcstombs(pw, hub->charset)) == NULL))
1468 qstrf(sk, "$MyPass %s|", mbspw);
1470 fn->regstatus = FNNS_REG;
1471 hubhandleaction(sk, fn, cmd, args);
1474 static void cmd_logedin(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1479 fn->regstatus = FNNS_OP;
1480 hubhandleaction(sk, fn, cmd, args);
1483 static void cmd_mynick(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1485 struct dcexppeer *expect;
1488 if(peer->nativename != NULL)
1489 free(peer->nativename);
1490 peer->nativename = sstrdup(args);
1491 if(peer->wcsname != NULL)
1492 free(peer->wcsname);
1493 if((peer->wcsname = icmbstowcs(peer->nativename, peer->charset)) == NULL)
1500 for(expect = expected; expect != NULL; expect = expect->next)
1502 if(!strcmp(expect->nick, args))
1509 hub = expect->fn->data;
1510 peer->fn = expect->fn;
1511 getfnetnode(peer->fn);
1512 peer->dcppemu = hub->dcppemu;
1513 freeexppeer(expect);
1518 static void cmd_direction(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1522 struct transfer *transfer;
1524 if((p = strchr(args, ' ')) == NULL)
1527 if(!strcmp(args, "Upload"))
1529 if(!strcmp(args, "Download"))
1533 if((peer->transfer == NULL) || (mydir != peer->direction))
1538 if(peer->direction == TRNSD_DOWN)
1541 if(peer->wcsname == NULL)
1546 peer->direction = mydir;
1547 if(peer->direction == TRNSD_UP)
1549 if(confgetint("transfer", "ulquota") && hasupload(&dcnet, peer->wcsname))
1554 transfer = newupload(peer->fn, &dcnet, peer->wcsname, &dctransfer, peer);
1556 if((transfer = finddownload(peer->wcsname)) == NULL)
1561 transferattach(transfer, &dctransfer, peer);
1562 transfersetstate(transfer, TRNS_HS);
1564 transfersetnick(transfer, peer->wcsname);
1565 peer->transfer = transfer;
1568 qstrf(sk, "$Direction %s %i|", (peer->direction == TRNSD_UP)?"Upload":"Download", rand() % 10000);
1569 if(peer->key != NULL)
1570 qstrf(sk, "$Key %s|", peer->key);
1571 if(peer->direction == TRNSD_DOWN)
1576 static void cmd_peerlock(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1579 struct transfer *transfer;
1581 if((p = strchr(args, ' ')) == NULL)
1584 if(!strncmp(args, "EXTENDEDPROTOCOL", 16))
1586 key = dcmakekey(args);
1589 if(peer->wcsname == NULL)
1598 if((transfer = finddownload(peer->wcsname)) == NULL)
1600 if(confgetint("transfer", "ulquota") && hasupload(&dcnet, peer->wcsname))
1605 peer->direction = TRNSD_UP;
1606 transfer = newupload(peer->fn, &dcnet, peer->wcsname, &dctransfer, peer);
1608 peer->direction = TRNSD_DOWN;
1609 transferattach(transfer, &dctransfer, peer);
1610 transfersetstate(transfer, TRNS_HS);
1612 transfersetnick(transfer, peer->wcsname);
1613 peer->transfer = transfer;
1614 qstrf(sk, "$Direction %s %i|", (peer->direction == TRNSD_UP)?"Upload":"Download", rand() % 10000);
1615 qstrf(sk, "$Key %s|", key);
1618 if(peer->key != NULL)
1624 static void cmd_key(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1629 static void startdl(struct dcpeer *peer)
1631 if(peer->timeout != NULL)
1632 canceltimer(peer->timeout);
1633 peer->state = PEER_TRNS;
1634 transferstartdl(peer->transfer, peer->sk);
1635 peer->sk->readcb = (void (*)(struct socket *, void *))transread;
1636 peer->sk->errcb = (void (*)(struct socket *, int, void *))transerr;
1639 static void startul(struct dcpeer *peer)
1641 if(peer->timeout != NULL)
1642 canceltimer(peer->timeout);
1643 peer->state = PEER_TRNS;
1644 transferstartul(peer->transfer, peer->sk);
1645 peer->sk->writecb = (void (*)(struct socket *, void *))transwrite;
1648 static void cmd_filelength(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1651 struct transfer *transfer;
1653 if(peer->transfer == NULL)
1659 if(peer->transfer->size != size)
1661 transfersetsize(peer->transfer, size);
1662 transfer = peer->transfer;
1664 trytransferbypeer(transfer->fnet, transfer->peerid);
1668 qstr(peer->sk, "$Send|");
1671 static void cmd_error(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1673 if(peer->fetchingtthl)
1675 peer->fetchingtthl = 0;
1680 if((peer->transfer != NULL) && (peer->transfer->dir == TRNSD_DOWN))
1682 transferseterror(peer->transfer, TRNSE_NOTFOUND);
1683 resettransfer(peer->transfer);
1689 static void cmd_maxedout(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1691 if((peer->transfer != NULL) && (peer->transfer->dir == TRNSD_DOWN))
1693 transferseterror(peer->transfer, TRNSE_NOSLOTS);
1694 resettransfer(peer->transfer);
1707 {"MyList.DcLst", &hmlistname, updatehmlist},
1708 {"files.xml", &xmllistname, updatexmllist},
1709 {"files.xml.bz2", &xmlbz2listname, updatexmlbz2list},
1713 static int openfilelist(char *name)
1718 for(i = 0; lists[i].name != NULL; i++)
1720 if(!strcmp(name, lists[i].name))
1724 if(lists[i].name == NULL)
1727 if((*lists[i].file == NULL) || ((fd = open(*lists[i].file, O_RDONLY)) < 0))
1729 if((fd < 0) && ((*lists[i].file == NULL) || ((fd = open(*lists[i].file, O_RDONLY)) < 0)))
1732 flog(LOG_ERR, "could not open filelist tempfile: %s", strerror(errno));
1739 static struct sharecache *findbytth(char *tth32)
1743 struct sharecache *node;
1745 if((buf = base32decode(tth32, &buflen)) == NULL)
1752 for(node = shareroot->child; node != NULL; node = nextscnode(node))
1754 if(node->f.b.hastth && !memcmp(node->hashtth, buf, 24))
1761 static struct sharecache *resdcpath(char *path, char *charset, char sep)
1763 struct sharecache *node;
1770 if((p2 = strchr(p, sep)) != NULL)
1772 if((node = findcache(node, icsmbstowcs(p, charset, L""))) == NULL)
1779 static void cmd_get(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1784 struct sharecache *node;
1785 struct socket *lesk;
1789 if(peer->transfer == NULL)
1794 if((p = strchr(args, '$')) == NULL)
1800 if((offset = (atoi(p) - 1)) < 0)
1805 if(((fd = openfilelist(args)) < 0) && (errno != 0))
1807 qstr(sk, "$Error Could not send file list|");
1810 } else if(fd >= 0) {
1811 if((buf2 = icsmbstowcs(args, DCCHARSET, NULL)) != NULL)
1812 transfersetpath(peer->transfer, buf2);
1813 peer->transfer->flags.b.minislot = 1;
1817 /* Use DCCHARSET in $Get paths until further researched... */
1818 if((node = resdcpath(args, DCCHARSET, '\\')) == NULL)
1820 qstrf(sk, "$Error File not in share|");
1824 if((fd = opensharecache(node)) < 0)
1826 qstrf(sk, "$Error %s|", strerror(errno));
1830 buf = getfspath(node);
1831 if((buf2 = icsmbstowcs(buf, NULL, NULL)) == NULL)
1832 flog(LOG_WARNING, "could not convert native path into a wcs (%s): %s", buf, strerror(errno));
1834 transfersetpath(peer->transfer, buf2);
1837 if(fstat(fd, &sb) < 0)
1840 flog(LOG_WARNING, "could not stat file %ls: %s", node->name, strerror(errno));
1841 qstrf(sk, "$Error|");
1845 if(sb.st_size < 65536)
1846 peer->transfer->flags.b.minislot = 1;
1847 if(!peer->transfer->flags.b.minislot && (slotsleft() < 1)) {
1849 qstr(sk, "$MaxedOut|");
1853 if((offset != 0) && (lseek(fd, offset, SEEK_SET) < 0))
1856 qstrf(sk, "$Error Offset out of range|");
1860 lesk = wrapsock(fd);
1861 transferprepul(peer->transfer, sb.st_size, offset, -1, lesk);
1863 qstrf(sk, "$FileLength %i|", peer->transfer->size);
1866 static void cmd_send(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1868 if(peer->transfer == NULL)
1873 if(peer->transfer->localend == NULL)
1882 static void cmd_supports(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1887 size_t arrsize, arrdata;
1889 if(peer->supports != NULL)
1891 for(i = 0; peer->supports[i] != NULL; i++)
1892 free(peer->supports[i]);
1893 free(peer->supports);
1896 arrsize = arrdata = 0;
1900 if((p2 = strchr(p, ' ')) != NULL)
1904 addtobuf(arr, sstrdup(p));
1905 } while((p = p2) != NULL);
1906 addtobuf(arr, NULL);
1907 peer->supports = arr;
1910 static void cmd_getblock(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1914 int start, numbytes;
1915 char *charset, *buf;
1917 struct sharecache *node;
1919 struct socket *lesk;
1921 if(peer->transfer == NULL)
1927 if((p2 = strchr(p, ' ')) == NULL)
1935 if((p2 = strchr(p, ' ')) == NULL)
1943 if(!strcmp(cmd, "$UGetBlock") || !strcmp(cmd, "$UGetZBlock"))
1946 /* Use DCCHARSET in $Get paths until further researched... */
1947 charset = DCCHARSET;
1948 if(!strcmp(cmd, "$GetZBlock") || !strcmp(cmd, "$UGetZBlock"))
1949 initcompress(peer, CPRS_ZLIB);
1950 if(((fd = openfilelist(p)) < 0) && (errno != 0))
1952 qstr(sk, "$Error Could not send file list|");
1954 } else if(fd >= 0) {
1955 if((buf2 = icsmbstowcs(args, charset, NULL)) != NULL)
1956 transfersetpath(peer->transfer, buf2);
1957 peer->transfer->flags.b.minislot = 1;
1961 if((node = resdcpath(p, charset, '\\')) == NULL)
1963 qstr(sk, "$Error File not in cache|");
1966 if((fd = opensharecache(node)) < 0)
1968 qstrf(sk, "$Error %s|", strerror(errno));
1971 buf = getfspath(node);
1972 if((buf2 = icsmbstowcs(buf, NULL, NULL)) == NULL)
1973 flog(LOG_WARNING, "could not convert native path into a wcs (%s): %s", buf, strerror(errno));
1975 transfersetpath(peer->transfer, buf2);
1978 if(fstat(fd, &sb) < 0)
1981 flog(LOG_WARNING, "could not stat file %ls: %s", node->name, strerror(errno));
1982 qstr(sk, "$Error|");
1985 if(sb.st_size < 65536)
1986 peer->transfer->flags.b.minislot = 1;
1987 if(!peer->transfer->flags.b.minislot && (slotsleft() < 1)) {
1989 qstr(sk, "$MaxedOut|");
1992 if((start != 0) && ((start >= sb.st_size) || (lseek(fd, start, SEEK_SET) < 0)))
1995 qstr(sk, "$Error Offset out of range|");
1998 if((numbytes < 0) || (start + numbytes > sb.st_size))
1999 numbytes = sb.st_size - start;
2000 lesk = wrapsock(fd);
2001 transferprepul(peer->transfer, sb.st_size, start, start + numbytes, lesk);
2003 qstrf(sk, "$Sending %i|", numbytes);
2007 static void cmd_adcget(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2011 int start, numbytes;
2012 struct sharecache *node;
2014 struct socket *lesk;
2018 if(peer->transfer == NULL)
2023 if((argv = parseadc(args)) == NULL)
2028 if(parrlen(argv) < 4)
2033 start = atoi(argv[2]);
2034 numbytes = atoi(argv[3]);
2037 if(((fd = openfilelist(argv[1])) < 0) && (errno != 0))
2039 qstr(sk, "$Error Could not send file list|");
2041 } else if(fd >= 0) {
2042 if((wbuf = icsmbstowcs(argv[1], "UTF-8", NULL)) != NULL)
2043 transfersetpath(peer->transfer, wbuf);
2044 peer->transfer->flags.b.minislot = 1;
2048 if(!strncmp(argv[1], "TTH/", 4))
2050 if((node = findbytth(argv[1] + 4)) == NULL)
2052 qstr(sk, "$Error File not in cache|");
2056 if((node = resdcpath((argv[1][0] == '/')?(argv[1] + 1):(argv[1]), "UTF-8", '/')) == NULL)
2058 qstr(sk, "$Error File not in cache|");
2062 if((fd = opensharecache(node)) < 0)
2064 qstrf(sk, "$Error %s|", strerror(errno));
2067 buf = getfspath(node);
2068 if((wbuf = icsmbstowcs(buf, NULL, NULL)) == NULL)
2069 flog(LOG_WARNING, "could not convert native path into a wcs (%s): %s", buf, strerror(errno));
2071 transfersetpath(peer->transfer, wbuf);
2074 if(!strcmp(argv[0], "file"))
2076 for(i = 4; argv[i] != NULL; i++)
2078 if(!strcmp(argv[i], "ZL1"))
2079 initcompress(peer, CPRS_ZLIB);
2081 if(fstat(fd, &sb) < 0)
2083 flog(LOG_WARNING, "could not stat file %ls: %s", node->name, strerror(errno));
2084 qstr(sk, "$Error|");
2087 if(sb.st_size < 65536)
2088 peer->transfer->flags.b.minislot = 1;
2089 if(!peer->transfer->flags.b.minislot && (slotsleft() < 1)) {
2090 qstr(sk, "$MaxedOut|");
2093 if((start != 0) && ((start >= sb.st_size) || (lseek(fd, start, SEEK_SET) < 0)))
2095 qstr(sk, "$Error Offset out of range|");
2098 if((numbytes < 0) || (start + numbytes > sb.st_size))
2099 numbytes = sb.st_size - start;
2100 lesk = wrapsock(fd);
2101 transferprepul(peer->transfer, sb.st_size, start, start + numbytes, lesk);
2104 qstr(sk, "$ADCSND");
2105 sendadc(sk, "file");
2106 sendadc(sk, argv[1]);
2107 sendadcf(sk, "%i", start);
2108 sendadcf(sk, "%i", numbytes);
2109 if(peer->compress == CPRS_ZLIB)
2113 } else if(!strcmp(argv[0], "tthl")) {
2115 * XXX: Implement full TTHL support.
2117 * In the meantime, this is better than nothing, since it at
2118 * least allows fetching of the TTH root if it isn't already
2123 qstr(sk, "$Error no TTHL data for virtual files|");
2126 qstr(sk, "$ADCSND");
2127 sendadc(sk, "tthl");
2128 sendadc(sk, argv[1]);
2132 sockqueue(sk, node->hashtth, 24);
2134 qstr(sk, "$Error Namespace not implemented|");
2144 static void handletthl(struct dcpeer *peer)
2148 while(peer->inbufdata >= 24)
2150 pushtigertree(&peer->tth, peer->inbuf);
2151 memmove(peer->inbuf, peer->inbuf + 24, peer->inbufdata -= 24);
2152 peer->curread += 24;
2154 if(peer->curread >= peer->totalsize)
2156 if(peer->timeout == NULL)
2157 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
2158 peer->state = PEER_CMD;
2159 synctigertree(&peer->tth);
2160 restigertree(&peer->tth, buf);
2161 transfersethash(peer->transfer, newhash(L"TTH", 24, buf));
2166 static void cmd_adcsnd(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2169 int start, numbytes;
2171 if(peer->transfer == NULL)
2176 if((argv = parseadc(args)) == NULL)
2181 if(parrlen(argv) < 4)
2186 start = atoi(argv[2]);
2187 numbytes = atoi(argv[3]);
2188 if(!strcmp(argv[0], "tthl"))
2190 if((start != 0) || (numbytes % 24 != 0))
2192 /* Weird. Bail out. */
2196 if(peer->timeout != NULL)
2197 canceltimer(peer->timeout);
2198 peer->state = PEER_TTHL;
2199 peer->totalsize = numbytes;
2201 peer->fetchingtthl = 0;
2202 inittigertree(&peer->tth);
2204 } else if(!strcmp(argv[0], "file")) {
2205 if(start != peer->transfer->curpos)
2210 if(start + numbytes != peer->transfer->size)
2212 transfersetsize(peer->transfer, start + numbytes);
2217 if(peer->inbufdata > 0)
2219 sockpushdata(sk, peer->inbuf, peer->inbufdata);
2220 peer->inbufdata = 0;
2221 transread(sk, peer);
2224 /* We certainly didn't request this...*/
2233 static void cmd_sending(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2237 if(peer->transfer == NULL)
2242 numbytes = atoi(args);
2243 if(peer->transfer->size - peer->transfer->curpos != numbytes)
2245 transfersetsize(peer->transfer, peer->transfer->curpos + numbytes);
2250 if(peer->inbufdata > 0)
2252 sockpushdata(sk, peer->inbuf, peer->inbufdata);
2253 peer->inbufdata = 0;
2254 transread(sk, peer);
2260 static void cmd_(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
2265 hubhandleaction(sk, fn, cmd, args);
2269 static void cmd_(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2275 static int hubreqconn(struct fnetpeer *peer)
2280 if((peer->fn->state != FNN_EST) || (peer->fn->fnet != &dcnet))
2285 if((hub = peer->fn->data) == NULL)
2290 if((mbsnick = icwcstombs(peer->id, hub->charset)) == NULL)
2291 return(1); /* Shouldn't happen, of course, but who knows... */
2294 sendctm(peer->fn->sk, mbsnick);
2295 expectpeer(mbsnick, peer->fn);
2297 qstrf(peer->fn->sk, "$RevConnectToMe %s %s|", hub->nativenick, mbsnick);
2303 static int hubsendchat(struct fnetnode *fn, int public, wchar_t *to, wchar_t *string)
2306 char *mbsstring, *mbsto;
2309 if((mbsto = icwcstombs(to, hub->charset)) == NULL)
2314 if((mbsstring = icwcstombs(string, hub->charset)) == NULL)
2319 if((strchr(mbsto, '|') != NULL) || (strchr(mbsto, ' ') != NULL))
2326 if(strchr(mbsstring, '|') != NULL)
2337 qstrf(fn->sk, "<%s> %s|", hub->nativenick, mbsstring);
2339 qstrf(fn->sk, "$To: %s From: %s $<%s> %s|", mbsto, hub->nativenick, hub->nativenick, mbsstring);
2342 qstrf(fn->sk, "$To: %s From: %s $<%s> %s|", mbsto, hub->nativenick, hub->nativenick, mbsstring);
2349 static void findsizelimit(struct sexpr *sexpr, int *min, int *max)
2351 int minl, maxl, minr, maxr, retmin, retmax;
2356 findsizelimit(sexpr->l, &minl, &maxl);
2357 findsizelimit(sexpr->r, &minr, &maxr);
2358 retmin = (minl > minr)?minl:minr;
2359 if((maxl != -1) && (maxr != -1))
2360 retmax = (maxl < maxr)?maxl:maxr;
2369 findsizelimit(sexpr->l, &minl, &maxl);
2370 findsizelimit(sexpr->r, &minr, &maxr);
2371 retmin = (minl < minr)?minl:minr;
2372 if((maxl == -1) || (maxr == -1))
2375 retmax = (maxl > maxr)?maxl:maxr;
2378 findsizelimit(sexpr->l, &minl, &maxl);
2379 if((minl == 0) && (maxl == -1)) /* Interval is unspecified */
2383 } else if((minl == 0) && (maxl != -1)) {
2386 } else if((minl != 0) && (maxl == -1)) {
2389 } else { /* This would yield two seperate intervals, which DC cannot handle */
2395 retmax = sexpr->d.n - 1;
2398 retmin = sexpr->d.n;
2399 retmax = sexpr->d.n;
2402 retmin = sexpr->d.n + 1;
2416 static struct hash *findsehash(struct sexpr *sexpr)
2418 struct hash *h1, *h2;
2423 if((h1 = findsehash(sexpr->l)) != NULL)
2425 if((h1 = findsehash(sexpr->r)) != NULL)
2429 if((h1 = findsehash(sexpr->l)) == NULL)
2431 if((h2 = findsehash(sexpr->r)) == NULL)
2437 if(!wcscmp(sexpr->d.hash->algo, L"TTH"))
2438 return(sexpr->d.hash);
2445 static int hubsearch(struct fnetnode *fn, struct search *srch, struct srchfnnlist *ln)
2448 struct wcslist *list, *cur;
2449 char *sstr, *buf, *p;
2450 size_t sstrsize, sstrdata;
2451 struct sockaddr *name;
2453 int minsize, maxsize;
2457 if((fn->state != FNN_EST) || (fn->sk == NULL) || (fn->sk->state != SOCK_EST))
2459 list = findsexprstrs(srch->sexpr);
2460 findsizelimit(srch->sexpr, &minsize, &maxsize);
2461 hash = findsehash(srch->sexpr);
2462 if((minsize != 0) && (maxsize != -1))
2464 /* Choose either minsize or maxsize by trying to determine
2465 * which choice will be most restrictive. The result can be
2466 * approximative at best anyway, so don't try too hard... */
2467 if((50000000 - maxsize) > (minsize - 50000000))
2473 sstrsize = sstrdata = 0;
2474 if((hash != NULL) && (hash->len == 24))
2476 /* Prioritize hash searches above all else */
2477 bufcat(sstr, "F?T?0?9?TTH:", 12);
2478 buf = base32encode(hash->buf, hash->len);
2480 bufcat(sstr, buf, 39);
2485 sizebuf2(sstr, sstrdata + 32, 1);
2486 sstrdata += snprintf(sstr + sstrdata, sstrsize - sstrdata, "T?F?%i?1?", minsize);
2487 } else if(maxsize != -1) {
2488 sizebuf2(sstr, sstrdata + 32, 1);
2489 sstrdata += snprintf(sstr + sstrdata, sstrsize - sstrdata, "T?T?%i?1?", maxsize);
2491 bufcat(sstr, "F?F?0?1?", 8);
2495 for(cur = list; cur != NULL; cur = cur->next)
2497 /* Use DCCHARSET in $Get paths until further researched... */
2498 if((buf = icwcstombs(cur->str, DCCHARSET)) == NULL)
2500 /* Can't find anything anyway if the search expression
2501 * requires characters outside DC's charset. There's
2502 * nothing technically wrong with the search itself,
2503 * however, so return success. This should be
2504 * considered as an optimization. */
2511 addtobuf(sstr, '$');
2513 * It probably doesn't hurt if buf contains any extra
2514 * dollar signs - it will just result in extra search
2515 * terms, and the extraneous results will be filtered by
2516 * the search layer anyway. It hurts if it contains any
2517 * pipes, though, so let's sell them for money.
2519 for(p = buf; *p; p++)
2524 bufcat(sstr, buf, strlen(buf));
2528 /* Will match all files... :-/ */
2529 addtobuf(sstr, '.');
2535 if(sockgetremotename2(udpsock, fn->sk, &name, &namelen) < 0)
2537 flog(LOG_WARNING, "cannot get address of UDP socket");
2539 qstrf(fn->sk, "$Search %s %s|", formataddress(name, namelen), sstr);
2543 qstrf(fn->sk, "$Search Hub:%s %s|", hub->nativenick, sstr);
2547 fn->lastsrch = time(NULL);
2555 #define cc(c) ((void (*)(struct socket *, void *, char *, char *))(c))
2556 static struct command hubcmds[] =
2558 {"$Lock", cc(cmd_lock)},
2559 {"$HubName", cc(cmd_hubname)},
2560 {"$Hello", cc(cmd_hello)},
2561 {"$Quit", cc(cmd_quit)},
2562 {"$NickList", cc(cmd_nicklist)},
2563 {"$OpList", cc(cmd_oplist)},
2564 {"$MyINFO", cc(cmd_myinfo)},
2565 {"$ForceMove", cc(cmd_forcemove)},
2566 {"$Search", cc(cmd_search)},
2567 {"$MultiSearch", cc(cmd_search)},
2568 {"$ConnectToMe", cc(cmd_connecttome)},
2569 {"$RevConnectToMe", cc(cmd_revconnecttome)},
2570 {"$GetNetInfo", cc(cmd_getnetinfo)},
2571 {"$To:", cc(cmd_to)},
2572 {"$SR", cc(cmd_sr)},
2573 {"$UserCommand", cc(cmd_usercommand)},
2574 {"$GetPass", cc(cmd_getpass)},
2575 {"$LogedIn", cc(cmd_logedin)}, /* sic */
2579 static struct command peercmds[] =
2581 {"$MyNick", cc(cmd_mynick)},
2582 {"$Lock", cc(cmd_peerlock)},
2583 {"$Direction", cc(cmd_direction)},
2584 {"$Key", cc(cmd_key)},
2585 {"$FileLength", cc(cmd_filelength)},
2586 {"$Error", cc(cmd_error)},
2587 {"$MaxedOut", cc(cmd_maxedout)},
2588 {"$Get", cc(cmd_get)},
2589 {"$Send", cc(cmd_send)},
2590 {"$Supports", cc(cmd_supports)},
2591 {"$GetBlock", cc(cmd_getblock)},
2592 {"$UGetBlock", cc(cmd_getblock)},
2593 {"$GetZBlock", cc(cmd_getblock)},
2594 {"$UGetZBlock", cc(cmd_getblock)},
2595 {"$ADCGET", cc(cmd_adcget)},
2596 {"$ADCSND", cc(cmd_adcsnd), 1},
2597 {"$Sending", cc(cmd_sending), 1},
2602 static void dctransdetach(struct transfer *transfer, struct dcpeer *peer)
2604 CBUNREG(transfer, trans_filterout, peer);
2607 peer->transfer = NULL;
2611 static void dctransgotdata(struct transfer *transfer, struct dcpeer *peer)
2615 unsigned char outbuf[1024];
2619 if((peer->state == PEER_TRNS) || (peer->state == PEER_SYNC))
2621 if(sockqueuesize(peer->sk) < 65536)
2623 if((buf = transfergetdata(transfer, &bufsize)) != NULL)
2625 if(peer->compress == CPRS_NONE)
2627 sockqueue(peer->sk, buf, bufsize);
2628 } else if(peer->compress == CPRS_ZLIB) {
2629 cstr = peer->cprsdata;
2630 cstr->next_in = buf;
2631 cstr->avail_in = bufsize;
2632 while(cstr->avail_in > 0)
2634 cstr->next_out = outbuf;
2635 cstr->avail_out = sizeof(outbuf);
2636 if((ret = deflate(cstr, 0)) != Z_OK)
2638 flog(LOG_WARNING, "bug? deflate() did not return Z_OK (but rather %i)", ret);
2642 sockqueue(peer->sk, outbuf, sizeof(outbuf) - cstr->avail_out);
2647 if(peer->state == PEER_SYNC)
2649 if(peer->compress == CPRS_ZLIB)
2651 cstr = peer->cprsdata;
2652 cstr->next_in = NULL;
2656 cstr->next_out = outbuf;
2657 cstr->avail_out = sizeof(outbuf);
2658 ret = deflate(cstr, Z_FINISH);
2659 if((ret != Z_OK) && (ret != Z_STREAM_END))
2661 flog(LOG_WARNING, "bug? deflate(Z_FINISH) did not return Z_OK (but rather %i)", ret);
2665 sockqueue(peer->sk, outbuf, sizeof(outbuf) - cstr->avail_out);
2666 } while(ret != Z_STREAM_END);
2672 if(peer->timeout == NULL)
2673 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
2674 peer->state = PEER_CMD;
2676 transfersetstate(transfer, TRNS_HS);
2677 socksettos(peer->sk, confgetint("fnet", "fnptos"));
2678 transfer->flags.b.minislot = 0;
2679 peer->sk->writecb = NULL;
2686 static void dctransendofdata(struct transfer *transfer, struct dcpeer *peer)
2688 peer->state = PEER_SYNC;
2689 dctransgotdata(transfer, peer);
2692 static void dcwantdata(struct transfer *transfer, struct dcpeer *peer)
2694 if(transferdatasize(transfer) < 65536)
2695 peer->sk->ignread = 0;
2698 static void transread(struct socket *sk, struct dcpeer *peer)
2702 struct transfer *transfer;
2704 if((buf = sockgetinbuf(sk, &bufsize)) == NULL)
2706 if(peer->transfer == NULL)
2712 transferputdata(peer->transfer, buf, bufsize);
2714 if(peer->transfer->curpos >= peer->transfer->size)
2716 transfer = peer->transfer;
2717 transferdetach(transfer);
2718 transferendofdata(transfer);
2721 if(transferdatasize(peer->transfer) > 65535)
2725 static void transerr(struct socket *sk, int err, struct dcpeer *peer)
2727 struct transfer *transfer;
2729 if((transfer = peer->transfer) == NULL)
2734 transferdetach(transfer);
2735 transferendofdata(transfer);
2738 static void transwrite(struct socket *sk, struct dcpeer *peer)
2740 if((peer->state != PEER_TRNS) && (peer->state != PEER_SYNC))
2742 if(peer->transfer == NULL)
2747 dctransgotdata(peer->transfer, peer);
2750 static void udpread(struct socket *sk, void *data)
2752 char *buf, *p, *p2, *hashbuf;
2753 size_t buflen, hashlen;
2754 char *nick, *filename, *hubname;
2755 struct sockaddr_in hubaddr;
2757 struct fnetnode *fn, *myfn;
2760 wchar_t *wnick, *wfile;
2763 if((buf = sockgetinbuf(sk, &buflen)) == NULL)
2765 buf = srealloc(buf, buflen + 1);
2767 if(!strncmp(buf, "$SR ", 4))
2771 if((p2 = strchr(p, ' ')) == NULL)
2779 if((p2 = strchr(p, 5)) == NULL)
2786 if((p2 = strchr(p, ' ')) == NULL)
2794 if((p2 = strchr(p, '/')) == NULL)
2802 if((p2 = strchr(p, 5)) == NULL)
2809 if((p2 = strstr(p, " (")) == NULL)
2816 if((p2 = strchr(p, ':')) == NULL)
2822 hubaddr.sin_family = AF_INET;
2823 if(!inet_aton(p, &hubaddr.sin_addr))
2829 if((p2 = strchr(p, ')')) == NULL)
2835 hubaddr.sin_port = htons(atoi(p));
2836 /* Use DCCHARSET in $Get paths until further researched... */
2837 if((wfile = icmbstowcs(filename, DCCHARSET)) == NULL)
2844 if(!strncmp(hubname, "TTH:", 4))
2846 if((hashbuf = base32decode(hubname + 4, &hashlen)) != NULL)
2849 hash = newhash(L"TTH", 24, hashbuf);
2853 for(fn = fnetnodes; fn != NULL; fn = fn->next)
2855 if((fn->fnet == &dcnet) && ((hub = fn->data) != NULL))
2857 if((hub->nativename != NULL) && !strcmp(hub->nativename, hubname))
2872 for(fn = fnetnodes; fn != NULL; fn = fn->next)
2874 if((fn->fnet == &dcnet) && (fn->sk != NULL) && addreq(fn->sk->remote, (struct sockaddr *)&hubaddr))
2884 if((wnick = icmbstowcs(nick, (hub == NULL)?DCCHARSET:(hub->charset))) == NULL)
2889 sr = newsrchres(&dcnet, wfile, wnick);
2890 if(sr->peernick != NULL)
2892 sr->peernick = swcsdup(wnick);
2898 getfnetnode(sr->fn = myfn);
2907 static void hubread(struct socket *sk, struct fnetnode *fn)
2914 hub = (struct dchub *)fn->data;
2915 if((newbuf = sockgetinbuf(sk, &datalen)) == NULL)
2917 if(hub->inbufdata > 500000) /* Discard possible malicious data */
2919 sizebuf2(hub->inbuf, hub->inbufdata + datalen, 1);
2920 memcpy(hub->inbuf + hub->inbufdata, newbuf, datalen);
2922 p = hub->inbuf + hub->inbufdata;
2923 hub->inbufdata += datalen;
2924 while((datalen > 0) && ((p = memchr(p, '|', datalen)) != NULL))
2927 newqcmd(&hub->queue, hub->inbuf);
2928 memmove(hub->inbuf, p, hub->inbufdata -= p - hub->inbuf);
2929 datalen = hub->inbufdata;
2934 static void huberr(struct socket *sk, int err, struct fnetnode *fn)
2939 static int hubsetnick(struct fnetnode *fn, wchar_t *newnick)
2945 if((buf = icwcstombs(newnick, (hub == NULL)?DCCHARSET:(hub->charset))) == NULL)
2947 if((strchr(buf, ' ') != NULL) || (strchr(buf, '|') != NULL) || (strchr(buf, '$') != NULL))
2952 if(hub == NULL) /* Not yet connected */
2957 if(hub->nativenick != NULL)
2958 free(hub->nativenick);
2959 hub->nativenick = buf;
2963 static struct dchub *newdchub(struct fnetnode *fn)
2970 new = smalloc(sizeof(*new));
2971 memset(new, 0, sizeof(*new));
2973 if(confgetint("dc", "dcppemu"))
2975 if((emu = wpfind(fn->args, L"dcppemu")) != NULL)
2983 if((wcharset = wpfind(fn->args, L"charset")) != NULL)
2985 if((charset = icwcstombs(wcharset, "US-ASCII")) != NULL)
2987 if(!havecharset(charset))
2995 new->charset = charset;
2997 new->charset = sstrdup(DCCHARSET);
2998 if(hubsetnick(fn, fn->mynick))
2999 fnetsetnick(fn, L"DoldaConnectUser-IN");
3000 /* IN as in Invalid Nick */
3004 static struct dcpeer *newdcpeer(struct socket *sk)
3008 new = smalloc(sizeof(*new));
3009 memset(new, 0, sizeof(*new));
3010 new->transfer = NULL;
3013 if(confgetint("dc", "dcppemu"))
3024 static void freedcpeer(struct dcpeer *peer)
3027 struct qcommand *qcmd;
3032 if(peer->next != NULL)
3033 peer->next->prev = peer->prev;
3034 if(peer->prev != NULL)
3035 peer->prev->next = peer->next;
3036 if(peer->transfer != NULL)
3038 if(peer->transfer->dir == TRNSD_UP)
3039 peer->transfer->close = 1;
3040 if(peer->transfer->dir == TRNSD_DOWN)
3041 resettransfer(peer->transfer);
3042 transferdetach(peer->transfer);
3044 if(peer->timeout != NULL)
3045 canceltimer(peer->timeout);
3046 if(peer->sk->data == peer)
3047 peer->sk->data = NULL;
3048 peer->sk->readcb = NULL;
3049 peer->sk->writecb = NULL;
3050 peer->sk->errcb = NULL;
3053 if(peer->supports != NULL)
3055 for(i = 0; peer->supports[i] != NULL; i++)
3056 free(peer->supports[i]);
3057 free(peer->supports);
3059 if(peer->inbuf != NULL)
3061 if(peer->key != NULL)
3063 if(peer->wcsname != NULL)
3064 free(peer->wcsname);
3065 if(peer->nativename != NULL)
3066 free(peer->nativename);
3067 if(peer->charset != NULL)
3068 free(peer->charset);
3069 if(peer->fn != NULL)
3070 putfnetnode(peer->fn);
3071 while((qcmd = ulqcmd(&peer->queue)) != NULL)
3077 static void hubconnect(struct fnetnode *fn)
3079 fn->sk->readcb = (void (*)(struct socket *, void *))hubread;
3080 fn->sk->errcb = (void (*)(struct socket *, int, void *))huberr;
3082 fn->data = newdchub(fn);
3087 static void hubdestroy(struct fnetnode *fn)
3090 struct qcommand *qcmd;
3092 hub = (struct dchub *)fn->data;
3093 if((fn->sk != NULL) && (fn->sk->data == fn))
3095 fn->sk->data = NULL;
3100 while((qcmd = ulqcmd(&hub->queue)) != NULL)
3102 if(hub->nativename != NULL)
3103 free(hub->nativename);
3104 if(hub->nativenick != NULL)
3105 free(hub->nativenick);
3106 if(hub->charset != NULL)
3108 if(hub->inbuf != NULL)
3113 static wchar_t *dcbasename(wchar_t *filename)
3117 if((ret = wcsrchr(filename, L'\\')) != NULL)
3122 static struct transferiface dctransfer =
3124 .detach = (void (*)(struct transfer *, void *))dctransdetach,
3125 .gotdata = (void (*)(struct transfer *, void *))dctransgotdata,
3126 .endofdata = (void (*)(struct transfer *, void *))dctransendofdata,
3127 .wantdata = (void (*)(struct transfer *, void *))dcwantdata
3130 static struct fnet dcnet =
3133 .connect = hubconnect,
3134 .destroy = hubdestroy,
3135 .setnick = hubsetnick,
3136 .reqconn = hubreqconn,
3137 .sendchat = hubsendchat,
3138 .search = hubsearch,
3139 .filebasename = dcbasename
3142 static void peerread(struct socket *sk, struct dcpeer *peer)
3146 struct command *cmd;
3148 if((newbuf = sockgetinbuf(sk, &datalen)) == NULL)
3150 sizebuf2(peer->inbuf, peer->inbufdata + datalen, 1);
3151 memcpy(peer->inbuf + peer->inbufdata, newbuf, datalen);
3153 peer->inbufdata += datalen;
3154 if(peer->state == PEER_CMD)
3157 while((peer->inbufdata > 0) && (p = memchr(peer->inbuf, '|', peer->inbufdata)) != NULL)
3160 newqcmd(&peer->queue, peer->inbuf);
3161 for(cmd = peercmds; cmd->handler != NULL; cmd++)
3163 if(!memcmp(peer->inbuf, cmd->name, strlen(cmd->name)) && ((peer->inbuf[strlen(cmd->name)] == ' ') || (peer->inbuf[strlen(cmd->name)] == '|')))
3166 memmove(peer->inbuf, p, peer->inbufdata -= p - peer->inbuf);
3169 peer->state = PEER_STOP;
3173 } else if(peer->state == PEER_TTHL) {
3178 static void peererror(struct socket *sk, int err, struct dcpeer *peer)
3183 static void peerconnect(struct socket *sk, int err, struct fnetnode *fn)
3185 struct dcpeer *peer;
3195 peer = newdcpeer(sk);
3198 peer->dcppemu = hub->dcppemu;
3199 sk->readcb = (void (*)(struct socket *, void *))peerread;
3200 sk->errcb = (void (*)(struct socket *, int, void *))peererror;
3202 socksettos(sk, confgetint("fnet", "fnptos"));
3204 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
3209 static void peeraccept(struct socket *sk, struct socket *newsk, void *data)
3211 struct dcpeer *peer;
3213 peer = newdcpeer(newsk);
3215 newsk->readcb = (void (*)(struct socket *, void *))peerread;
3216 newsk->errcb = (void (*)(struct socket *, int, void *))peererror;
3218 socksettos(newsk, confgetint("fnet", "fnptos"));
3219 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
3222 static void updatehmlist(void)
3224 int i, lev, ic, ret;
3225 struct sharecache *node;
3226 char *buf, *buf2, numbuf[32];
3227 size_t bufsize, bufdata;
3231 buf = smalloc(bufsize = 65536);
3232 node = shareroot->child;
3237 /* Use DCCHARSET in $Get paths until further researched... */
3238 if((buf2 = icwcstombs(node->name, DCCHARSET)) != NULL)
3240 for(i = 0; i < lev; i++)
3242 bufcat(buf, buf2, strlen(buf2));
3244 if(node->f.b.type == FILE_REG)
3247 sprintf(numbuf, "%i", node->size);
3248 bufcat(buf, numbuf, strlen(numbuf));
3255 if((node->child != NULL) && !ic)
3259 } else if(node->next != NULL) {
3262 while(node->next == NULL)
3265 node = node->parent;
3266 if(node == shareroot)
3269 if(node == shareroot)
3274 if(hmlistname != NULL)
3279 hmlistname = sstrdup("/tmp/dc-filelist-hm-XXXXXX");
3280 if((fd = mkstemp(hmlistname)) < 0)
3282 flog(LOG_WARNING, "could not create HM file list tempfile: %s", strerror(errno));
3287 * I do not want to implement a good Huffman encoder, and it's not
3288 * like Huffman encoding actually yields any impressive results
3289 * for DC file lists anyway, so I'll just output a bogus
3290 * tree. Implement a good encoder if you want to.
3292 write(fd, "HE3\r\0", 5);
3293 write(fd, &bufdata, 4);
3295 write(fd, &ibuf, 2);
3297 for(i = 0; i < 256; i++)
3300 write(fd, &ibuf, 1);
3302 for(i = 0; i < 256; i++)
3304 for(buf2 = buf; bufdata > 0;)
3306 if((ret = write(fd, buf2, bufdata)) < 0)
3308 flog(LOG_WARNING, "could not write file list: %s", strerror(errno));
3319 static struct xmlent
3326 /* {L'\'', L"""}, Emulate DC++ escaping by omitting this. */
3330 static wchar_t *escapexml(wchar_t *src)
3332 static wchar_t *buf = NULL;;
3335 size_t bufsize, bufdata;
3341 bufsize = bufdata = 0;
3342 for(; *src != L'\0'; src++)
3345 if((c > 0) && (c < 32))
3347 bufcat(buf, L"&#", 2);
3348 ret = swprintf(nbuf, (sizeof(nbuf) / sizeof(*nbuf)), L"%i", c);
3349 bufcat(buf, nbuf, ret);
3350 addtobuf(buf, L';');
3352 for(ent = entities; ent->ent != NULL; ent++)
3356 bufcat(buf, ent->ent, wcslen(ent->ent));
3360 if(ent->ent == NULL)
3361 addtobuf(buf, *src);
3364 addtobuf(buf, L'\0');
3368 static void updatexmllist(void)
3372 char cidbuf[14], *namebuf;
3374 struct sharecache *node;
3376 if(xmllistname != NULL)
3378 unlink(xmllistname);
3381 xmllistname = sstrdup("/tmp/dc-filelist-dcxml-XXXXXX");
3382 if((fd = mkstemp(xmllistname)) < 0)
3384 flog(LOG_WARNING, "could not create XML file list tempfile: %s", strerror(errno));
3389 if((fs = fdopen(fd, "w")) == NULL)
3391 flog(LOG_WARNING, "could not fdopen XML list fd %i: %s", fd, strerror(errno));
3392 unlink(xmllistname);
3398 fprintf(fs, "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>\r\n");
3399 for(i = 0; i < sizeof(cidbuf) - 1; i++)
3400 cidbuf[i] = (rand() % ('Z' - 'A' + 1)) + 'A';
3402 if(confgetint("dc", "dcppemu"))
3403 fprintf(fs, "<FileListing Version=\"1\" CID=\"%s\" Base=\"/\" Generator=\"DC++ 0.674\">\r\n", cidbuf);
3405 fprintf(fs, "<FileListing Version=\"1\" CID=\"%s\" Base=\"/\" Generator=\"%s\">\r\n", cidbuf, "DoldaConnect" VERSION);
3407 node = shareroot->child;
3411 if((namebuf = icswcstombs(escapexml(node->name), "UTF-8", NULL)) != NULL)
3413 for(i = 0; i < lev; i++)
3415 if(node->child != NULL)
3417 fprintf(fs, "<Directory Name=\"%s\">\r\n", namebuf);
3422 fprintf(fs, "<File Name=\"%s\" Size=\"%i\"", namebuf, node->size);
3423 if(node->f.b.hastth)
3425 hashbuf = base32encode(node->hashtth, 24);
3426 fprintf(fs, " TTH=\"%.39s\"", hashbuf);
3429 fprintf(fs, "/>\r\n");
3431 while(node->next == NULL)
3433 node = node->parent;
3434 if(node == shareroot)
3439 for(i = 0; i < lev; i++)
3441 fprintf(fs, "</Directory>\r\n");
3444 if(node == shareroot)
3450 if(confgetint("dc", "dcppemu"))
3451 fprintf(fs, "</FileListing>");
3453 fprintf(fs, "</FileListing>\r\n");
3457 static void updatexmlbz2list(void)
3466 if(xmllistname == NULL)
3468 if((in = fopen(xmllistname, "r")) == NULL)
3470 flog(LOG_WARNING, "could not open XML file list for bzipping: %s", strerror(errno));
3473 if(xmlbz2listname != NULL)
3475 unlink(xmlbz2listname);
3476 free(xmlbz2listname);
3478 xmlbz2listname = sstrdup("/tmp/dc-filelist-dcxmlbz2-XXXXXX");
3479 if((fd = mkstemp(xmlbz2listname)) < 0)
3481 flog(LOG_WARNING, "could not create bzipped XML file list tempfile: %s", strerror(errno));
3482 free(xmlbz2listname);
3483 xmlbz2listname = NULL;
3487 if((real = fdopen(fd, "w")) == NULL)
3489 flog(LOG_WARNING, "could not fdopen bzipped XML list fd %i: %s", fd, strerror(errno));
3491 unlink(xmlbz2listname);
3492 free(xmlbz2listname);
3493 xmlbz2listname = NULL;
3497 out = BZ2_bzWriteOpen(&err, real, 9, 0, 0);
3500 flog(LOG_WARNING, "could not open bzip2 stream from XML list");
3502 unlink(xmlbz2listname);
3503 free(xmlbz2listname);
3504 xmlbz2listname = NULL;
3510 bufdata = fread(buf, 1, sizeof(buf), in);
3511 BZ2_bzWrite(&err, out, buf, bufdata);
3514 BZ2_bzWriteClose(&err, out, 0, NULL, NULL);
3518 static void listtimercb(int cancelled, void *uudata)
3520 listwritetimer = NULL;
3525 static void updatelists(int now)
3527 if((hmlistname == NULL) || (xmllistname == NULL) || (xmlbz2listname == NULL))
3531 if(listwritetimer == NULL)
3532 listwritetimer = timercallback(ntime() + 300, listtimercb, NULL);
3535 if(listwritetimer != NULL)
3536 canceltimer(listwritetimer);
3542 static int shareupdate(unsigned long long uusharesize, void *data)
3548 static void dispatchcommand(struct qcommand *qcmd, struct command *cmdlist, struct socket *sk, void *data)
3551 struct command *cmd;
3553 if((p = strchr(qcmd->string, ' ')) != NULL)
3555 for(cmd = cmdlist; cmd->handler != NULL; cmd++)
3557 if(!strcmp(cmd->name, qcmd->string))
3560 if(cmd->handler != NULL)
3561 cmd->handler(sk, data, qcmd->string, p);
3564 flog(LOG_DEBUG, "Unimplemented DC command: %s \"%s\"", qcmd->string, p?p:"noargs");
3568 static int run(void)
3570 struct fnetnode *fn, *nextfn;
3572 struct dcpeer *peer, *nextpeer;
3573 struct qcommand *qcmd;
3577 for(fn = fnetnodes; fn != NULL; fn = nextfn)
3580 if(fn->fnet != &dcnet)
3582 if(fn->data == NULL)
3584 hub = (struct dchub *)fn->data;
3585 if((qcmd = ulqcmd(&hub->queue)) != NULL)
3587 if(*qcmd->string == '$')
3589 if((fn->sk != NULL) && (fn->sk->state == SOCK_EST))
3590 dispatchcommand(qcmd, hubcmds, fn->sk, fn);
3591 } else if(*qcmd->string != 0) {
3592 hubrecvchat(fn->sk, fn, NULL, qcmd->string);
3599 for(peer = peers; peer != NULL; peer = nextpeer)
3601 nextpeer = peer->next;
3602 if((qcmd = ulqcmd(&peer->queue)) != NULL)
3604 if(peer->timeout != NULL)
3605 canceltimer(peer->timeout);
3606 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
3607 if(*qcmd->string == '$')
3608 dispatchcommand(qcmd, peercmds, peer->sk, peer);
3617 static void preinit(int hup)
3624 static int updateudpport(struct configvar *var, void *uudata)
3626 struct sockaddr_in addr;
3627 struct socket *newsock;
3629 memset(&addr, 0, sizeof(addr));
3630 addr.sin_family = AF_INET;
3631 addr.sin_port = htons(var->val.num);
3632 if((newsock = netcsdgram((struct sockaddr *)&addr, sizeof(addr))) == NULL)
3634 flog(LOG_WARNING, "could not create new DC UDP socket, reverting to old: %s", strerror(errno));
3637 newsock->readcb = udpread;
3644 static int updatetcpport(struct configvar *var, void *uudata)
3646 struct sockaddr_in addr;
3647 struct socket *newsock;
3649 memset(&addr, 0, sizeof(addr));
3650 addr.sin_family = AF_INET;
3651 addr.sin_port = htons(var->val.num);
3652 if((newsock = netcslisten(SOCK_STREAM, (struct sockaddr *)&addr, sizeof(addr), peeraccept, NULL)) == NULL)
3653 flog(LOG_INFO, "could not listen to a remote address, going into passive mode");
3660 static int init(int hup)
3662 struct sockaddr_in addr;
3666 GCBREG(sharechangecb, shareupdate, NULL);
3671 addr.sin_family = AF_INET;
3672 memset(&addr.sin_addr, 0, sizeof(addr.sin_addr));
3673 addr.sin_port = htons(confgetint("dc", "udpport"));
3674 if((udpsock = netcsdgram((struct sockaddr *)&addr, sizeof(addr))) == NULL)
3676 flog(LOG_CRIT, "could not create DC UDP socket: %s", strerror(errno));
3679 udpsock->readcb = udpread;
3680 addr.sin_port = htons(confgetint("dc", "tcpport"));
3681 if((tcpsock = netcslisten(SOCK_STREAM, (struct sockaddr *)&addr, sizeof(addr), peeraccept, NULL)) == NULL)
3682 flog(LOG_INFO, "could not listen to a remote address, going into passive mode");
3683 CBREG(confgetvar("dc", "udpport"), conf_update, updateudpport, NULL, NULL);
3684 CBREG(confgetvar("dc", "tcpport"), conf_update, updatetcpport, NULL, NULL);
3685 CBREG(confgetvar("net", "mode"), conf_update, updatetcpport, NULL, NULL);
3690 static void terminate(void)
3692 if(hmlistname != NULL)
3697 if(xmllistname != NULL)
3699 unlink(xmllistname);
3702 if(xmlbz2listname != NULL)
3704 unlink(xmlbz2listname);
3705 free(xmlbz2listname);
3709 static struct configvar myvars[] =
3711 /** Specifies the share description reported to other DC users. */
3712 {CONF_VAR_STRING, "desc", {.str = L""}},
3713 /** Specifies the speed reported to other DC users. Normal values
3714 * are 28.8Kbps, 33.6Kbps, 56Kbps, Satellite, ISDN, DSL, Cable,
3715 * LAN(T1) or LAN(T3)*/
3716 {CONF_VAR_STRING, "speedstring", {.str = L"LAN(T1)"}},
3717 /** The e-mail address to report to other DC users. */
3718 {CONF_VAR_STRING, "email", {.str = L"spam@spam.org"}},
3719 /** Specifies a specific UDP port to use for DC search results. If
3720 * left unspecified, a port is allocated dynamically. Useful for
3721 * NAT routers (see also the net.visibleipv4 address for those
3723 {CONF_VAR_INT, "udpport", {.num = 0}},
3724 /** Specifies a specific TCP port to use for DC peer
3725 * connections. If left unspecified, a port is allocated
3726 * dynamically. Useful for NAT routers (see also the
3727 * net.visibleipv4 address for those cases). */
3728 {CONF_VAR_INT, "tcpport", {.num = 0}},
3729 /** If set to true, doldacond will do its best to emulate DC++
3730 * (currently v0.674). This should be left off if at all possible,
3731 * since turning it on will violate the rules of most hubs and
3732 * thus give hub owners an actual reason to kick you if it is
3733 * detected. It might be needed for some of the more bone-headed
3734 * hub owners, though. Note that DC++ emulation can also be turned
3735 * on or off for individual hubs, overriding this setting. */
3736 {CONF_VAR_BOOL, "dcppemu", {.num = 0}},
3740 static struct module me =
3749 .terminate = terminate,