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;
115 struct dcexppeer *next, *prev;
118 struct timer *expire;
123 struct dcpeer *next, *prev;
127 size_t inbufdata, inbufsize;
128 size_t curread, totalsize;
130 struct timer *timeout;
131 struct qcommand *queue;
132 struct transfer *transfer;
134 int ptclose; /* Close after transfer is complete */
135 int accepted; /* If false, we connected, otherwise, we accepted */
136 int extended, dcppemu;
137 int direction; /* Using the constants from transfer.h */
139 int hascurpos, fetchingtthl, notthl;
140 struct tigertreehash tth;
149 static struct fnet dcnet;
150 static struct transferiface dctransfer;
151 static struct socket *udpsock = NULL;
152 static struct socket *tcpsock = NULL;
153 static struct dcpeer *peers = NULL;
155 static struct dcexppeer *expected = NULL;
156 static char *hmlistname = NULL;
157 static char *xmllistname = NULL;
158 static char *xmlbz2listname = NULL;
159 static struct timer *listwritetimer = NULL;
161 static void peerconnect(struct socket *sk, int err, struct fnetnode *fn);
162 static void freedcpeer(struct dcpeer *peer);
163 static void transread(struct socket *sk, struct dcpeer *peer);
164 static void transerr(struct socket *sk, int err, struct dcpeer *peer);
165 static void transwrite(struct socket *sk, struct dcpeer *peer);
166 static void updatehmlist(void);
167 static void updatexmllist(void);
168 static void updatexmlbz2list(void);
169 static void requestfile(struct dcpeer *peer);
170 static void updatelists(int now);
172 static int reservedchar(unsigned char c)
174 return((c == 0) || (c == 5) || (c == 124) || (c == 96) || (c == 126) || (c == 36));
177 /* Oh, how I despise having to do this... */
178 static char *dcmakekey(char *lock)
184 buf = smalloc(strlen(lock));
187 for(i = 0; lock[i]; i++)
189 buf[i] = lock[i] ^ save;
190 buf[i] = ((buf[i] & 0x0F) << 4) | ((buf[i] & 0xF0) >> 4);
192 if((i != 0) && reservedchar(buf[i]))
197 buf[0] ^= buf[i - 1];
198 if(reservedchar(buf[0]))
202 key = smalloc(len + 1);
204 for(i = 0; lock[i] != 0; i++)
206 if(reservedchar(buf[i]))
207 offset += sprintf(key + offset, "/%%DCN%03i%%/", buf[i]);
209 key[offset++] = buf[i];
216 static char *pathnmdc2adc(char *path)
219 size_t retsize, retdata;
221 if(!strcmp(path, "files.xml") || !strcmp(path, "files.xml.bz2") || !strcmp(path, "MyList.DcLst"))
222 return(sstrdup(path));
224 retsize = retdata = 0;
231 addtobuf(ret, *path);
237 static int isdchash(struct hash *hash)
239 if(wcscmp(hash->algo, L"TTH"))
246 static int supports(struct dcpeer *peer, char *cap)
250 if(peer->supports == NULL)
252 for(p = peer->supports; *p != NULL; p++)
254 if(!strcasecmp(*p, cap))
260 static void endcompress(struct dcpeer *peer)
262 if(peer->compress == CPRS_ZLIB)
264 deflateEnd(peer->cprsdata);
265 free(peer->cprsdata);
267 peer->compress = CPRS_NONE;
270 static void initcompress(struct dcpeer *peer, int algo)
275 peer->compress = algo;
276 if(algo == CPRS_ZLIB)
278 peer->cprsdata = smalloc(sizeof(z_stream));
279 memset(peer->cprsdata, 0, sizeof(z_stream));
280 if((ret = deflateInit(peer->cprsdata, 3)) != Z_OK)
282 flog(LOG_CRIT, "Aiya! zlib refuses to init (%i)!", ret);
288 static void unquote(wchar_t *in)
292 for(p = in; *p != L'\0'; p++)
296 for(p2 = p + 1; (*p2 != L'\0') && (*p2 != L';') && (*p2 != L'&'); p2++);
303 if(!wcscmp(p + 1, L"amp"))
306 } else if(p[1] == L'#') {
307 nc = ucptowc(wcstol(p + 2, NULL, 10));
316 memmove(p + 1, p2 + 1, (wcslen(p2 + 1) + 1) * sizeof(wchar_t));
321 static void freeexppeer(struct dcexppeer *ep)
324 ep->next->prev = ep->prev;
326 ep->prev->next = ep->next;
331 if(ep->expire != NULL)
332 canceltimer(ep->expire);
336 static void exppeerexpire(int cancelled, struct dcexppeer *ep)
343 static struct dcexppeer *expectpeer(char *nick, struct fnetnode *fn)
345 struct dcexppeer *ep;
347 ep = smalloc(sizeof(*ep));
348 ep->nick = sstrdup(nick);
349 getfnetnode(ep->fn = fn);
350 ep->expire = timercallback(ntime() + 300, (void (*)(int, void *))exppeerexpire, ep);
359 static struct qcommand *newqcmd(struct qcommand **queue, char *string)
361 struct qcommand *new;
363 while(*queue != NULL)
364 queue = &(*queue)->next;
365 new = smalloc(sizeof(*new));
366 new->string = sstrdup(string);
372 static struct qcommand *ulqcmd(struct qcommand **queue)
374 struct qcommand *qcmd;
376 if((qcmd = *queue) == NULL)
382 static void freeqcmd(struct qcommand *qcmd)
388 static void hubrecvchat(struct socket *sk, struct fnetnode *fn, char *from, char *string)
390 wchar_t *chat, *wfrom, *wpeer;
392 struct fnetpeer *peer;
396 end = string + strlen(string);
397 while((p = strchr(string, 13)) != NULL)
398 memmove(p, p + 1, (end-- - p));
401 if((strlen(string) > strlen(from) + 2) && (*string == '<') && !memcmp(string + 1, from, strlen(from)) && (*(string + strlen(from) + 1) == '>'))
402 string += strlen(from) + 2;
403 if((wfrom = icmbstowcs(from, hub->charset)) == NULL)
405 wpeer = swcsdup(wfrom);
411 for(p = string + 1; *p; p++)
413 if((*p == ' ') || (*p == '>'))
421 if((wpeer = icmbstowcs(string + 1, hub->charset)) == NULL)
427 wpeer = swcsdup(L"");
429 if((chat = icmbstowcs(string, hub->charset)) == NULL)
439 if((peer = fnetfindpeer(fn, wfrom)) == NULL) /* Assume public chat */
440 fnethandlechat(fn, 1, wfrom, wpeer, chat);
442 fnethandlechat(fn, 0, wfrom, wpeer, chat);
444 fnethandlechat(fn, 1, L"", wpeer, chat);
452 static void peertimeout(int cancelled, struct dcpeer *peer)
454 peer->timeout = NULL;
460 static void sendadc(struct socket *sk, char *arg)
463 size_t bufsize, bufdata;
466 bufsize = bufdata = 0;
472 bufcat(buf, "\\s", 2);
473 } else if(*arg == '\n') {
474 bufcat(buf, "\\n", 2);
475 } else if(*arg == '\\') {
476 bufcat(buf, "\\\\", 2);
481 sockqueue(sk, buf, bufdata);
485 static void sendadcf(struct socket *sk, char *arg, ...)
491 buf = vsprintf2(arg, args);
499 static char **parseadc(char *args)
502 size_t retbufsize, retbufdata;
504 size_t bufsize, bufdata;
509 retbufsize = retbufdata = bufsize = bufdata = 0;
518 else if(*args != ' ')
522 if((*args == ' ') || (*args == 0))
525 addtobuf(retbuf, buf);
527 bufsize = bufdata = 0;
530 } else if(*args == '\\') {
533 addtobuf(buf, *args);
542 addtobuf(retbuf, NULL);
545 } else if((*args == 's') || (*args == ' ')) {
547 } else if(*args == 'n') {
549 } else if(*args == '\\') {
559 addtobuf(retbuf, NULL);
563 /* Macros useful in command handlers */
564 #define skipspace(s) ({if(((s) = strchr((s), ' ')) == NULL) return; else (s)++;})
565 #define qstr(sk, str) sockqueue(sk, str, strlen(str))
566 #define qstrf(sk, strandargs...) \
569 if((__buf__ = sprintf2(strandargs)) != NULL) { \
570 sockqueue(sk, __buf__, strlen(__buf__)); \
575 static char *tr(char *str, char *trans)
579 for(; *trans; trans += 2)
581 for(p = strchr(str, trans[0]); p != NULL; p = strchr(p, trans[0]))
587 static char *getadcid(struct dcpeer *peer)
594 if(!wcscmp(peer->transfer->path, L"files.xml") || !wcscmp(peer->transfer->path, L"files.xml.bz2") || !wcscmp(peer->transfer->path, L"MyList.DcLst"))
596 if(!isfilelist && (peer->transfer->hash != NULL) && isdchash(peer->transfer->hash) && supports(peer, "tthf"))
598 buf = base32encode(peer->transfer->hash->buf, 24);
599 ret = sprintf2("TTH/%.39s", buf);
602 if((buf = icwcstombs(peer->transfer->path, "UTF-8")) == NULL)
604 ret = pathnmdc2adc(buf);
611 static int trresumecb(struct transfer *transfer, wchar_t *cmd, wchar_t *arg, struct dcpeer *peer)
613 if(!wcscmp(cmd, L"resume"))
617 flog(LOG_WARNING, "filter returned no position for \"resume\" on transfer %i", transfer->id);
620 transfer->curpos = wcstol(arg, NULL, 10);
629 static void sendmynick(struct dcpeer *peer)
635 qstrf(peer->sk, "$MyNick %s|", icswcstombs(confgetstr("cli", "defnick"), peer->charset, "DoldaConnectUser-IN"));
637 qstrf(peer->sk, "$MyNick %s|", icswcstombs(fn->mynick, peer->charset, "DoldaConnectUser-IN"));
640 static void sendpeerlock(struct dcpeer *peer)
643 qstrf(peer->sk, "$Lock EXTENDEDPROTOCOLABCABCABCABCABCABC Pk=DCPLUSPLUS0.674ABCABC|");
645 qstrf(peer->sk, "$Lock EXTENDEDPROTOCOLABCABCABCABCABCABC Pk=DOLDA%sABCABCABC|", VERSION);
648 static void sendsupports(struct dcpeer *peer)
651 qstr(peer->sk, "$Supports MiniSlots XmlBZList ADCGet TTHL TTHF GetZBlock ZLIG |");
653 qstr(peer->sk, "$Supports MiniSlots XmlBZList ADCGet TTHL TTHF GetZBlock ZLIG|");
656 static void requestfile(struct dcpeer *peer)
660 if(peer->transfer->size == -1)
662 /* Use DCCHARSET for $Get paths until further researched... */
663 if((buf = icswcstombs(peer->transfer->path, DCCHARSET, NULL)) == NULL)
665 transferseterror(peer->transfer, TRNSE_NOTFOUND);
669 /* The transfer will be restarted later from
670 * cmd_filelength when it detects that the sizes
672 qstrf(peer->sk, "$Get %s$1|", buf);
675 if((peer->transfer->hash == NULL) && !peer->notthl)
677 if(supports(peer, "adcget") && supports(peer, "tthl"))
679 qstr(peer->sk, "$ADCGET");
680 sendadc(peer->sk, "tthl");
681 if((buf = getadcid(peer)) == NULL)
683 transferseterror(peer->transfer, TRNSE_NOTFOUND);
687 sendadc(peer->sk, buf);
689 sendadc(peer->sk, "0");
690 sendadc(peer->sk, "-1");
692 peer->fetchingtthl = 1;
698 if(forkfilter(peer->transfer))
700 flog(LOG_WARNING, "could not fork filter for transfer %i: %s", peer->transfer->id, strerror(errno));
704 CBREG(peer->transfer, trans_filterout, (int (*)(struct transfer *, wchar_t *, wchar_t *, void *))trresumecb, NULL, peer);
707 if(supports(peer, "adcget"))
709 qstr(peer->sk, "$ADCGET");
710 sendadc(peer->sk, "file");
711 if((buf = getadcid(peer)) == NULL)
713 transferseterror(peer->transfer, TRNSE_NOTFOUND);
717 sendadc(peer->sk, buf);
719 sendadcf(peer->sk, "%i", peer->transfer->curpos);
720 sendadcf(peer->sk, "%i", peer->transfer->size - peer->transfer->curpos);
722 } else if(supports(peer, "xmlbzlist")) {
723 if((buf = icswcstombs(peer->transfer->path, "UTF-8", NULL)) == NULL)
725 transferseterror(peer->transfer, TRNSE_NOTFOUND);
729 qstrf(peer->sk, "$UGetBlock %zi %zi %s|", peer->transfer->curpos, peer->transfer->size - peer->transfer->curpos, buf);
731 /* Use DCCHARSET for $Get paths until further researched... */
732 if((buf = icswcstombs(peer->transfer->path, DCCHARSET, NULL)) == NULL)
734 transferseterror(peer->transfer, TRNSE_NOTFOUND);
738 qstrf(peer->sk, "$Get %s$%zi|", buf, peer->transfer->curpos + 1);
742 static void sendmyinfo(struct socket *sk, struct fnetnode *fn)
746 struct fnetnode *cfn;
750 qstrf(sk, "$MyINFO $ALL %s ", hub->nativenick);
751 buf = tr(icswcstombs(confgetstr("dc", "desc"), hub->charset, "Charset_conv_failure"), "$_|_");
752 qstrf(sk, "%s", buf);
754 for(cfn = fnetnodes; cfn != NULL; cfn = cfn->next)
756 if((cfn->state == FNN_EST) || (cfn->state == FNN_HS))
758 if(cfn->regstatus == FNNS_OP)
760 else if(cfn->regstatus == FNNS_REG)
766 qstrf(sk, "<%s V:%s,M:%c,H:%i/%i/%i,S:%i>",
767 (hub->dcppemu)?"++":"Dolda",
768 (hub->dcppemu)?"0.674":VERSION,
769 (tcpsock == NULL)?'P':'A',
771 confgetint("transfer", "slots")
774 buf = tr(icswcstombs(confgetstr("dc", "speedstring"), hub->charset, "Charset_conv_failure"), "$_|_");
775 qstrf(sk, "%s\x01$", buf);
776 buf = tr(icswcstombs(confgetstr("dc", "email"), hub->charset, "Charset_conv_failure"), "$_|_");
777 qstrf(sk, "%s$", buf);
778 qstrf(sk, "%llu$|", sharesize);
781 static void hubhandleaction(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
786 if(!strcmp(cmd, "$Lock"))
788 qstrf(sk, "$ValidateNick %s|", hub->nativenick);
789 } else if(!strcmp(cmd, "$Hello")) {
790 if(fn->state == FNN_HS)
792 qstrf(sk, "$Version 1,0091|");
793 qstrf(sk, "$GetNickList|");
795 fnetsetstate(fn, FNN_EST);
797 qstrf(sk, "$GetINFO %s %s|", args, hub->nativenick);
802 static void cmd_lock(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
809 if(!strncmp(args, "EXTENDEDPROTOCOL", 16))
811 if((p = strchr(args, ' ')) != NULL)
816 qstrf(sk, "$Supports UserCommand NoGetINFO NoHello UserIP2 TTHSearch GetZBlock |");
818 qstrf(sk, "$Supports UserCommand NoGetINFO NoHello UserIP2 TTHSearch GetZBlock|");
820 key = dcmakekey(args);
821 qstrf(sk, "$Key %s|", key);
823 hubhandleaction(sk, fn, cmd, args);
826 static void cmd_hubname(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
832 if(hub->nativename == NULL)
833 free(hub->nativename);
834 hub->nativename = sstrdup(args);
835 buf = icmbstowcs(args, hub->charset);
836 fnetsetname(fn, (buf == NULL)?L"Hubname conv error":buf);
839 hubhandleaction(sk, fn, cmd, args);
842 static void cmd_hello(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
848 if((nick = icmbstowcs(args, hub->charset)) == NULL)
850 if(strcmp(args, hub->nativenick) && (fnetfindpeer(fn, nick) == NULL))
851 fnetaddpeer(fn, nick, nick);
853 hubhandleaction(sk, fn, cmd, args);
856 static void cmd_quit(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
859 struct fnetpeer *peer;
863 if((nick = icmbstowcs(args, hub->charset)) == NULL)
865 if((peer = fnetfindpeer(fn, nick)) != NULL)
868 hubhandleaction(sk, fn, cmd, args);
871 static void cmd_nicklist(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
876 struct fnetpeer *peer, *npeer;
879 for(peer = fn->peers; peer != NULL; peer = peer->next)
880 peer->flags.b.delete = 1;
881 while((p = strstr(args, "$$")) != NULL)
884 if((buf = icmbstowcs(args, hub->charset)) != NULL)
886 if((peer = fnetfindpeer(fn, buf)) == NULL)
887 peer = fnetaddpeer(fn, buf, buf);
889 peer->flags.b.delete = 0;
891 qstrf(sk, "$GetINFO %s %s|", args, hub->nativenick);
895 for(peer = fn->peers; peer != NULL; peer = npeer)
898 if(peer->flags.b.delete)
901 hubhandleaction(sk, fn, cmd, args);
904 static void cmd_oplist(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
909 struct fnetpeer *peer;
912 for(peer = fn->peers; peer != NULL; peer = peer->next)
913 peer->flags.b.op = 0;
914 while((p = strstr(args, "$$")) != NULL)
917 if((buf = icmbstowcs(args, hub->charset)) != NULL)
919 if((peer = fnetfindpeer(fn, buf)) != NULL)
920 peer->flags.b.op = 1;
925 hubhandleaction(sk, fn, cmd, args);
928 static void cmd_myinfo(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
931 wchar_t *buf, *wp, *wp2;
933 struct fnetpeer *peer;
938 if(strncmp(p, "$ALL ", 5))
941 if((p2 = strchr(p, ' ')) == NULL)
944 if((buf = icmbstowcs(p, hub->charset)) == NULL)
946 if((peer = fnetfindpeer(fn, buf)) == NULL)
947 peer = fnetaddpeer(fn, buf, buf);
950 if((p2 = strstr(p, "$ $")) == NULL)
953 if((buf = icmbstowcs(p, hub->charset)) == NULL)
955 if((wcslen(buf) > 0) && (buf[wcslen(buf) - 1] == L'>') && ((wp = wcsrchr(buf, L'<')) != NULL))
957 buf[wcslen(buf) - 1] = L'\0';
959 if((wp2 = wcschr(wp, L' ')) != NULL)
962 fnetpeersetstr(peer, L"dc-client", wp);
966 if((wp2 = wcschr(wp, L',')) != NULL)
970 swprintf(abuf, 10, L"dc-tag-%lc", wp[0]);
971 fnetpeersetstr(peer, abuf, wp + 2);
973 } while(wp2 != NULL);
976 fnetpeersetstr(peer, L"descr", buf);
979 if((p2 = strchr(p, '$')) == NULL)
982 if((buf = icmbstowcs(p, hub->charset)) == NULL)
984 fnetpeersetstr(peer, L"dc-speed", buf);
987 if((p2 = strchr(p, '$')) == NULL)
990 if((buf = icmbstowcs(p, hub->charset)) == NULL)
992 fnetpeersetstr(peer, L"email", buf);
997 fnetpeersetlnum(peer, L"share", strtoll(p, NULL, 10));
998 hubhandleaction(sk, fn, cmd, args);
1001 /* I do not implement the fully in that I do not disconnect from the
1002 * old hub. I do this since I believe that if the hub owner really
1003 * wants to get rid of us, then it is his responsibility to disconnect
1005 static void cmd_forcemove(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1008 struct fnetnode *newfn;
1012 if(strchr(args, ':') == NULL)
1014 args = strcpy(smalloc(strlen(args) + 5), args);
1015 strcat(args, ":411");
1020 if((newfn = fnetinitconnect(L"dc", fn->owner, args, NULL)) != NULL)
1022 linkfnetnode(newfn);
1025 hubhandleaction(sk, fn, cmd, args);
1030 static char *getdcpath(struct sharecache *node, size_t *retlen, char *charset)
1035 if(node->parent == NULL)
1037 if(node->parent == shareroot)
1039 if((buf = icwcstombs(node->name, charset)) == NULL)
1042 *retlen = strlen(buf);
1045 if((buf2 = icwcstombs(node->name, charset)) == NULL)
1047 if((buf = getdcpath(node->parent, &len, charset)) == NULL)
1052 len2 = strlen(buf2);
1053 buf = srealloc(buf, len + 1 + len2 + 1);
1055 strcpy(buf + len, buf2);
1056 buf[len + len2] = 0;
1059 *retlen = len + len2;
1065 * This is the main share searching function for Direct Connect
1066 * peers. Feel free to optimize it if you feel the need for it. I
1067 * haven't ever seen it take any noticable CPU time anyway, so I
1068 * haven't felt that need.
1070 * It may feel dubious to just return the directory when all terms are
1071 * satisfied rather than all the files in it, but it really benefits
1072 * everyone: Less cycles used for us, less UDP squelching for active
1073 * searchers, and less bandwidth waste for hubs when serving passive
1076 static void cmd_search(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1081 char *prefix, *infix, *postfix, *buf, *buf2;
1083 struct sockaddr_in addr;
1084 struct sharecache *node;
1085 int minsize, maxsize;
1088 int termnum, satisfied, skipcheck;
1089 int level, tersat[32];
1094 if((p = strchr(args, ' ')) == NULL)
1098 memset(terms, 0, sizeof(terms));
1099 prefix = infix = postfix = NULL;
1103 if(!strncmp(args, "Hub:", 4))
1105 if(!strcmp(cmd, "$MultiSearch"))
1107 if(!strcmp(args + 4, hub->nativenick))
1109 prefix = sprintf2("$SR %s ", hub->nativenick);
1110 infix = sprintf2(" %i/%i\005", slotsleft(), confgetint("transfer", "slots"));
1111 postfix = sprintf2(" (%s)\005%s|", formataddress(fn->sk->remote, fn->sk->remotelen), args + 4);
1115 if((p2 = strchr(args, ':')) == NULL)
1118 addr.sin_family = AF_INET;
1119 if(!inet_aton(args, &addr.sin_addr))
1121 addr.sin_port = htons(atoi(p2));
1122 prefix = sprintf2("$SR %s ", hub->nativenick);
1123 infix = sprintf2(" %i/%i\005", slotsleft(), confgetint("transfer", "slots"));
1124 postfix = sprintf2(" (%s)|", formataddress(fn->sk->remote, fn->sk->remotelen));
1125 netdgramconn(dsk = netdupsock(udpsock), (struct sockaddr *)&addr, sizeof(addr));
1128 minsize = maxsize = -1;
1137 if((*(p++) == 'T') && (minsize == 0))
1144 if((p2 = strchr(p, '?')) == NULL)
1159 if((*p2 == 0) || (*p2 == '$'))
1167 if(!dotth && !strncmp(p, "TTH:", 4))
1170 if(((buf = base32decode(p + 4, &buflen)) == NULL) || (buflen != 24))
1175 memcpy(hashtth, buf, 24);
1178 if((terms[termnum] = icmbstowcs(p, hub->charset)) != NULL)
1189 node = shareroot->child;
1191 for(i = 0; i < termnum; i++)
1197 if(node->f.b.type == FILE_REG)
1199 if((minsize >= 0) && (node->size < minsize))
1201 if((maxsize >= 0) && (node->size > maxsize))
1204 if(!skipcheck && dotth)
1206 if((node->f.b.type != FILE_REG) || (node->f.b.hastth && memcmp(hashtth, node->hashtth, 24)))
1211 for(i = 0; i < termnum; i++)
1215 if(wcsexists(node->name, terms[i]))
1219 } else if(node->child == NULL) {
1224 if(!skipcheck && (satisfied == termnum))
1226 /* Use DCCHARSET in $Get paths until further researched... */
1227 if((buf = getdcpath(node, NULL, DCCHARSET)) != NULL)
1229 if(node->f.b.hastth)
1231 buf2 = base32encode(node->hashtth, 24);
1232 qstrf(dsk, "%s%s\005%zi%sTTH:%.39s%s", prefix, buf, node->size, infix, buf2, postfix);
1235 qstrf(dsk, "%s%s\005%zi%s%s%s", prefix, buf, node->size, infix, hub->nativename, postfix);
1240 if((!skipcheck && (satisfied == termnum)) || (node->child == NULL))
1242 while(node->next == NULL)
1244 if((node = node->parent) == shareroot)
1248 if(node == shareroot)
1250 for(i = 0; i < termnum; i++)
1252 if(tersat[i] >= level)
1265 hubhandleaction(sk, fn, cmd, args);
1276 for(i = 0; (i < 32) && (terms[i] != NULL); i++)
1280 static void cmd_connecttome(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1284 struct socket *newsk;
1285 struct sockaddr_in addr;
1288 if((p = strchr(args, ' ')) == NULL)
1291 if(strcmp(args, hub->nativenick))
1293 addr.sin_family = AF_INET;
1295 if((p = strchr(args, ':')) == NULL)
1298 addr.sin_port = htons(atoi(p));
1299 if(!inet_aton(args, &addr.sin_addr))
1301 newsk = netcsconn((struct sockaddr *)&addr, sizeof(addr), (void (*)(struct socket *, int, void *))peerconnect, fn);
1303 hubhandleaction(sk, fn, cmd, args);
1306 static void sendctm(struct socket *sk, char *nick)
1308 struct sockaddr *addr;
1313 if(sockgetremotename2(tcpsock, sk, &addr, &addrlen) < 0)
1315 if(addr->sa_family == AF_INET)
1316 qstrf(sk, "$ConnectToMe %s %s|", nick, formataddress(addr, addrlen));
1318 flog(LOG_WARNING, "Direct Connect TCP socket is suddenly not AF_INET, but %i", addr->sa_family);
1322 static void cmd_revconnecttome(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1328 if((p = strchr(args, ' ')) == NULL)
1331 if(strcmp(p, hub->nativenick))
1334 expectpeer(args, fn);
1335 hubhandleaction(sk, fn, cmd, args);
1338 static void cmd_getnetinfo(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1341 struct fnetnode *node;
1346 for(node = fnetnodes; node != NULL; node = node->next)
1348 if(node->state == FNN_EST)
1351 qstrf(sk, "$NetInfo %i$%i$%c$0|", confgetint("transfer", "slots"), numhubs, (tcpsock == NULL)?'P':'A');
1352 hubhandleaction(sk, fn, cmd, args);
1355 static void cmd_to(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1362 if((p2 = strchr(p, ' ')) == NULL)
1366 if((p2 = strchr(p, ' ')) == NULL)
1369 if(strcmp(p, "From:"))
1372 if((p2 = strstr(p, " $")) == NULL)
1376 hubrecvchat(fn->sk, fn, p, p2);
1377 hubhandleaction(sk, fn, cmd, args);
1380 static void cmd_sr(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1384 char *nick, *filename, *hubname;
1388 wchar_t *wnick, *wfile;
1392 if((p2 = strchr(p, ' ')) == NULL)
1397 if((p2 = strchr(p, 5)) == NULL)
1401 if((p2 = strchr(p, ' ')) == NULL)
1406 if((p2 = strchr(p, '/')) == NULL)
1411 if((p2 = strchr(p, 5)) == NULL)
1415 if((p2 = strstr(p, " (")) == NULL)
1418 if((wnick = icmbstowcs(nick, hub->charset)) == NULL)
1420 /* Use DCCHARSET in $Get paths until further researched... */
1421 if((wfile = icmbstowcs(filename, DCCHARSET)) == NULL)
1426 sr = newsrchres(&dcnet, wfile, wnick);
1427 if(sr->peernick != NULL)
1429 sr->peernick = swcsdup(wnick);
1434 if(!strncmp(hubname, "TTH:", 4))
1436 if((buf = base32decode(hubname + 4, &buflen)) != NULL)
1439 sr->hash = newhash(L"TTH", 24, buf);
1443 getfnetnode(sr->fn = fn);
1446 hubhandleaction(sk, fn, cmd, args);
1449 static void cmd_usercommand(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1451 /* Do nothing for now. */
1454 static void cmd_getpass(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1461 pw = wpfind(fn->args, L"password");
1462 if((pw == NULL) || ((mbspw = icwcstombs(pw, hub->charset)) == NULL))
1467 qstrf(sk, "$MyPass %s|", mbspw);
1469 fn->regstatus = FNNS_REG;
1470 hubhandleaction(sk, fn, cmd, args);
1473 static void cmd_logedin(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1478 fn->regstatus = FNNS_OP;
1479 hubhandleaction(sk, fn, cmd, args);
1482 static void cmd_mynick(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1484 struct dcexppeer *expect;
1487 if(peer->nativename != NULL)
1488 free(peer->nativename);
1489 peer->nativename = sstrdup(args);
1490 if(peer->wcsname != NULL)
1491 free(peer->wcsname);
1492 if((peer->wcsname = icmbstowcs(peer->nativename, peer->charset)) == NULL)
1499 for(expect = expected; expect != NULL; expect = expect->next)
1501 if(!strcmp(expect->nick, args))
1508 hub = expect->fn->data;
1509 peer->fn = expect->fn;
1510 getfnetnode(peer->fn);
1511 peer->dcppemu = hub->dcppemu;
1512 freeexppeer(expect);
1517 static void cmd_direction(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1521 struct transfer *transfer;
1523 if((p = strchr(args, ' ')) == NULL)
1526 if(!strcmp(args, "Upload"))
1528 if(!strcmp(args, "Download"))
1532 if((peer->transfer == NULL) || (mydir != peer->direction))
1537 if(peer->direction == TRNSD_DOWN)
1540 if(peer->wcsname == NULL)
1545 peer->direction = mydir;
1546 if(peer->direction == TRNSD_UP)
1548 if(confgetint("transfer", "ulquota") && hasupload(&dcnet, peer->wcsname))
1553 transfer = newupload(peer->fn, &dcnet, peer->wcsname, &dctransfer, peer);
1555 if((transfer = finddownload(peer->wcsname)) == NULL)
1560 transferattach(transfer, &dctransfer, peer);
1561 transfersetstate(transfer, TRNS_HS);
1563 transfersetnick(transfer, peer->wcsname);
1564 peer->transfer = transfer;
1567 qstrf(sk, "$Direction %s %i|", (peer->direction == TRNSD_UP)?"Upload":"Download", rand() % 10000);
1568 if(peer->key != NULL)
1569 qstrf(sk, "$Key %s|", peer->key);
1570 if(peer->direction == TRNSD_DOWN)
1575 static void cmd_peerlock(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1578 struct transfer *transfer;
1580 if((p = strchr(args, ' ')) == NULL)
1583 if(!strncmp(args, "EXTENDEDPROTOCOL", 16))
1585 key = dcmakekey(args);
1588 if(peer->wcsname == NULL)
1597 if((transfer = finddownload(peer->wcsname)) == NULL)
1599 if(confgetint("transfer", "ulquota") && hasupload(&dcnet, peer->wcsname))
1604 peer->direction = TRNSD_UP;
1605 transfer = newupload(peer->fn, &dcnet, peer->wcsname, &dctransfer, peer);
1607 peer->direction = TRNSD_DOWN;
1608 transferattach(transfer, &dctransfer, peer);
1609 transfersetstate(transfer, TRNS_HS);
1611 transfersetnick(transfer, peer->wcsname);
1612 peer->transfer = transfer;
1613 qstrf(sk, "$Direction %s %i|", (peer->direction == TRNSD_UP)?"Upload":"Download", rand() % 10000);
1614 qstrf(sk, "$Key %s|", key);
1617 if(peer->key != NULL)
1623 static void cmd_key(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1628 static void startdl(struct dcpeer *peer)
1630 if(peer->timeout != NULL)
1631 canceltimer(peer->timeout);
1632 peer->state = PEER_TRNS;
1633 transferstartdl(peer->transfer, peer->sk);
1634 peer->sk->readcb = (void (*)(struct socket *, void *))transread;
1635 peer->sk->errcb = (void (*)(struct socket *, int, void *))transerr;
1638 static void startul(struct dcpeer *peer)
1640 if(peer->timeout != NULL)
1641 canceltimer(peer->timeout);
1642 peer->state = PEER_TRNS;
1643 transferstartul(peer->transfer, peer->sk);
1644 peer->sk->writecb = (void (*)(struct socket *, void *))transwrite;
1647 static void cmd_filelength(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1650 struct transfer *transfer;
1652 if(peer->transfer == NULL)
1658 if(peer->transfer->size != size)
1660 transfersetsize(peer->transfer, size);
1661 transfer = peer->transfer;
1663 trytransferbypeer(transfer->fnet, transfer->peerid);
1667 qstr(peer->sk, "$Send|");
1670 static void cmd_error(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1672 if(peer->fetchingtthl)
1674 peer->fetchingtthl = 0;
1679 if((peer->transfer != NULL) && (peer->transfer->dir == TRNSD_DOWN))
1681 transferseterror(peer->transfer, TRNSE_NOTFOUND);
1682 resettransfer(peer->transfer);
1688 static void cmd_maxedout(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1690 if((peer->transfer != NULL) && (peer->transfer->dir == TRNSD_DOWN))
1692 transferseterror(peer->transfer, TRNSE_NOSLOTS);
1693 resettransfer(peer->transfer);
1706 {"MyList.DcLst", &hmlistname, updatehmlist},
1707 {"files.xml", &xmllistname, updatexmllist},
1708 {"files.xml.bz2", &xmlbz2listname, updatexmlbz2list},
1712 static int openfilelist(char *name)
1717 for(i = 0; lists[i].name != NULL; i++)
1719 if(!strcmp(name, lists[i].name))
1723 if(lists[i].name == NULL)
1726 if((*lists[i].file == NULL) || ((fd = open(*lists[i].file, O_RDONLY)) < 0))
1728 if((fd < 0) && ((*lists[i].file == NULL) || ((fd = open(*lists[i].file, O_RDONLY)) < 0)))
1731 flog(LOG_ERR, "could not open filelist tempfile: %s", strerror(errno));
1738 static struct sharecache *findbytth(char *tth32)
1742 struct sharecache *node;
1744 if((buf = base32decode(tth32, &buflen)) == NULL)
1751 for(node = shareroot->child; node != NULL; node = nextscnode(node))
1753 if(node->f.b.hastth && !memcmp(node->hashtth, buf, 24))
1760 static struct sharecache *resdcpath(char *path, char *charset, char sep)
1762 struct sharecache *node;
1769 if((p2 = strchr(p, sep)) != NULL)
1771 if((node = findcache(node, icsmbstowcs(p, charset, L""))) == NULL)
1778 static void cmd_get(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1783 struct sharecache *node;
1784 struct socket *lesk;
1788 if(peer->transfer == NULL)
1793 if((p = strchr(args, '$')) == NULL)
1799 if((offset = (atoi(p) - 1)) < 0)
1804 if(((fd = openfilelist(args)) < 0) && (errno != 0))
1806 qstr(sk, "$Error Could not send file list|");
1809 } else if(fd >= 0) {
1810 if((buf2 = icsmbstowcs(args, DCCHARSET, NULL)) != NULL)
1811 transfersetpath(peer->transfer, buf2);
1812 peer->transfer->flags.b.minislot = 1;
1816 /* Use DCCHARSET in $Get paths until further researched... */
1817 if((node = resdcpath(args, DCCHARSET, '\\')) == NULL)
1819 qstrf(sk, "$Error File not in share|");
1823 if((fd = opensharecache(node)) < 0)
1825 qstrf(sk, "$Error %s|", strerror(errno));
1829 buf = getfspath(node);
1830 if((buf2 = icsmbstowcs(buf, NULL, NULL)) == NULL)
1831 flog(LOG_WARNING, "could not convert native path into a wcs (%s): %s", buf, strerror(errno));
1833 transfersetpath(peer->transfer, buf2);
1836 if(fstat(fd, &sb) < 0)
1839 flog(LOG_WARNING, "could not stat file %ls: %s", node->name, strerror(errno));
1840 qstrf(sk, "$Error|");
1844 if(sb.st_size < 65536)
1845 peer->transfer->flags.b.minislot = 1;
1846 if(!peer->transfer->flags.b.minislot && (slotsleft() < 1)) {
1848 qstr(sk, "$MaxedOut|");
1852 if((offset != 0) && (lseek(fd, offset, SEEK_SET) < 0))
1855 qstrf(sk, "$Error Offset out of range|");
1859 lesk = wrapsock(fd);
1860 transferprepul(peer->transfer, sb.st_size, offset, -1, lesk);
1862 qstrf(sk, "$FileLength %zi|", peer->transfer->size);
1865 static void cmd_send(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1867 if(peer->transfer == NULL)
1872 if(peer->transfer->localend == NULL)
1881 static void cmd_supports(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1886 size_t arrsize, arrdata;
1888 if(peer->supports != NULL)
1890 for(i = 0; peer->supports[i] != NULL; i++)
1891 free(peer->supports[i]);
1892 free(peer->supports);
1895 arrsize = arrdata = 0;
1899 if((p2 = strchr(p, ' ')) != NULL)
1903 addtobuf(arr, sstrdup(p));
1904 } while((p = p2) != NULL);
1905 addtobuf(arr, NULL);
1906 peer->supports = arr;
1909 static void cmd_getblock(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1913 int start, numbytes;
1914 char *charset, *buf;
1916 struct sharecache *node;
1918 struct socket *lesk;
1920 if(peer->transfer == NULL)
1926 if((p2 = strchr(p, ' ')) == NULL)
1934 if((p2 = strchr(p, ' ')) == NULL)
1942 if(!strcmp(cmd, "$UGetBlock") || !strcmp(cmd, "$UGetZBlock"))
1945 /* Use DCCHARSET in $Get paths until further researched... */
1946 charset = DCCHARSET;
1947 if(!strcmp(cmd, "$GetZBlock") || !strcmp(cmd, "$UGetZBlock"))
1948 initcompress(peer, CPRS_ZLIB);
1949 if(((fd = openfilelist(p)) < 0) && (errno != 0))
1951 qstr(sk, "$Error Could not send file list|");
1953 } else if(fd >= 0) {
1954 if((buf2 = icsmbstowcs(args, charset, NULL)) != NULL)
1955 transfersetpath(peer->transfer, buf2);
1956 peer->transfer->flags.b.minislot = 1;
1960 if((node = resdcpath(p, charset, '\\')) == NULL)
1962 qstr(sk, "$Error File not in cache|");
1965 if((fd = opensharecache(node)) < 0)
1967 qstrf(sk, "$Error %s|", strerror(errno));
1970 buf = getfspath(node);
1971 if((buf2 = icsmbstowcs(buf, NULL, NULL)) == NULL)
1972 flog(LOG_WARNING, "could not convert native path into a wcs (%s): %s", buf, strerror(errno));
1974 transfersetpath(peer->transfer, buf2);
1977 if(fstat(fd, &sb) < 0)
1980 flog(LOG_WARNING, "could not stat file %ls: %s", node->name, strerror(errno));
1981 qstr(sk, "$Error|");
1984 if(sb.st_size < 65536)
1985 peer->transfer->flags.b.minislot = 1;
1986 if(!peer->transfer->flags.b.minislot && (slotsleft() < 1)) {
1988 qstr(sk, "$MaxedOut|");
1991 if((start != 0) && ((start >= sb.st_size) || (lseek(fd, start, SEEK_SET) < 0)))
1994 qstr(sk, "$Error Offset out of range|");
1997 if((numbytes < 0) || (start + numbytes > sb.st_size))
1998 numbytes = sb.st_size - start;
1999 lesk = wrapsock(fd);
2000 transferprepul(peer->transfer, sb.st_size, start, start + numbytes, lesk);
2002 qstrf(sk, "$Sending %i|", numbytes);
2006 static void cmd_adcget(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2010 int start, numbytes;
2011 struct sharecache *node;
2013 struct socket *lesk;
2017 if(peer->transfer == NULL)
2022 if((argv = parseadc(args)) == NULL)
2027 if(parrlen(argv) < 4)
2032 start = atoi(argv[2]);
2033 numbytes = atoi(argv[3]);
2036 if(((fd = openfilelist(argv[1])) < 0) && (errno != 0))
2038 qstr(sk, "$Error Could not send file list|");
2040 } else if(fd >= 0) {
2041 if((wbuf = icsmbstowcs(argv[1], "UTF-8", NULL)) != NULL)
2042 transfersetpath(peer->transfer, wbuf);
2043 peer->transfer->flags.b.minislot = 1;
2047 if(!strncmp(argv[1], "TTH/", 4))
2049 if((node = findbytth(argv[1] + 4)) == NULL)
2051 qstr(sk, "$Error File not in cache|");
2055 if((node = resdcpath((argv[1][0] == '/')?(argv[1] + 1):(argv[1]), "UTF-8", '/')) == NULL)
2057 qstr(sk, "$Error File not in cache|");
2061 if((fd = opensharecache(node)) < 0)
2063 qstrf(sk, "$Error %s|", strerror(errno));
2066 buf = getfspath(node);
2067 if((wbuf = icsmbstowcs(buf, NULL, NULL)) == NULL)
2068 flog(LOG_WARNING, "could not convert native path into a wcs (%s): %s", buf, strerror(errno));
2070 transfersetpath(peer->transfer, wbuf);
2073 if(!strcmp(argv[0], "file"))
2075 for(i = 4; argv[i] != NULL; i++)
2077 if(!strcmp(argv[i], "ZL1"))
2078 initcompress(peer, CPRS_ZLIB);
2080 if(fstat(fd, &sb) < 0)
2082 flog(LOG_WARNING, "could not stat file %ls: %s", node->name, strerror(errno));
2083 qstr(sk, "$Error|");
2086 if(sb.st_size < 65536)
2087 peer->transfer->flags.b.minislot = 1;
2088 if(!peer->transfer->flags.b.minislot && (slotsleft() < 1)) {
2089 qstr(sk, "$MaxedOut|");
2092 if((start != 0) && ((start >= sb.st_size) || (lseek(fd, start, SEEK_SET) < 0)))
2094 qstr(sk, "$Error Offset out of range|");
2097 if((numbytes < 0) || (start + numbytes > sb.st_size))
2098 numbytes = sb.st_size - start;
2099 lesk = wrapsock(fd);
2100 transferprepul(peer->transfer, sb.st_size, start, start + numbytes, lesk);
2103 qstr(sk, "$ADCSND");
2104 sendadc(sk, "file");
2105 sendadc(sk, argv[1]);
2106 sendadcf(sk, "%i", start);
2107 sendadcf(sk, "%i", numbytes);
2108 if(peer->compress == CPRS_ZLIB)
2112 } else if(!strcmp(argv[0], "tthl")) {
2114 * XXX: Implement full TTHL support.
2116 * In the meantime, this is better than nothing, since it at
2117 * least allows fetching of the TTH root if it isn't already
2122 qstr(sk, "$Error no TTHL data for virtual files|");
2125 qstr(sk, "$ADCSND");
2126 sendadc(sk, "tthl");
2127 sendadc(sk, argv[1]);
2131 sockqueue(sk, node->hashtth, 24);
2133 qstr(sk, "$Error Namespace not implemented|");
2143 static void handletthl(struct dcpeer *peer)
2147 while(peer->inbufdata >= 24)
2149 pushtigertree(&peer->tth, peer->inbuf);
2150 memmove(peer->inbuf, peer->inbuf + 24, peer->inbufdata -= 24);
2151 peer->curread += 24;
2153 if(peer->curread >= peer->totalsize)
2155 if(peer->timeout == NULL)
2156 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
2157 peer->state = PEER_CMD;
2158 synctigertree(&peer->tth);
2159 restigertree(&peer->tth, buf);
2160 transfersethash(peer->transfer, newhash(L"TTH", 24, buf));
2165 static void cmd_adcsnd(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2168 int start, numbytes;
2170 if(peer->transfer == NULL)
2175 if((argv = parseadc(args)) == NULL)
2180 if(parrlen(argv) < 4)
2185 start = atoi(argv[2]);
2186 numbytes = atoi(argv[3]);
2187 if(!strcmp(argv[0], "tthl"))
2189 if((start != 0) || (numbytes % 24 != 0))
2191 /* Weird. Bail out. */
2195 if(peer->timeout != NULL)
2196 canceltimer(peer->timeout);
2197 peer->state = PEER_TTHL;
2198 peer->totalsize = numbytes;
2200 peer->fetchingtthl = 0;
2201 inittigertree(&peer->tth);
2203 } else if(!strcmp(argv[0], "file")) {
2204 if(start != peer->transfer->curpos)
2209 if(start + numbytes != peer->transfer->size)
2211 transfersetsize(peer->transfer, start + numbytes);
2216 if(peer->inbufdata > 0)
2218 sockpushdata(sk, peer->inbuf, peer->inbufdata);
2219 peer->inbufdata = 0;
2220 transread(sk, peer);
2223 /* We certainly didn't request this...*/
2232 static void cmd_sending(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2236 if(peer->transfer == NULL)
2241 numbytes = atoi(args);
2242 if(peer->transfer->size - peer->transfer->curpos != numbytes)
2244 transfersetsize(peer->transfer, peer->transfer->curpos + numbytes);
2249 if(peer->inbufdata > 0)
2251 sockpushdata(sk, peer->inbuf, peer->inbufdata);
2252 peer->inbufdata = 0;
2253 transread(sk, peer);
2259 static void cmd_(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
2264 hubhandleaction(sk, fn, cmd, args);
2268 static void cmd_(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2274 static int hubreqconn(struct fnetpeer *peer)
2279 if((peer->fn->state != FNN_EST) || (peer->fn->fnet != &dcnet))
2284 if((hub = peer->fn->data) == NULL)
2289 if((mbsnick = icwcstombs(peer->id, hub->charset)) == NULL)
2290 return(1); /* Shouldn't happen, of course, but who knows... */
2293 sendctm(peer->fn->sk, mbsnick);
2294 expectpeer(mbsnick, peer->fn);
2296 qstrf(peer->fn->sk, "$RevConnectToMe %s %s|", hub->nativenick, mbsnick);
2302 static int hubsendchat(struct fnetnode *fn, int public, wchar_t *to, wchar_t *string)
2305 char *mbsstring, *mbsto;
2308 if((mbsto = icwcstombs(to, hub->charset)) == NULL)
2313 if((mbsstring = icwcstombs(string, hub->charset)) == NULL)
2318 if((strchr(mbsto, '|') != NULL) || (strchr(mbsto, ' ') != NULL))
2325 if(strchr(mbsstring, '|') != NULL)
2336 qstrf(fn->sk, "<%s> %s|", hub->nativenick, mbsstring);
2338 qstrf(fn->sk, "$To: %s From: %s $<%s> %s|", mbsto, hub->nativenick, hub->nativenick, mbsstring);
2341 qstrf(fn->sk, "$To: %s From: %s $<%s> %s|", mbsto, hub->nativenick, hub->nativenick, mbsstring);
2348 static void findsizelimit(struct sexpr *sexpr, int *min, int *max)
2350 int minl, maxl, minr, maxr, retmin, retmax;
2355 findsizelimit(sexpr->l, &minl, &maxl);
2356 findsizelimit(sexpr->r, &minr, &maxr);
2357 retmin = (minl > minr)?minl:minr;
2358 if((maxl != -1) && (maxr != -1))
2359 retmax = (maxl < maxr)?maxl:maxr;
2368 findsizelimit(sexpr->l, &minl, &maxl);
2369 findsizelimit(sexpr->r, &minr, &maxr);
2370 retmin = (minl < minr)?minl:minr;
2371 if((maxl == -1) || (maxr == -1))
2374 retmax = (maxl > maxr)?maxl:maxr;
2377 findsizelimit(sexpr->l, &minl, &maxl);
2378 if((minl == 0) && (maxl == -1)) /* Interval is unspecified */
2382 } else if((minl == 0) && (maxl != -1)) {
2385 } else if((minl != 0) && (maxl == -1)) {
2388 } else { /* This would yield two seperate intervals, which DC cannot handle */
2394 retmax = sexpr->d.n - 1;
2397 retmin = sexpr->d.n;
2398 retmax = sexpr->d.n;
2401 retmin = sexpr->d.n + 1;
2415 static struct hash *findsehash(struct sexpr *sexpr)
2417 struct hash *h1, *h2;
2422 if((h1 = findsehash(sexpr->l)) != NULL)
2424 if((h1 = findsehash(sexpr->r)) != NULL)
2428 if((h1 = findsehash(sexpr->l)) == NULL)
2430 if((h2 = findsehash(sexpr->r)) == NULL)
2436 if(!wcscmp(sexpr->d.hash->algo, L"TTH"))
2437 return(sexpr->d.hash);
2444 static int hubsearch(struct fnetnode *fn, struct search *srch, struct srchfnnlist *ln)
2447 struct wcslist *list, *cur;
2448 char *sstr, *buf, *p;
2449 size_t sstrsize, sstrdata;
2450 struct sockaddr *name;
2452 int minsize, maxsize;
2456 if((fn->state != FNN_EST) || (fn->sk == NULL) || (fn->sk->state != SOCK_EST))
2458 list = findsexprstrs(srch->sexpr);
2459 findsizelimit(srch->sexpr, &minsize, &maxsize);
2460 hash = findsehash(srch->sexpr);
2461 if((minsize != 0) && (maxsize != -1))
2463 /* Choose either minsize or maxsize by trying to determine
2464 * which choice will be most restrictive. The result can be
2465 * approximative at best anyway, so don't try too hard... */
2466 if((50000000 - maxsize) > (minsize - 50000000))
2472 sstrsize = sstrdata = 0;
2473 if((hash != NULL) && (hash->len == 24))
2475 /* Prioritize hash searches above all else */
2476 bufcat(sstr, "F?T?0?9?TTH:", 12);
2477 buf = base32encode(hash->buf, hash->len);
2479 bufcat(sstr, buf, 39);
2484 sizebuf2(sstr, sstrdata + 32, 1);
2485 sstrdata += snprintf(sstr + sstrdata, sstrsize - sstrdata, "T?F?%i?1?", minsize);
2486 } else if(maxsize != -1) {
2487 sizebuf2(sstr, sstrdata + 32, 1);
2488 sstrdata += snprintf(sstr + sstrdata, sstrsize - sstrdata, "T?T?%i?1?", maxsize);
2490 bufcat(sstr, "F?F?0?1?", 8);
2494 for(cur = list; cur != NULL; cur = cur->next)
2496 /* Use DCCHARSET in $Get paths until further researched... */
2497 if((buf = icwcstombs(cur->str, DCCHARSET)) == NULL)
2499 /* Can't find anything anyway if the search expression
2500 * requires characters outside DC's charset. There's
2501 * nothing technically wrong with the search itself,
2502 * however, so return success. This should be
2503 * considered as an optimization. */
2510 addtobuf(sstr, '$');
2512 * It probably doesn't hurt if buf contains any extra
2513 * dollar signs - it will just result in extra search
2514 * terms, and the extraneous results will be filtered by
2515 * the search layer anyway. It hurts if it contains any
2516 * pipes, though, so let's sell them for money.
2518 for(p = buf; *p; p++)
2523 bufcat(sstr, buf, strlen(buf));
2527 /* Will match all files... :-/ */
2528 addtobuf(sstr, '.');
2534 if(sockgetremotename2(udpsock, fn->sk, &name, &namelen) < 0)
2536 flog(LOG_WARNING, "cannot get address of UDP socket");
2538 qstrf(fn->sk, "$Search %s %s|", formataddress(name, namelen), sstr);
2542 qstrf(fn->sk, "$Search Hub:%s %s|", hub->nativenick, sstr);
2546 fn->lastsrch = time(NULL);
2554 #define cc(c) ((void (*)(struct socket *, void *, char *, char *))(c))
2555 static struct command hubcmds[] =
2557 {"$Lock", cc(cmd_lock)},
2558 {"$HubName", cc(cmd_hubname)},
2559 {"$Hello", cc(cmd_hello)},
2560 {"$Quit", cc(cmd_quit)},
2561 {"$NickList", cc(cmd_nicklist)},
2562 {"$OpList", cc(cmd_oplist)},
2563 {"$MyINFO", cc(cmd_myinfo)},
2564 {"$ForceMove", cc(cmd_forcemove)},
2565 {"$Search", cc(cmd_search)},
2566 {"$MultiSearch", cc(cmd_search)},
2567 {"$ConnectToMe", cc(cmd_connecttome)},
2568 {"$RevConnectToMe", cc(cmd_revconnecttome)},
2569 {"$GetNetInfo", cc(cmd_getnetinfo)},
2570 {"$To:", cc(cmd_to)},
2571 {"$SR", cc(cmd_sr)},
2572 {"$UserCommand", cc(cmd_usercommand)},
2573 {"$GetPass", cc(cmd_getpass)},
2574 {"$LogedIn", cc(cmd_logedin)}, /* sic */
2578 static struct command peercmds[] =
2580 {"$MyNick", cc(cmd_mynick)},
2581 {"$Lock", cc(cmd_peerlock)},
2582 {"$Direction", cc(cmd_direction)},
2583 {"$Key", cc(cmd_key)},
2584 {"$FileLength", cc(cmd_filelength)},
2585 {"$Error", cc(cmd_error)},
2586 {"$MaxedOut", cc(cmd_maxedout)},
2587 {"$Get", cc(cmd_get)},
2588 {"$Send", cc(cmd_send)},
2589 {"$Supports", cc(cmd_supports)},
2590 {"$GetBlock", cc(cmd_getblock)},
2591 {"$UGetBlock", cc(cmd_getblock)},
2592 {"$GetZBlock", cc(cmd_getblock)},
2593 {"$UGetZBlock", cc(cmd_getblock)},
2594 {"$ADCGET", cc(cmd_adcget)},
2595 {"$ADCSND", cc(cmd_adcsnd), 1},
2596 {"$Sending", cc(cmd_sending), 1},
2601 static void dctransdetach(struct transfer *transfer, struct dcpeer *peer)
2603 CBUNREG(transfer, trans_filterout, peer);
2606 peer->transfer = NULL;
2610 static void dctransgotdata(struct transfer *transfer, struct dcpeer *peer)
2614 unsigned char outbuf[1024];
2618 if((peer->state == PEER_TRNS) || (peer->state == PEER_SYNC))
2620 if(sockqueuesize(peer->sk) < 65536)
2622 if((buf = transfergetdata(transfer, &bufsize)) != NULL)
2624 if(peer->compress == CPRS_NONE)
2626 sockqueue(peer->sk, buf, bufsize);
2627 } else if(peer->compress == CPRS_ZLIB) {
2628 cstr = peer->cprsdata;
2629 cstr->next_in = buf;
2630 cstr->avail_in = bufsize;
2631 while(cstr->avail_in > 0)
2633 cstr->next_out = outbuf;
2634 cstr->avail_out = sizeof(outbuf);
2635 if((ret = deflate(cstr, 0)) != Z_OK)
2637 flog(LOG_WARNING, "bug? deflate() did not return Z_OK (but rather %i)", ret);
2641 sockqueue(peer->sk, outbuf, sizeof(outbuf) - cstr->avail_out);
2646 if(peer->state == PEER_SYNC)
2648 if(peer->compress == CPRS_ZLIB)
2650 cstr = peer->cprsdata;
2651 cstr->next_in = NULL;
2655 cstr->next_out = outbuf;
2656 cstr->avail_out = sizeof(outbuf);
2657 ret = deflate(cstr, Z_FINISH);
2658 if((ret != Z_OK) && (ret != Z_STREAM_END))
2660 flog(LOG_WARNING, "bug? deflate(Z_FINISH) did not return Z_OK (but rather %i)", ret);
2664 sockqueue(peer->sk, outbuf, sizeof(outbuf) - cstr->avail_out);
2665 } while(ret != Z_STREAM_END);
2671 if(peer->timeout == NULL)
2672 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
2673 peer->state = PEER_CMD;
2675 transfersetstate(transfer, TRNS_HS);
2676 socksettos(peer->sk, confgetint("fnet", "fnptos"));
2677 transfer->flags.b.minislot = 0;
2678 peer->sk->writecb = NULL;
2685 static void dctransendofdata(struct transfer *transfer, struct dcpeer *peer)
2687 peer->state = PEER_SYNC;
2688 dctransgotdata(transfer, peer);
2691 static void dcwantdata(struct transfer *transfer, struct dcpeer *peer)
2693 if(transferdatasize(transfer) < 65536)
2694 peer->sk->ignread = 0;
2697 static void transread(struct socket *sk, struct dcpeer *peer)
2701 struct transfer *transfer;
2703 if((buf = sockgetinbuf(sk, &bufsize)) == NULL)
2705 if(peer->transfer == NULL)
2711 transferputdata(peer->transfer, buf, bufsize);
2713 if(peer->transfer->curpos >= peer->transfer->size)
2715 transfer = peer->transfer;
2716 transferdetach(transfer);
2717 transferendofdata(transfer);
2720 if(transferdatasize(peer->transfer) > 65535)
2724 static void transerr(struct socket *sk, int err, struct dcpeer *peer)
2726 struct transfer *transfer;
2728 if((transfer = peer->transfer) == NULL)
2733 transferdetach(transfer);
2734 transferendofdata(transfer);
2737 static void transwrite(struct socket *sk, struct dcpeer *peer)
2739 if((peer->state != PEER_TRNS) && (peer->state != PEER_SYNC))
2741 if(peer->transfer == NULL)
2746 dctransgotdata(peer->transfer, peer);
2749 static void udpread(struct socket *sk, void *data)
2751 char *buf, *p, *p2, *hashbuf;
2752 size_t buflen, hashlen;
2753 char *nick, *filename, *hubname;
2754 struct sockaddr_in hubaddr;
2756 struct fnetnode *fn, *myfn;
2759 wchar_t *wnick, *wfile;
2762 if((buf = sockgetinbuf(sk, &buflen)) == NULL)
2764 buf = srealloc(buf, buflen + 1);
2766 if(!strncmp(buf, "$SR ", 4))
2770 if((p2 = strchr(p, ' ')) == NULL)
2778 if((p2 = strchr(p, 5)) == NULL)
2785 if((p2 = strchr(p, ' ')) == NULL)
2793 if((p2 = strchr(p, '/')) == NULL)
2801 if((p2 = strchr(p, 5)) == NULL)
2808 if((p2 = strstr(p, " (")) == NULL)
2815 if((p2 = strchr(p, ':')) == NULL)
2821 hubaddr.sin_family = AF_INET;
2822 if(!inet_aton(p, &hubaddr.sin_addr))
2828 if((p2 = strchr(p, ')')) == NULL)
2834 hubaddr.sin_port = htons(atoi(p));
2835 /* Use DCCHARSET in $Get paths until further researched... */
2836 if((wfile = icmbstowcs(filename, DCCHARSET)) == NULL)
2843 if(!strncmp(hubname, "TTH:", 4))
2845 if((hashbuf = base32decode(hubname + 4, &hashlen)) != NULL)
2848 hash = newhash(L"TTH", 24, hashbuf);
2852 for(fn = fnetnodes; fn != NULL; fn = fn->next)
2854 if((fn->fnet == &dcnet) && ((hub = fn->data) != NULL))
2856 if((hub->nativename != NULL) && !strcmp(hub->nativename, hubname))
2871 for(fn = fnetnodes; fn != NULL; fn = fn->next)
2873 if((fn->fnet == &dcnet) && (fn->sk != NULL) && addreq(fn->sk->remote, (struct sockaddr *)&hubaddr))
2883 if((wnick = icmbstowcs(nick, (hub == NULL)?DCCHARSET:(hub->charset))) == NULL)
2888 sr = newsrchres(&dcnet, wfile, wnick);
2889 if(sr->peernick != NULL)
2891 sr->peernick = swcsdup(wnick);
2897 getfnetnode(sr->fn = myfn);
2906 static void hubread(struct socket *sk, struct fnetnode *fn)
2913 hub = (struct dchub *)fn->data;
2914 if((newbuf = sockgetinbuf(sk, &datalen)) == NULL)
2916 if(hub->inbufdata > 500000) /* Discard possible malicious data */
2918 sizebuf2(hub->inbuf, hub->inbufdata + datalen, 1);
2919 memcpy(hub->inbuf + hub->inbufdata, newbuf, datalen);
2921 p = hub->inbuf + hub->inbufdata;
2922 hub->inbufdata += datalen;
2923 while((datalen > 0) && ((p = memchr(p, '|', datalen)) != NULL))
2926 newqcmd(&hub->queue, hub->inbuf);
2927 memmove(hub->inbuf, p, hub->inbufdata -= p - hub->inbuf);
2928 datalen = hub->inbufdata;
2933 static void huberr(struct socket *sk, int err, struct fnetnode *fn)
2938 static int hubsetnick(struct fnetnode *fn, wchar_t *newnick)
2944 if((buf = icwcstombs(newnick, (hub == NULL)?DCCHARSET:(hub->charset))) == NULL)
2946 if((strchr(buf, ' ') != NULL) || (strchr(buf, '|') != NULL) || (strchr(buf, '$') != NULL))
2951 if(hub == NULL) /* Not yet connected */
2956 if(hub->nativenick != NULL)
2957 free(hub->nativenick);
2958 hub->nativenick = buf;
2962 static struct dchub *newdchub(struct fnetnode *fn)
2969 new = smalloc(sizeof(*new));
2970 memset(new, 0, sizeof(*new));
2972 if(confgetint("dc", "dcppemu"))
2974 if((emu = wpfind(fn->args, L"dcppemu")) != NULL)
2982 if((wcharset = wpfind(fn->args, L"charset")) != NULL)
2984 if((charset = icwcstombs(wcharset, "US-ASCII")) != NULL)
2986 if(!havecharset(charset))
2994 new->charset = charset;
2996 new->charset = sstrdup(DCCHARSET);
2997 if(hubsetnick(fn, fn->mynick))
2998 fnetsetnick(fn, L"DoldaConnectUser-IN");
2999 /* IN as in Invalid Nick */
3003 static struct dcpeer *newdcpeer(struct socket *sk)
3007 new = smalloc(sizeof(*new));
3008 memset(new, 0, sizeof(*new));
3009 new->transfer = NULL;
3012 if(confgetint("dc", "dcppemu"))
3023 static void freedcpeer(struct dcpeer *peer)
3026 struct qcommand *qcmd;
3031 if(peer->next != NULL)
3032 peer->next->prev = peer->prev;
3033 if(peer->prev != NULL)
3034 peer->prev->next = peer->next;
3035 if(peer->transfer != NULL)
3037 if(peer->transfer->dir == TRNSD_UP)
3038 peer->transfer->close = 1;
3039 if(peer->transfer->dir == TRNSD_DOWN)
3040 resettransfer(peer->transfer);
3041 transferdetach(peer->transfer);
3043 if(peer->timeout != NULL)
3044 canceltimer(peer->timeout);
3045 if(peer->sk->data == peer)
3046 peer->sk->data = NULL;
3047 peer->sk->readcb = NULL;
3048 peer->sk->writecb = NULL;
3049 peer->sk->errcb = NULL;
3052 if(peer->supports != NULL)
3054 for(i = 0; peer->supports[i] != NULL; i++)
3055 free(peer->supports[i]);
3056 free(peer->supports);
3058 if(peer->inbuf != NULL)
3060 if(peer->key != NULL)
3062 if(peer->wcsname != NULL)
3063 free(peer->wcsname);
3064 if(peer->nativename != NULL)
3065 free(peer->nativename);
3066 if(peer->charset != NULL)
3067 free(peer->charset);
3068 if(peer->fn != NULL)
3069 putfnetnode(peer->fn);
3070 while((qcmd = ulqcmd(&peer->queue)) != NULL)
3076 static void hubconnect(struct fnetnode *fn)
3078 fn->sk->readcb = (void (*)(struct socket *, void *))hubread;
3079 fn->sk->errcb = (void (*)(struct socket *, int, void *))huberr;
3081 fn->data = newdchub(fn);
3086 static void hubdestroy(struct fnetnode *fn)
3089 struct qcommand *qcmd;
3091 hub = (struct dchub *)fn->data;
3092 if((fn->sk != NULL) && (fn->sk->data == fn))
3094 fn->sk->data = NULL;
3095 fn->sk->readcb = NULL;
3096 fn->sk->errcb = NULL;
3101 while((qcmd = ulqcmd(&hub->queue)) != NULL)
3103 if(hub->nativename != NULL)
3104 free(hub->nativename);
3105 if(hub->nativenick != NULL)
3106 free(hub->nativenick);
3107 if(hub->charset != NULL)
3109 if(hub->inbuf != NULL)
3114 static wchar_t *dcbasename(wchar_t *filename)
3118 if((ret = wcsrchr(filename, L'\\')) != NULL)
3123 static struct transferiface dctransfer =
3125 .detach = (void (*)(struct transfer *, void *))dctransdetach,
3126 .gotdata = (void (*)(struct transfer *, void *))dctransgotdata,
3127 .endofdata = (void (*)(struct transfer *, void *))dctransendofdata,
3128 .wantdata = (void (*)(struct transfer *, void *))dcwantdata
3131 static struct fnet dcnet =
3134 .connect = hubconnect,
3135 .destroy = hubdestroy,
3136 .setnick = hubsetnick,
3137 .reqconn = hubreqconn,
3138 .sendchat = hubsendchat,
3139 .search = hubsearch,
3140 .filebasename = dcbasename
3143 static void peerread(struct socket *sk, struct dcpeer *peer)
3147 struct command *cmd;
3149 if((newbuf = sockgetinbuf(sk, &datalen)) == NULL)
3151 sizebuf2(peer->inbuf, peer->inbufdata + datalen, 1);
3152 memcpy(peer->inbuf + peer->inbufdata, newbuf, datalen);
3154 peer->inbufdata += datalen;
3155 if(peer->state == PEER_CMD)
3158 while((peer->inbufdata > 0) && (p = memchr(peer->inbuf, '|', peer->inbufdata)) != NULL)
3161 newqcmd(&peer->queue, peer->inbuf);
3162 for(cmd = peercmds; cmd->handler != NULL; cmd++)
3164 if(!memcmp(peer->inbuf, cmd->name, strlen(cmd->name)) && ((peer->inbuf[strlen(cmd->name)] == ' ') || (peer->inbuf[strlen(cmd->name)] == '|')))
3167 memmove(peer->inbuf, p, peer->inbufdata -= p - peer->inbuf);
3170 peer->state = PEER_STOP;
3174 } else if(peer->state == PEER_TTHL) {
3179 static void peererror(struct socket *sk, int err, struct dcpeer *peer)
3184 static void peerconnect(struct socket *sk, int err, struct fnetnode *fn)
3186 struct dcpeer *peer;
3196 peer = newdcpeer(sk);
3199 peer->dcppemu = hub->dcppemu;
3200 sk->readcb = (void (*)(struct socket *, void *))peerread;
3201 sk->errcb = (void (*)(struct socket *, int, void *))peererror;
3203 socksettos(sk, confgetint("fnet", "fnptos"));
3205 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
3210 static void peeraccept(struct socket *sk, struct socket *newsk, void *data)
3212 struct dcpeer *peer;
3214 peer = newdcpeer(newsk);
3216 newsk->readcb = (void (*)(struct socket *, void *))peerread;
3217 newsk->errcb = (void (*)(struct socket *, int, void *))peererror;
3219 socksettos(newsk, confgetint("fnet", "fnptos"));
3220 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
3223 static void updatehmlist(void)
3225 int i, lev, ic, ret;
3226 struct sharecache *node;
3227 char *buf, *buf2, numbuf[32];
3228 size_t bufsize, bufdata;
3232 buf = smalloc(bufsize = 65536);
3233 node = shareroot->child;
3238 /* Use DCCHARSET in $Get paths until further researched... */
3239 if((buf2 = icwcstombs(node->name, DCCHARSET)) != NULL)
3241 for(i = 0; i < lev; i++)
3243 bufcat(buf, buf2, strlen(buf2));
3245 if(node->f.b.type == FILE_REG)
3248 sprintf(numbuf, "%zi", node->size);
3249 bufcat(buf, numbuf, strlen(numbuf));
3256 if((node->child != NULL) && !ic)
3260 } else if(node->next != NULL) {
3263 while(node->next == NULL)
3266 node = node->parent;
3267 if(node == shareroot)
3270 if(node == shareroot)
3275 if(hmlistname != NULL)
3280 hmlistname = sstrdup("/tmp/dc-filelist-hm-XXXXXX");
3281 if((fd = mkstemp(hmlistname)) < 0)
3283 flog(LOG_WARNING, "could not create HM file list tempfile: %s", strerror(errno));
3288 * I do not want to implement a good Huffman encoder, and it's not
3289 * like Huffman encoding actually yields any impressive results
3290 * for DC file lists anyway, so I'll just output a bogus
3291 * tree. Implement a good encoder if you want to.
3293 write(fd, "HE3\r\0", 5);
3294 write(fd, &bufdata, 4);
3296 write(fd, &ibuf, 2);
3298 for(i = 0; i < 256; i++)
3301 write(fd, &ibuf, 1);
3303 for(i = 0; i < 256; i++)
3305 for(buf2 = buf; bufdata > 0;)
3307 if((ret = write(fd, buf2, bufdata)) < 0)
3309 flog(LOG_WARNING, "could not write file list: %s", strerror(errno));
3320 static struct xmlent
3327 /* {L'\'', L"""}, Emulate DC++ escaping by omitting this. */
3331 static wchar_t *escapexml(wchar_t *src)
3333 static wchar_t *buf = NULL;;
3336 size_t bufsize, bufdata;
3342 bufsize = bufdata = 0;
3343 for(; *src != L'\0'; src++)
3346 if((c > 0) && (c < 32))
3348 bufcat(buf, L"&#", 2);
3349 ret = swprintf(nbuf, (sizeof(nbuf) / sizeof(*nbuf)), L"%i", c);
3350 bufcat(buf, nbuf, ret);
3351 addtobuf(buf, L';');
3353 for(ent = entities; ent->ent != NULL; ent++)
3357 bufcat(buf, ent->ent, wcslen(ent->ent));
3361 if(ent->ent == NULL)
3362 addtobuf(buf, *src);
3365 addtobuf(buf, L'\0');
3369 static void updatexmllist(void)
3373 char cidbuf[14], *namebuf;
3375 struct sharecache *node;
3377 if(xmllistname != NULL)
3379 unlink(xmllistname);
3382 xmllistname = sstrdup("/tmp/dc-filelist-dcxml-XXXXXX");
3383 if((fd = mkstemp(xmllistname)) < 0)
3385 flog(LOG_WARNING, "could not create XML file list tempfile: %s", strerror(errno));
3390 if((fs = fdopen(fd, "w")) == NULL)
3392 flog(LOG_WARNING, "could not fdopen XML list fd %i: %s", fd, strerror(errno));
3393 unlink(xmllistname);
3399 fprintf(fs, "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>\r\n");
3400 for(i = 0; i < sizeof(cidbuf) - 1; i++)
3401 cidbuf[i] = (rand() % ('Z' - 'A' + 1)) + 'A';
3403 if(confgetint("dc", "dcppemu"))
3404 fprintf(fs, "<FileListing Version=\"1\" CID=\"%s\" Base=\"/\" Generator=\"DC++ 0.674\">\r\n", cidbuf);
3406 fprintf(fs, "<FileListing Version=\"1\" CID=\"%s\" Base=\"/\" Generator=\"%s\">\r\n", cidbuf, "DoldaConnect" VERSION);
3408 node = shareroot->child;
3412 if((namebuf = icswcstombs(escapexml(node->name), "UTF-8", NULL)) != NULL)
3414 for(i = 0; i < lev; i++)
3416 if(node->child != NULL)
3418 fprintf(fs, "<Directory Name=\"%s\">\r\n", namebuf);
3423 fprintf(fs, "<File Name=\"%s\" Size=\"%zi\"", namebuf, node->size);
3424 if(node->f.b.hastth)
3426 hashbuf = base32encode(node->hashtth, 24);
3427 fprintf(fs, " TTH=\"%.39s\"", hashbuf);
3430 fprintf(fs, "/>\r\n");
3432 while(node->next == NULL)
3434 node = node->parent;
3435 if(node == shareroot)
3440 for(i = 0; i < lev; i++)
3442 fprintf(fs, "</Directory>\r\n");
3445 if(node == shareroot)
3451 if(confgetint("dc", "dcppemu"))
3452 fprintf(fs, "</FileListing>");
3454 fprintf(fs, "</FileListing>\r\n");
3458 static void updatexmlbz2list(void)
3467 if(xmllistname == NULL)
3469 if((in = fopen(xmllistname, "r")) == NULL)
3471 flog(LOG_WARNING, "could not open XML file list for bzipping: %s", strerror(errno));
3474 if(xmlbz2listname != NULL)
3476 unlink(xmlbz2listname);
3477 free(xmlbz2listname);
3479 xmlbz2listname = sstrdup("/tmp/dc-filelist-dcxmlbz2-XXXXXX");
3480 if((fd = mkstemp(xmlbz2listname)) < 0)
3482 flog(LOG_WARNING, "could not create bzipped XML file list tempfile: %s", strerror(errno));
3483 free(xmlbz2listname);
3484 xmlbz2listname = NULL;
3488 if((real = fdopen(fd, "w")) == NULL)
3490 flog(LOG_WARNING, "could not fdopen bzipped XML list fd %i: %s", fd, strerror(errno));
3492 unlink(xmlbz2listname);
3493 free(xmlbz2listname);
3494 xmlbz2listname = NULL;
3498 out = BZ2_bzWriteOpen(&err, real, 9, 0, 0);
3501 flog(LOG_WARNING, "could not open bzip2 stream from XML list");
3503 unlink(xmlbz2listname);
3504 free(xmlbz2listname);
3505 xmlbz2listname = NULL;
3511 bufdata = fread(buf, 1, sizeof(buf), in);
3512 BZ2_bzWrite(&err, out, buf, bufdata);
3515 BZ2_bzWriteClose(&err, out, 0, NULL, NULL);
3519 static void listtimercb(int cancelled, void *uudata)
3521 listwritetimer = NULL;
3526 static void updatelists(int now)
3528 if((hmlistname == NULL) || (xmllistname == NULL) || (xmlbz2listname == NULL))
3532 if(listwritetimer == NULL)
3533 listwritetimer = timercallback(ntime() + confgetint("cli", "hashwritedelay"), listtimercb, NULL);
3536 if(listwritetimer != NULL)
3537 canceltimer(listwritetimer);
3543 static int shareupdate(unsigned long long uusharesize, void *data)
3549 static void dispatchcommand(struct qcommand *qcmd, struct command *cmdlist, struct socket *sk, void *data)
3552 struct command *cmd;
3554 if((p = strchr(qcmd->string, ' ')) != NULL)
3556 for(cmd = cmdlist; cmd->handler != NULL; cmd++)
3558 if(!strcmp(cmd->name, qcmd->string))
3561 if(cmd->handler != NULL)
3562 cmd->handler(sk, data, qcmd->string, p);
3565 flog(LOG_DEBUG, "Unimplemented DC command: %s \"%s\"", qcmd->string, p?p:"noargs");
3569 static int run(void)
3571 struct fnetnode *fn, *nextfn;
3573 struct dcpeer *peer, *nextpeer;
3574 struct qcommand *qcmd;
3578 for(fn = fnetnodes; fn != NULL; fn = nextfn)
3581 if(fn->fnet != &dcnet)
3583 if(fn->data == NULL)
3585 hub = (struct dchub *)fn->data;
3586 if((qcmd = ulqcmd(&hub->queue)) != NULL)
3588 if(*qcmd->string == '$')
3590 if((fn->sk != NULL) && (fn->sk->state == SOCK_EST))
3591 dispatchcommand(qcmd, hubcmds, fn->sk, fn);
3592 } else if(*qcmd->string != 0) {
3593 hubrecvchat(fn->sk, fn, NULL, qcmd->string);
3600 for(peer = peers; peer != NULL; peer = nextpeer)
3602 nextpeer = peer->next;
3603 if((qcmd = ulqcmd(&peer->queue)) != NULL)
3605 if(peer->timeout != NULL)
3606 canceltimer(peer->timeout);
3607 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
3608 if(*qcmd->string == '$')
3609 dispatchcommand(qcmd, peercmds, peer->sk, peer);
3618 static void preinit(int hup)
3625 static int updateudpport(struct configvar *var, void *uudata)
3627 struct sockaddr_in addr;
3628 struct socket *newsock;
3630 memset(&addr, 0, sizeof(addr));
3631 addr.sin_family = AF_INET;
3632 addr.sin_port = htons(var->val.num);
3633 if((newsock = netcsdgram((struct sockaddr *)&addr, sizeof(addr))) == NULL)
3635 flog(LOG_WARNING, "could not create new DC UDP socket, reverting to old: %s", strerror(errno));
3638 newsock->readcb = udpread;
3645 static int updatetcpport(struct configvar *var, void *uudata)
3647 struct sockaddr_in addr;
3648 struct socket *newsock;
3650 memset(&addr, 0, sizeof(addr));
3651 addr.sin_family = AF_INET;
3652 addr.sin_port = htons(var->val.num);
3653 if((newsock = netcslisten(SOCK_STREAM, (struct sockaddr *)&addr, sizeof(addr), peeraccept, NULL)) == NULL)
3654 flog(LOG_INFO, "could not listen to a remote address, going into passive mode");
3661 static int init(int hup)
3663 struct sockaddr_in addr;
3667 GCBREG(sharechangecb, shareupdate, NULL);
3672 addr.sin_family = AF_INET;
3673 memset(&addr.sin_addr, 0, sizeof(addr.sin_addr));
3674 addr.sin_port = htons(confgetint("dc", "udpport"));
3675 if((udpsock = netcsdgram((struct sockaddr *)&addr, sizeof(addr))) == NULL)
3677 flog(LOG_CRIT, "could not create DC UDP socket: %s", strerror(errno));
3680 udpsock->readcb = udpread;
3681 addr.sin_port = htons(confgetint("dc", "tcpport"));
3682 if((tcpsock = netcslisten(SOCK_STREAM, (struct sockaddr *)&addr, sizeof(addr), peeraccept, NULL)) == NULL)
3683 flog(LOG_INFO, "could not listen to a remote address, going into passive mode");
3684 CBREG(confgetvar("dc", "udpport"), conf_update, updateudpport, NULL, NULL);
3685 CBREG(confgetvar("dc", "tcpport"), conf_update, updatetcpport, NULL, NULL);
3686 CBREG(confgetvar("net", "mode"), conf_update, updatetcpport, NULL, NULL);
3691 static void terminate(void)
3693 if(hmlistname != NULL)
3698 if(xmllistname != NULL)
3700 unlink(xmllistname);
3703 if(xmlbz2listname != NULL)
3705 unlink(xmlbz2listname);
3706 free(xmlbz2listname);
3710 static struct configvar myvars[] =
3712 /** Specifies the share description reported to other DC users. */
3713 {CONF_VAR_STRING, "desc", {.str = L""}},
3714 /** Specifies the speed reported to other DC users. Normal values
3715 * are 28.8Kbps, 33.6Kbps, 56Kbps, Satellite, ISDN, DSL, Cable,
3716 * LAN(T1) or LAN(T3)*/
3717 {CONF_VAR_STRING, "speedstring", {.str = L"LAN(T1)"}},
3718 /** The e-mail address to report to other DC users. */
3719 {CONF_VAR_STRING, "email", {.str = L"spam@spam.org"}},
3720 /** Specifies a specific UDP port to use for DC search results. If
3721 * left unspecified, a port is allocated dynamically. Useful for
3722 * NAT routers (see also the net.visibleipv4 address for those
3724 {CONF_VAR_INT, "udpport", {.num = 0}},
3725 /** Specifies a specific TCP port to use for DC peer
3726 * connections. If left unspecified, a port is allocated
3727 * dynamically. Useful for NAT routers (see also the
3728 * net.visibleipv4 address for those cases). */
3729 {CONF_VAR_INT, "tcpport", {.num = 0}},
3730 /** If set to true, doldacond will do its best to emulate DC++
3731 * (currently v0.674). This should be left off if at all possible,
3732 * since turning it on will violate the rules of most hubs and
3733 * thus give hub owners an actual reason to kick you if it is
3734 * detected. It might be needed for some of the more bone-headed
3735 * hub owners, though. Note that DC++ emulation can also be turned
3736 * on or off for individual hubs, overriding this setting. */
3737 {CONF_VAR_BOOL, "dcppemu", {.num = 0}},
3741 static struct module me =
3750 .terminate = terminate,