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
26 #include <netinet/in.h>
27 #include <arpa/inet.h>
45 #include "sysevents.h"
50 * The Direct Connect protocol is extremely ugly. Thus, this code must
51 * also be a bit ugly in certain places. Please forgive me. =/
53 * This also means that there might be some pieces of the code that
54 * look completely illogical to you, and you think that you may make
55 * them much neater/better. However, in many cases it might just be
56 * that it's required to cope with some oddity of the protocol, such
57 * as the amazingly ugly delayed key response in the peer protocol.
60 /* I assume this is the correct character set to use for DC,
61 * considering it was developed without i18n support under Windows */
62 #define DCCHARSET "windows-1252"
64 #ifdef DCPP_MASQUERADE
66 * I honestly don't want to pretend being a client that I'm not, but
67 * there are so many hubs that simply do not accept any clients
68 * outside their whitelists, for no obvious reasons, so I feel that I
69 * am left with little choice. Anyhow, as long as I actually support
70 * all the features that my faked DC++ version does, there should be
71 * very little harm done.
74 #define DCIDTAGV "0.674"
75 #define DCIDFULL "DC++ 0.674"
77 #define DCIDTAG "Dolda"
78 #define DCIDTAGV VERSION
79 #define DCIDFULL "DoldaConnect " VERSION
94 void (*handler)(struct socket *sk, void *data, char *cmd, char *args);
100 struct qcommand *next;
107 size_t inbufdata, inbufsize;
108 struct qcommand *queue;
109 int extended, dcppemu;
117 struct dcexppeer *next, *prev;
120 struct timer *expire;
125 struct dcpeer *next, *prev;
129 size_t inbufdata, inbufsize;
130 size_t curread, totalsize;
132 struct timer *timeout;
133 struct qcommand *queue;
134 struct transfer *transfer;
136 int ptclose; /* Close after transfer is complete */
137 int accepted; /* If false, we connected, otherwise, we accepted */
138 int extended, dcppemu;
139 int direction; /* Using the constants from transfer.h */
141 int hascurpos, fetchingtthl, notthl;
142 struct tigertreehash tth;
151 static struct fnet dcnet;
152 static struct transferiface dctransfer;
153 static struct socket *udpsock = NULL;
154 static struct socket *tcpsock = NULL;
155 static struct dcpeer *peers = NULL;
157 static struct dcexppeer *expected = NULL;
158 static char *hmlistname = NULL;
159 static char *xmllistname = NULL;
160 static char *xmlbz2listname = NULL;
161 static struct timer *listwritetimer = NULL;
163 static void peerconnect(struct socket *sk, int err, struct fnetnode *fn);
164 static void freedcpeer(struct dcpeer *peer);
165 static void transread(struct socket *sk, struct dcpeer *peer);
166 static void transerr(struct socket *sk, int err, struct dcpeer *peer);
167 static void transwrite(struct socket *sk, struct dcpeer *peer);
168 static void updatehmlist(void);
169 static void updatexmllist(void);
170 static void updatexmlbz2list(void);
171 static void requestfile(struct dcpeer *peer);
172 static void updatelists(int now);
174 static int reservedchar(unsigned char c)
176 return((c == 0) || (c == 5) || (c == 124) || (c == 96) || (c == 126) || (c == 36));
179 /* Oh, how I despise having to do this... */
180 static char *dcmakekey(char *lock)
186 buf = smalloc(strlen(lock));
189 for(i = 0; lock[i]; i++)
191 buf[i] = lock[i] ^ save;
192 buf[i] = ((buf[i] & 0x0F) << 4) | ((buf[i] & 0xF0) >> 4);
194 if((i != 0) && reservedchar(buf[i]))
199 buf[0] ^= buf[i - 1];
200 if(reservedchar(buf[0]))
204 key = smalloc(len + 1);
206 for(i = 0; lock[i] != 0; i++)
208 if(reservedchar(buf[i]))
209 offset += sprintf(key + offset, "/%%DCN%03i%%/", buf[i]);
211 key[offset++] = buf[i];
218 static char *pathnmdc2adc(char *path)
221 size_t retsize, retdata;
223 if(!strcmp(path, "files.xml") || !strcmp(path, "files.xml.bz2") || !strcmp(path, "MyList.DcLst"))
224 return(sstrdup(path));
226 retsize = retdata = 0;
233 addtobuf(ret, *path);
239 static int isdchash(struct hash *hash)
241 if(wcscmp(hash->algo, L"TTH"))
248 static int supports(struct dcpeer *peer, char *cap)
252 if(peer->supports == NULL)
254 for(p = peer->supports; *p != NULL; p++)
256 if(!strcasecmp(*p, cap))
262 static void endcompress(struct dcpeer *peer)
264 if(peer->compress == CPRS_ZLIB)
266 deflateEnd(peer->cprsdata);
267 free(peer->cprsdata);
269 peer->compress = CPRS_NONE;
272 static void initcompress(struct dcpeer *peer, int algo)
277 peer->compress = algo;
278 if(algo == CPRS_ZLIB)
280 peer->cprsdata = smalloc(sizeof(z_stream));
281 memset(peer->cprsdata, 0, sizeof(z_stream));
282 if((ret = deflateInit(peer->cprsdata, 3)) != Z_OK)
284 flog(LOG_CRIT, "Aiya! zlib refuses to init (%i)!", ret);
290 static void unquote(wchar_t *in)
294 for(p = in; *p != L'\0'; p++)
298 for(p2 = p + 1; (*p2 != L'\0') && (*p2 != L';') && (*p2 != L'&'); p2++);
305 if(!wcscmp(p + 1, L"amp"))
308 } else if(p[1] == L'#') {
309 nc = ucptowc(wcstol(p + 2, NULL, 10));
318 memmove(p + 1, p2 + 1, (wcslen(p2 + 1) + 1) * sizeof(wchar_t));
323 static void freeexppeer(struct dcexppeer *ep)
326 ep->next->prev = ep->prev;
328 ep->prev->next = ep->next;
333 if(ep->expire != NULL)
334 canceltimer(ep->expire);
338 static void exppeerexpire(int cancelled, struct dcexppeer *ep)
345 static struct dcexppeer *expectpeer(char *nick, struct fnetnode *fn)
347 struct dcexppeer *ep;
349 ep = smalloc(sizeof(*ep));
350 ep->nick = sstrdup(nick);
351 getfnetnode(ep->fn = fn);
352 ep->expire = timercallback(ntime() + 300, (void (*)(int, void *))exppeerexpire, ep);
361 static struct qcommand *newqcmd(struct qcommand **queue, char *string)
363 struct qcommand *new;
365 while(*queue != NULL)
366 queue = &(*queue)->next;
367 new = smalloc(sizeof(*new));
368 new->string = sstrdup(string);
374 static struct qcommand *ulqcmd(struct qcommand **queue)
376 struct qcommand *qcmd;
378 if((qcmd = *queue) == NULL)
384 static void freeqcmd(struct qcommand *qcmd)
390 static void hubrecvchat(struct socket *sk, struct fnetnode *fn, char *from, char *string)
392 wchar_t *chat, *wfrom, *wpeer;
394 struct fnetpeer *peer;
398 end = string + strlen(string);
399 while((p = strchr(string, 13)) != NULL)
400 memmove(p, p + 1, (end-- - p));
403 if((strlen(string) > strlen(from) + 2) && (*string == '<') && !memcmp(string + 1, from, strlen(from)) && (*(string + strlen(from) + 1) == '>'))
404 string += strlen(from) + 2;
405 if((wfrom = icmbstowcs(from, hub->charset)) == NULL)
407 wpeer = swcsdup(wfrom);
413 for(p = string + 1; *p; p++)
415 if((*p == ' ') || (*p == '>'))
423 if((wpeer = icmbstowcs(string + 1, hub->charset)) == NULL)
429 wpeer = swcsdup(L"");
431 if((chat = icmbstowcs(string, hub->charset)) == NULL)
441 if((peer = fnetfindpeer(fn, wfrom)) == NULL) /* Assume public chat */
442 fnethandlechat(fn, 1, wfrom, wpeer, chat);
444 fnethandlechat(fn, 0, wfrom, wpeer, chat);
446 fnethandlechat(fn, 1, L"", wpeer, chat);
454 static void peertimeout(int cancelled, struct dcpeer *peer)
456 peer->timeout = NULL;
462 static void sendadc(struct socket *sk, char *arg)
465 size_t bufsize, bufdata;
468 bufsize = bufdata = 0;
474 bufcat(buf, "\\s", 2);
475 } else if(*arg == '\n') {
476 bufcat(buf, "\\n", 2);
477 } else if(*arg == '\\') {
478 bufcat(buf, "\\\\", 2);
483 sockqueue(sk, buf, bufdata);
487 static void sendadcf(struct socket *sk, char *arg, ...)
493 buf = vsprintf2(arg, args);
501 static char **parseadc(char *args)
504 size_t retbufsize, retbufdata;
506 size_t bufsize, bufdata;
511 retbufsize = retbufdata = bufsize = bufdata = 0;
520 else if(*args != ' ')
524 if((*args == ' ') || (*args == 0))
527 addtobuf(retbuf, buf);
529 bufsize = bufdata = 0;
532 } else if(*args == '\\') {
535 addtobuf(buf, *args);
544 addtobuf(retbuf, NULL);
547 } else if((*args == 's') || (*args == ' ')) {
549 } else if(*args == 'n') {
551 } else if(*args == '\\') {
561 addtobuf(retbuf, NULL);
565 /* Macros useful in command handlers */
566 #define skipspace(s) ({if(((s) = strchr((s), ' ')) == NULL) return; else (s)++;})
567 #define qstr(sk, str) sockqueue(sk, str, strlen(str))
568 #define qstrf(sk, strandargs...) \
571 if((__buf__ = sprintf2(strandargs)) != NULL) { \
572 sockqueue(sk, __buf__, strlen(__buf__)); \
577 static char *tr(char *str, char *trans)
581 for(; *trans; trans += 2)
583 for(p = strchr(str, trans[0]); p != NULL; p = strchr(p, trans[0]))
589 static char *getadcid(struct dcpeer *peer)
596 if(!wcscmp(peer->transfer->path, L"files.xml") || !wcscmp(peer->transfer->path, L"files.xml.bz2") || !wcscmp(peer->transfer->path, L"MyList.DcLst"))
598 if(!isfilelist && (peer->transfer->hash != NULL) && isdchash(peer->transfer->hash) && supports(peer, "tthf"))
600 buf = base32encode(peer->transfer->hash->buf, 24);
601 ret = sprintf2("TTH/%.39s", buf);
604 if((buf = icwcstombs(peer->transfer->path, "UTF-8")) == NULL)
606 ret = pathnmdc2adc(buf);
613 static int trresumecb(struct transfer *transfer, wchar_t *cmd, wchar_t *arg, struct dcpeer *peer)
615 if(!wcscmp(cmd, L"resume"))
619 flog(LOG_WARNING, "filter returned no position for \"resume\" on transfer %i", transfer->id);
622 transfer->curpos = wcstol(arg, NULL, 10);
631 static void sendmynick(struct dcpeer *peer)
637 qstrf(peer->sk, "$MyNick %s|", icswcstombs(confgetstr("cli", "defnick"), peer->charset, "DoldaConnectUser-IN"));
639 qstrf(peer->sk, "$MyNick %s|", icswcstombs(fn->mynick, peer->charset, "DoldaConnectUser-IN"));
642 static void sendpeerlock(struct dcpeer *peer)
645 qstrf(peer->sk, "$Lock EXTENDEDPROTOCOLABCABCABCABCABCABC Pk=DCPLUSPLUS0.674ABCABC|");
647 qstrf(peer->sk, "$Lock EXTENDEDPROTOCOLABCABCABCABCABCABC Pk=DOLDA%sABCABCABC|", VERSION);
650 static void sendsupports(struct dcpeer *peer)
653 qstr(peer->sk, "$Supports MiniSlots XmlBZList ADCGet TTHL TTHF GetZBlock ZLIG |");
655 qstr(peer->sk, "$Supports MiniSlots XmlBZList ADCGet TTHL TTHF GetZBlock ZLIG|");
658 static void requestfile(struct dcpeer *peer)
662 if(peer->transfer->size == -1)
664 /* Use DCCHARSET for $Get paths until further researched... */
665 if((buf = icswcstombs(peer->transfer->path, DCCHARSET, NULL)) == NULL)
667 transferseterror(peer->transfer, TRNSE_NOTFOUND);
671 /* The transfer will be restarted later from
672 * cmd_filelength when it detects that the sizes
674 qstrf(peer->sk, "$Get %s$1|", buf);
677 if((peer->transfer->hash == NULL) && !peer->notthl)
679 if(supports(peer, "adcget") && supports(peer, "tthl"))
681 qstr(peer->sk, "$ADCGET");
682 sendadc(peer->sk, "tthl");
683 if((buf = getadcid(peer)) == NULL)
685 transferseterror(peer->transfer, TRNSE_NOTFOUND);
689 sendadc(peer->sk, buf);
691 sendadc(peer->sk, "0");
692 sendadc(peer->sk, "-1");
694 peer->fetchingtthl = 1;
700 if(forkfilter(peer->transfer))
702 flog(LOG_WARNING, "could not fork filter for transfer %i: %s", peer->transfer->id, strerror(errno));
706 CBREG(peer->transfer, trans_filterout, (int (*)(struct transfer *, wchar_t *, wchar_t *, void *))trresumecb, NULL, peer);
709 if(supports(peer, "adcget"))
711 qstr(peer->sk, "$ADCGET");
712 sendadc(peer->sk, "file");
713 if((buf = getadcid(peer)) == NULL)
715 transferseterror(peer->transfer, TRNSE_NOTFOUND);
719 sendadc(peer->sk, buf);
721 sendadcf(peer->sk, "%i", peer->transfer->curpos);
722 sendadcf(peer->sk, "%i", peer->transfer->size - peer->transfer->curpos);
724 } else if(supports(peer, "xmlbzlist")) {
725 if((buf = icswcstombs(peer->transfer->path, "UTF-8", NULL)) == NULL)
727 transferseterror(peer->transfer, TRNSE_NOTFOUND);
731 qstrf(peer->sk, "$UGetBlock %i %i %s|", peer->transfer->curpos, peer->transfer->size - peer->transfer->curpos, buf);
733 /* Use DCCHARSET for $Get paths until further researched... */
734 if((buf = icswcstombs(peer->transfer->path, DCCHARSET, NULL)) == NULL)
736 transferseterror(peer->transfer, TRNSE_NOTFOUND);
740 qstrf(peer->sk, "$Get %s$%i|", buf, peer->transfer->curpos + 1);
744 static void sendmyinfo(struct socket *sk, struct fnetnode *fn)
748 struct fnetnode *cfn;
752 qstrf(sk, "$MyINFO $ALL %s ", hub->nativenick);
753 buf = tr(icswcstombs(confgetstr("dc", "desc"), hub->charset, "Charset_conv_failure"), "$_|_");
754 qstrf(sk, "%s", buf);
756 for(cfn = fnetnodes; cfn != NULL; cfn = cfn->next)
758 if((cfn->state == FNN_EST) || (cfn->state == FNN_HS))
760 if(cfn->regstatus == FNNS_OP)
762 else if(cfn->regstatus == FNNS_REG)
768 qstrf(sk, "<%s V:%s,M:%c,H:%i/%i/%i,S:%i>",
769 (hub->dcppemu)?"++":"Dolda",
770 (hub->dcppemu)?"0.674":VERSION,
771 (tcpsock == NULL)?'P':'A',
773 confgetint("transfer", "slots")
776 buf = tr(icswcstombs(confgetstr("dc", "speedstring"), hub->charset, "Charset_conv_failure"), "$_|_");
777 qstrf(sk, "%s\x01$", buf);
778 buf = tr(icswcstombs(confgetstr("dc", "email"), hub->charset, "Charset_conv_failure"), "$_|_");
779 qstrf(sk, "%s$", buf);
780 qstrf(sk, "%llu$|", sharesize);
783 static void hubhandleaction(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
788 if(!strcmp(cmd, "$Lock"))
790 qstrf(sk, "$ValidateNick %s|", hub->nativenick);
791 } else if(!strcmp(cmd, "$Hello")) {
792 if(fn->state == FNN_HS)
794 qstrf(sk, "$Version 1,0091|");
795 qstrf(sk, "$GetNickList|");
797 fnetsetstate(fn, FNN_EST);
799 qstrf(sk, "$GetINFO %s %s|", args, hub->nativenick);
804 static void cmd_lock(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
811 if(!strncmp(args, "EXTENDEDPROTOCOL", 16))
813 if((p = strchr(args, ' ')) != NULL)
818 qstrf(sk, "$Supports UserCommand NoGetINFO NoHello UserIP2 TTHSearch GetZBlock |");
820 qstrf(sk, "$Supports UserCommand NoGetINFO NoHello UserIP2 TTHSearch GetZBlock|");
822 key = dcmakekey(args);
823 qstrf(sk, "$Key %s|", key);
825 hubhandleaction(sk, fn, cmd, args);
828 static void cmd_hubname(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
834 if(hub->nativename == NULL)
835 free(hub->nativename);
836 hub->nativename = sstrdup(args);
837 buf = icmbstowcs(args, hub->charset);
838 fnetsetname(fn, (buf == NULL)?L"Hubname conv error":buf);
841 hubhandleaction(sk, fn, cmd, args);
844 static void cmd_hello(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
850 if((nick = icmbstowcs(args, hub->charset)) == NULL)
852 if(strcmp(args, hub->nativenick) && (fnetfindpeer(fn, nick) == NULL))
853 fnetaddpeer(fn, nick, nick);
855 hubhandleaction(sk, fn, cmd, args);
858 static void cmd_quit(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
861 struct fnetpeer *peer;
865 if((nick = icmbstowcs(args, hub->charset)) == NULL)
867 if((peer = fnetfindpeer(fn, nick)) != NULL)
870 hubhandleaction(sk, fn, cmd, args);
873 static void cmd_nicklist(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
878 struct fnetpeer *peer, *npeer;
881 for(peer = fn->peers; peer != NULL; peer = peer->next)
882 peer->flags.b.delete = 1;
883 while((p = strstr(args, "$$")) != NULL)
886 if((buf = icmbstowcs(args, hub->charset)) != NULL)
888 if((peer = fnetfindpeer(fn, buf)) == NULL)
889 peer = fnetaddpeer(fn, buf, buf);
891 peer->flags.b.delete = 0;
893 qstrf(sk, "$GetINFO %s %s|", args, hub->nativenick);
897 for(peer = fn->peers; peer != NULL; peer = npeer)
900 if(peer->flags.b.delete)
903 hubhandleaction(sk, fn, cmd, args);
906 static void cmd_oplist(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
911 struct fnetpeer *peer;
914 for(peer = fn->peers; peer != NULL; peer = peer->next)
915 peer->flags.b.op = 0;
916 while((p = strstr(args, "$$")) != NULL)
919 if((buf = icmbstowcs(args, hub->charset)) != NULL)
921 if((peer = fnetfindpeer(fn, buf)) != NULL)
922 peer->flags.b.op = 1;
927 hubhandleaction(sk, fn, cmd, args);
930 static void cmd_myinfo(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
933 wchar_t *buf, *wp, *wp2;
935 struct fnetpeer *peer;
940 if(strncmp(p, "$ALL ", 5))
943 if((p2 = strchr(p, ' ')) == NULL)
946 if((buf = icmbstowcs(p, hub->charset)) == NULL)
948 if((peer = fnetfindpeer(fn, buf)) == NULL)
949 peer = fnetaddpeer(fn, buf, buf);
952 if((p2 = strstr(p, "$ $")) == NULL)
955 if((buf = icmbstowcs(p, hub->charset)) == NULL)
957 if((wcslen(buf) > 0) && (buf[wcslen(buf) - 1] == L'>') && ((wp = wcsrchr(buf, L'<')) != NULL))
959 buf[wcslen(buf) - 1] = L'\0';
961 if((wp2 = wcschr(wp, L' ')) != NULL)
964 fnetpeersetstr(peer, L"dc-client", wp);
968 if((wp2 = wcschr(wp, L',')) != NULL)
972 swprintf(abuf, 10, L"dc-tag-%lc", wp[0]);
973 fnetpeersetstr(peer, abuf, wp + 2);
975 } while(wp2 != NULL);
978 fnetpeersetstr(peer, L"descr", buf);
981 if((p2 = strchr(p, '$')) == NULL)
984 if((buf = icmbstowcs(p, hub->charset)) == NULL)
986 fnetpeersetstr(peer, L"dc-speed", buf);
989 if((p2 = strchr(p, '$')) == NULL)
992 if((buf = icmbstowcs(p, hub->charset)) == NULL)
994 fnetpeersetstr(peer, L"email", buf);
999 fnetpeersetlnum(peer, L"share", strtoll(p, NULL, 10));
1000 hubhandleaction(sk, fn, cmd, args);
1003 /* I do not implement the fully in that I do not disconnect from the
1004 * old hub. I do this since I believe that if the hub owner really
1005 * wants to get rid of us, then it is his responsibility to disconnect
1007 static void cmd_forcemove(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1010 struct fnetnode *newfn;
1014 if(strchr(args, ':') == NULL)
1016 args = strcpy(smalloc(strlen(args) + 5), args);
1017 strcat(args, ":411");
1022 if((newfn = fnetinitconnect(L"dc", fn->owner, args, NULL)) != NULL)
1024 linkfnetnode(newfn);
1027 hubhandleaction(sk, fn, cmd, args);
1032 static char *getdcpath(struct sharecache *node, size_t *retlen, char *charset)
1037 if(node->parent == NULL)
1039 if(node->parent == shareroot)
1041 if((buf = icwcstombs(node->name, charset)) == NULL)
1044 *retlen = strlen(buf);
1047 if((buf2 = icwcstombs(node->name, charset)) == NULL)
1049 if((buf = getdcpath(node->parent, &len, charset)) == NULL)
1054 len2 = strlen(buf2);
1055 buf = srealloc(buf, len + 1 + len2 + 1);
1057 strcpy(buf + len, buf2);
1058 buf[len + len2] = 0;
1061 *retlen = len + len2;
1067 * This is the main share searching function for Direct Connect
1068 * peers. Feel free to optimize it if you feel the need for it. I
1069 * haven't ever seen it take any noticable CPU time anyway, so I
1070 * haven't felt that need.
1072 * It may feel dubious to just return the directory when all terms are
1073 * satisfied rather than all the files in it, but it really benefits
1074 * everyone: Less cycles used for us, less UDP squelching for active
1075 * searchers, and less bandwidth waste for hubs when serving passive
1078 static void cmd_search(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1083 char *prefix, *infix, *postfix, *buf, *buf2;
1085 struct sockaddr_in addr;
1086 struct sharecache *node;
1087 int minsize, maxsize;
1090 int termnum, satisfied, skipcheck;
1091 int level, tersat[32];
1096 if((p = strchr(args, ' ')) == NULL)
1100 memset(terms, 0, sizeof(terms));
1101 prefix = infix = postfix = NULL;
1105 if(!strncmp(args, "Hub:", 4))
1107 if(!strcmp(cmd, "$MultiSearch"))
1109 if(!strcmp(args + 4, hub->nativenick))
1111 prefix = sprintf2("$SR %s ", hub->nativenick);
1112 infix = sprintf2(" %i/%i\005", slotsleft(), confgetint("transfer", "slots"));
1113 postfix = sprintf2(" (%s)\005%s|", formataddress(fn->sk->remote, fn->sk->remotelen), args + 4);
1117 if((p2 = strchr(args, ':')) == NULL)
1120 addr.sin_family = AF_INET;
1121 if(!inet_aton(args, &addr.sin_addr))
1123 addr.sin_port = htons(atoi(p2));
1124 prefix = sprintf2("$SR %s ", hub->nativenick);
1125 infix = sprintf2(" %i/%i\005", slotsleft(), confgetint("transfer", "slots"));
1126 postfix = sprintf2(" (%s)|", formataddress(fn->sk->remote, fn->sk->remotelen));
1127 netdgramconn(dsk = netdupsock(udpsock), (struct sockaddr *)&addr, sizeof(addr));
1130 minsize = maxsize = -1;
1139 if((*(p++) == 'T') && (minsize == 0))
1146 if((p2 = strchr(p, '?')) == NULL)
1161 if((*p2 == 0) || (*p2 == '$'))
1169 if(!dotth && !strncmp(p, "TTH:", 4))
1172 if(((buf = base32decode(p + 4, &buflen)) == NULL) || (buflen != 24))
1177 memcpy(hashtth, buf, 24);
1180 if((terms[termnum] = icmbstowcs(p, hub->charset)) != NULL)
1191 node = shareroot->child;
1193 for(i = 0; i < termnum; i++)
1199 if(node->f.b.type == FILE_REG)
1201 if((minsize >= 0) && (node->size < minsize))
1203 if((maxsize >= 0) && (node->size > maxsize))
1206 if(!skipcheck && dotth)
1208 if((node->f.b.type != FILE_REG) || (node->f.b.hastth && memcmp(hashtth, node->hashtth, 24)))
1213 for(i = 0; i < termnum; i++)
1217 if(wcsexists(node->name, terms[i]))
1221 } else if(node->child == NULL) {
1226 if(!skipcheck && (satisfied == termnum))
1228 /* Use DCCHARSET in $Get paths until further researched... */
1229 if((buf = getdcpath(node, NULL, DCCHARSET)) != NULL)
1231 if(node->f.b.hastth)
1233 buf2 = base32encode(node->hashtth, 24);
1234 qstrf(dsk, "%s%s\005%i%sTTH:%.39s%s", prefix, buf, node->size, infix, buf2, postfix);
1237 qstrf(dsk, "%s%s\005%i%s%s%s", prefix, buf, node->size, infix, hub->nativename, postfix);
1242 if((!skipcheck && (satisfied == termnum)) || (node->child == NULL))
1244 while(node->next == NULL)
1246 if((node = node->parent) == shareroot)
1250 if(node == shareroot)
1252 for(i = 0; i < termnum; i++)
1254 if(tersat[i] >= level)
1267 hubhandleaction(sk, fn, cmd, args);
1278 for(i = 0; (i < 32) && (terms[i] != NULL); i++)
1282 static void cmd_connecttome(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1286 struct socket *newsk;
1287 struct sockaddr_in addr;
1290 if((p = strchr(args, ' ')) == NULL)
1293 if(strcmp(args, hub->nativenick))
1295 addr.sin_family = AF_INET;
1297 if((p = strchr(args, ':')) == NULL)
1300 addr.sin_port = htons(atoi(p));
1301 if(!inet_aton(args, &addr.sin_addr))
1303 newsk = netcsconn((struct sockaddr *)&addr, sizeof(addr), (void (*)(struct socket *, int, void *))peerconnect, fn);
1305 hubhandleaction(sk, fn, cmd, args);
1308 static void sendctm(struct socket *sk, char *nick)
1310 struct sockaddr *addr;
1315 if(sockgetremotename2(tcpsock, sk, &addr, &addrlen) < 0)
1317 if(addr->sa_family == AF_INET)
1318 qstrf(sk, "$ConnectToMe %s %s|", nick, formataddress(addr, addrlen));
1320 flog(LOG_WARNING, "Direct Connect TCP socket is suddenly not AF_INET, but %i", addr->sa_family);
1324 static void cmd_revconnecttome(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1330 if((p = strchr(args, ' ')) == NULL)
1333 if(strcmp(p, hub->nativenick))
1336 expectpeer(args, fn);
1337 hubhandleaction(sk, fn, cmd, args);
1340 static void cmd_getnetinfo(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1343 struct fnetnode *node;
1348 for(node = fnetnodes; node != NULL; node = node->next)
1350 if(node->state == FNN_EST)
1353 qstrf(sk, "$NetInfo %i$%i$%c$0|", confgetint("transfer", "slots"), numhubs, (tcpsock == NULL)?'P':'A');
1354 hubhandleaction(sk, fn, cmd, args);
1357 static void cmd_to(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1364 if((p2 = strchr(p, ' ')) == NULL)
1368 if((p2 = strchr(p, ' ')) == NULL)
1371 if(strcmp(p, "From:"))
1374 if((p2 = strstr(p, " $")) == NULL)
1378 hubrecvchat(fn->sk, fn, p, p2);
1379 hubhandleaction(sk, fn, cmd, args);
1382 static void cmd_sr(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1386 char *nick, *filename, *hubname;
1390 wchar_t *wnick, *wfile;
1394 if((p2 = strchr(p, ' ')) == NULL)
1399 if((p2 = strchr(p, 5)) == NULL)
1403 if((p2 = strchr(p, ' ')) == NULL)
1408 if((p2 = strchr(p, '/')) == NULL)
1413 if((p2 = strchr(p, 5)) == NULL)
1417 if((p2 = strstr(p, " (")) == NULL)
1420 if((wnick = icmbstowcs(nick, hub->charset)) == NULL)
1422 /* Use DCCHARSET in $Get paths until further researched... */
1423 if((wfile = icmbstowcs(filename, DCCHARSET)) == NULL)
1428 sr = newsrchres(&dcnet, wfile, wnick);
1429 if(sr->peernick != NULL)
1431 sr->peernick = swcsdup(wnick);
1436 if(!strncmp(hubname, "TTH:", 4))
1438 if((buf = base32decode(hubname + 4, &buflen)) != NULL)
1441 sr->hash = newhash(L"TTH", 24, buf);
1445 getfnetnode(sr->fn = fn);
1448 hubhandleaction(sk, fn, cmd, args);
1451 static void cmd_usercommand(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1453 /* Do nothing for now. */
1456 static void cmd_getpass(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1463 pw = wpfind(fn->args, L"password");
1464 if((pw == NULL) || ((mbspw = icwcstombs(pw, hub->charset)) == NULL))
1469 qstrf(sk, "$MyPass %s|", mbspw);
1471 fn->regstatus = FNNS_REG;
1472 hubhandleaction(sk, fn, cmd, args);
1475 static void cmd_logedin(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1480 fn->regstatus = FNNS_OP;
1481 hubhandleaction(sk, fn, cmd, args);
1484 static void cmd_mynick(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1486 struct dcexppeer *expect;
1489 if(peer->nativename != NULL)
1490 free(peer->nativename);
1491 peer->nativename = sstrdup(args);
1492 if(peer->wcsname != NULL)
1493 free(peer->wcsname);
1494 if((peer->wcsname = icmbstowcs(peer->nativename, peer->charset)) == NULL)
1501 for(expect = expected; expect != NULL; expect = expect->next)
1503 if(!strcmp(expect->nick, args))
1510 hub = expect->fn->data;
1511 peer->fn = expect->fn;
1512 getfnetnode(peer->fn);
1513 peer->dcppemu = hub->dcppemu;
1514 freeexppeer(expect);
1519 static void cmd_direction(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1523 struct transfer *transfer;
1525 if((p = strchr(args, ' ')) == NULL)
1528 if(!strcmp(args, "Upload"))
1530 if(!strcmp(args, "Download"))
1534 if((peer->transfer == NULL) || (mydir != peer->direction))
1539 if(peer->direction == TRNSD_DOWN)
1542 if(peer->wcsname == NULL)
1547 peer->direction = mydir;
1548 if(peer->direction == TRNSD_UP)
1550 if(confgetint("transfer", "ulquota") && hasupload(&dcnet, peer->wcsname))
1555 transfer = newupload(peer->fn, &dcnet, peer->wcsname, &dctransfer, peer);
1557 if((transfer = finddownload(peer->wcsname)) == NULL)
1562 transferattach(transfer, &dctransfer, peer);
1563 transfersetstate(transfer, TRNS_HS);
1565 transfersetnick(transfer, peer->wcsname);
1566 peer->transfer = transfer;
1569 qstrf(sk, "$Direction %s %i|", (peer->direction == TRNSD_UP)?"Upload":"Download", rand() % 10000);
1570 if(peer->key != NULL)
1571 qstrf(sk, "$Key %s|", peer->key);
1572 if(peer->direction == TRNSD_DOWN)
1577 static void cmd_peerlock(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1580 struct transfer *transfer;
1582 if((p = strchr(args, ' ')) == NULL)
1585 if(!strncmp(args, "EXTENDEDPROTOCOL", 16))
1587 key = dcmakekey(args);
1590 if(peer->wcsname == NULL)
1599 if((transfer = finddownload(peer->wcsname)) == NULL)
1601 if(confgetint("transfer", "ulquota") && hasupload(&dcnet, peer->wcsname))
1606 peer->direction = TRNSD_UP;
1607 transfer = newupload(peer->fn, &dcnet, peer->wcsname, &dctransfer, peer);
1609 peer->direction = TRNSD_DOWN;
1610 transferattach(transfer, &dctransfer, peer);
1611 transfersetstate(transfer, TRNS_HS);
1613 transfersetnick(transfer, peer->wcsname);
1614 peer->transfer = transfer;
1615 qstrf(sk, "$Direction %s %i|", (peer->direction == TRNSD_UP)?"Upload":"Download", rand() % 10000);
1616 qstrf(sk, "$Key %s|", key);
1619 if(peer->key != NULL)
1625 static void cmd_key(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1630 static void startdl(struct dcpeer *peer)
1632 if(peer->timeout != NULL)
1633 canceltimer(peer->timeout);
1634 peer->state = PEER_TRNS;
1635 transferstartdl(peer->transfer, peer->sk);
1636 peer->sk->readcb = (void (*)(struct socket *, void *))transread;
1637 peer->sk->errcb = (void (*)(struct socket *, int, void *))transerr;
1640 static void startul(struct dcpeer *peer)
1642 if(peer->timeout != NULL)
1643 canceltimer(peer->timeout);
1644 peer->state = PEER_TRNS;
1645 transferstartul(peer->transfer, peer->sk);
1646 peer->sk->writecb = (void (*)(struct socket *, void *))transwrite;
1649 static void cmd_filelength(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1652 struct transfer *transfer;
1654 if(peer->transfer == NULL)
1660 if(peer->transfer->size != size)
1662 transfersetsize(peer->transfer, size);
1663 transfer = peer->transfer;
1665 trytransferbypeer(transfer->fnet, transfer->peerid);
1669 qstr(peer->sk, "$Send|");
1672 static void cmd_error(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1674 if(peer->fetchingtthl)
1676 peer->fetchingtthl = 0;
1681 if((peer->transfer != NULL) && (peer->transfer->dir == TRNSD_DOWN))
1683 transferseterror(peer->transfer, TRNSE_NOTFOUND);
1684 resettransfer(peer->transfer);
1690 static void cmd_maxedout(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1692 if((peer->transfer != NULL) && (peer->transfer->dir == TRNSD_DOWN))
1694 transferseterror(peer->transfer, TRNSE_NOSLOTS);
1695 resettransfer(peer->transfer);
1708 {"MyList.DcLst", &hmlistname, updatehmlist},
1709 {"files.xml", &xmllistname, updatexmllist},
1710 {"files.xml.bz2", &xmlbz2listname, updatexmlbz2list},
1714 static int openfilelist(char *name)
1719 for(i = 0; lists[i].name != NULL; i++)
1721 if(!strcmp(name, lists[i].name))
1725 if(lists[i].name == NULL)
1728 if((*lists[i].file == NULL) || ((fd = open(*lists[i].file, O_RDONLY)) < 0))
1730 if((fd < 0) && ((*lists[i].file == NULL) || ((fd = open(*lists[i].file, O_RDONLY)) < 0)))
1733 flog(LOG_ERR, "could not open filelist tempfile: %s", strerror(errno));
1740 static struct sharecache *findbytth(char *tth32)
1744 struct sharecache *node;
1746 if((buf = base32decode(tth32, &buflen)) == NULL)
1753 for(node = shareroot->child; node != NULL; node = nextscnode(node))
1755 if(node->f.b.hastth && !memcmp(node->hashtth, buf, 24))
1762 static struct sharecache *resdcpath(char *path, char *charset, char sep)
1764 struct sharecache *node;
1771 if((p2 = strchr(p, sep)) != NULL)
1773 if((node = findcache(node, icsmbstowcs(p, charset, L""))) == NULL)
1780 static void cmd_get(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1785 struct sharecache *node;
1786 struct socket *lesk;
1790 if(peer->transfer == NULL)
1795 if((p = strchr(args, '$')) == NULL)
1801 if((offset = (atoi(p) - 1)) < 0)
1806 if(((fd = openfilelist(args)) < 0) && (errno != 0))
1808 qstr(sk, "$Error Could not send file list|");
1811 } else if(fd >= 0) {
1812 if((buf2 = icsmbstowcs(args, DCCHARSET, NULL)) != NULL)
1813 transfersetpath(peer->transfer, buf2);
1814 peer->transfer->flags.b.minislot = 1;
1818 /* Use DCCHARSET in $Get paths until further researched... */
1819 if((node = resdcpath(args, DCCHARSET, '\\')) == NULL)
1821 qstrf(sk, "$Error File not in share|");
1825 if((fd = opensharecache(node)) < 0)
1827 qstrf(sk, "$Error %s|", strerror(errno));
1831 buf = getfspath(node);
1832 if((buf2 = icsmbstowcs(buf, NULL, NULL)) == NULL)
1833 flog(LOG_WARNING, "could not convert native path into a wcs (%s): %s", buf, strerror(errno));
1835 transfersetpath(peer->transfer, buf2);
1838 if(fstat(fd, &sb) < 0)
1841 flog(LOG_WARNING, "could not stat file %ls: %s", node->name, strerror(errno));
1842 qstrf(sk, "$Error|");
1846 if(sb.st_size < 65536)
1847 peer->transfer->flags.b.minislot = 1;
1848 if(!peer->transfer->flags.b.minislot && (slotsleft() < 1)) {
1850 qstr(sk, "$MaxedOut|");
1854 if((offset != 0) && (lseek(fd, offset, SEEK_SET) < 0))
1857 qstrf(sk, "$Error Offset out of range|");
1861 lesk = wrapsock(fd);
1862 transferprepul(peer->transfer, sb.st_size, offset, -1, lesk);
1864 qstrf(sk, "$FileLength %i|", peer->transfer->size);
1867 static void cmd_send(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1869 if(peer->transfer == NULL)
1874 if(peer->transfer->localend == NULL)
1883 static void cmd_supports(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1888 size_t arrsize, arrdata;
1890 if(peer->supports != NULL)
1892 for(i = 0; peer->supports[i] != NULL; i++)
1893 free(peer->supports[i]);
1894 free(peer->supports);
1897 arrsize = arrdata = 0;
1901 if((p2 = strchr(p, ' ')) != NULL)
1905 addtobuf(arr, sstrdup(p));
1906 } while((p = p2) != NULL);
1907 addtobuf(arr, NULL);
1908 peer->supports = arr;
1911 static void cmd_getblock(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1915 int start, numbytes;
1916 char *charset, *buf;
1918 struct sharecache *node;
1920 struct socket *lesk;
1922 if(peer->transfer == NULL)
1928 if((p2 = strchr(p, ' ')) == NULL)
1936 if((p2 = strchr(p, ' ')) == NULL)
1944 if(!strcmp(cmd, "$UGetBlock") || !strcmp(cmd, "$UGetZBlock"))
1947 /* Use DCCHARSET in $Get paths until further researched... */
1948 charset = DCCHARSET;
1949 if(!strcmp(cmd, "$GetZBlock") || !strcmp(cmd, "$UGetZBlock"))
1950 initcompress(peer, CPRS_ZLIB);
1951 if(((fd = openfilelist(p)) < 0) && (errno != 0))
1953 qstr(sk, "$Error Could not send file list|");
1955 } else if(fd >= 0) {
1956 if((buf2 = icsmbstowcs(args, charset, NULL)) != NULL)
1957 transfersetpath(peer->transfer, buf2);
1958 peer->transfer->flags.b.minislot = 1;
1962 if((node = resdcpath(p, charset, '\\')) == NULL)
1964 qstr(sk, "$Error File not in cache|");
1967 if((fd = opensharecache(node)) < 0)
1969 qstrf(sk, "$Error %s|", strerror(errno));
1972 buf = getfspath(node);
1973 if((buf2 = icsmbstowcs(buf, NULL, NULL)) == NULL)
1974 flog(LOG_WARNING, "could not convert native path into a wcs (%s): %s", buf, strerror(errno));
1976 transfersetpath(peer->transfer, buf2);
1979 if(fstat(fd, &sb) < 0)
1982 flog(LOG_WARNING, "could not stat file %ls: %s", node->name, strerror(errno));
1983 qstr(sk, "$Error|");
1986 if(sb.st_size < 65536)
1987 peer->transfer->flags.b.minislot = 1;
1988 if(!peer->transfer->flags.b.minislot && (slotsleft() < 1)) {
1990 qstr(sk, "$MaxedOut|");
1993 if((start != 0) && ((start >= sb.st_size) || (lseek(fd, start, SEEK_SET) < 0)))
1996 qstr(sk, "$Error Offset out of range|");
1999 if((numbytes < 0) || (start + numbytes > sb.st_size))
2000 numbytes = sb.st_size - start;
2001 lesk = wrapsock(fd);
2002 transferprepul(peer->transfer, sb.st_size, start, start + numbytes, lesk);
2004 qstrf(sk, "$Sending %i|", numbytes);
2008 static void cmd_adcget(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2012 int start, numbytes;
2013 struct sharecache *node;
2015 struct socket *lesk;
2019 if(peer->transfer == NULL)
2024 if((argv = parseadc(args)) == NULL)
2029 if(parrlen(argv) < 4)
2034 start = atoi(argv[2]);
2035 numbytes = atoi(argv[3]);
2038 if(((fd = openfilelist(argv[1])) < 0) && (errno != 0))
2040 qstr(sk, "$Error Could not send file list|");
2042 } else if(fd >= 0) {
2043 if((wbuf = icsmbstowcs(argv[1], "UTF-8", NULL)) != NULL)
2044 transfersetpath(peer->transfer, wbuf);
2045 peer->transfer->flags.b.minislot = 1;
2049 if(!strncmp(argv[1], "TTH/", 4))
2051 if((node = findbytth(argv[1] + 4)) == NULL)
2053 qstr(sk, "$Error File not in cache|");
2057 if((node = resdcpath((argv[1][0] == '/')?(argv[1] + 1):(argv[1]), "UTF-8", '/')) == NULL)
2059 qstr(sk, "$Error File not in cache|");
2063 if((fd = opensharecache(node)) < 0)
2065 qstrf(sk, "$Error %s|", strerror(errno));
2068 buf = getfspath(node);
2069 if((wbuf = icsmbstowcs(buf, NULL, NULL)) == NULL)
2070 flog(LOG_WARNING, "could not convert native path into a wcs (%s): %s", buf, strerror(errno));
2072 transfersetpath(peer->transfer, wbuf);
2075 if(!strcmp(argv[0], "file"))
2077 for(i = 4; argv[i] != NULL; i++)
2079 if(!strcmp(argv[i], "ZL1"))
2080 initcompress(peer, CPRS_ZLIB);
2082 if(fstat(fd, &sb) < 0)
2084 flog(LOG_WARNING, "could not stat file %ls: %s", node->name, strerror(errno));
2085 qstr(sk, "$Error|");
2088 if(sb.st_size < 65536)
2089 peer->transfer->flags.b.minislot = 1;
2090 if(!peer->transfer->flags.b.minislot && (slotsleft() < 1)) {
2091 qstr(sk, "$MaxedOut|");
2094 if((start != 0) && ((start >= sb.st_size) || (lseek(fd, start, SEEK_SET) < 0)))
2096 qstr(sk, "$Error Offset out of range|");
2099 if((numbytes < 0) || (start + numbytes > sb.st_size))
2100 numbytes = sb.st_size - start;
2101 lesk = wrapsock(fd);
2102 transferprepul(peer->transfer, sb.st_size, start, start + numbytes, lesk);
2105 qstr(sk, "$ADCSND");
2106 sendadc(sk, "file");
2107 sendadc(sk, argv[1]);
2108 sendadcf(sk, "%i", start);
2109 sendadcf(sk, "%i", numbytes);
2110 if(peer->compress == CPRS_ZLIB)
2114 } else if(!strcmp(argv[0], "tthl")) {
2116 * XXX: Implement full TTHL support.
2118 * In the meantime, this is better than nothing, since it at
2119 * least allows fetching of the TTH root if it isn't already
2124 qstr(sk, "$Error no TTHL data for virtual files|");
2127 qstr(sk, "$ADCSND");
2128 sendadc(sk, "tthl");
2129 sendadc(sk, argv[1]);
2133 sockqueue(sk, node->hashtth, 24);
2135 qstr(sk, "$Error Namespace not implemented|");
2145 static void handletthl(struct dcpeer *peer)
2149 while(peer->inbufdata >= 24)
2151 pushtigertree(&peer->tth, peer->inbuf);
2152 memmove(peer->inbuf, peer->inbuf + 24, peer->inbufdata -= 24);
2153 peer->curread += 24;
2155 if(peer->curread >= peer->totalsize)
2157 if(peer->timeout == NULL)
2158 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
2159 peer->state = PEER_CMD;
2160 synctigertree(&peer->tth);
2161 restigertree(&peer->tth, buf);
2162 transfersethash(peer->transfer, newhash(L"TTH", 24, buf));
2167 static void cmd_adcsnd(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2170 int start, numbytes;
2172 if(peer->transfer == NULL)
2177 if((argv = parseadc(args)) == NULL)
2182 if(parrlen(argv) < 4)
2187 start = atoi(argv[2]);
2188 numbytes = atoi(argv[3]);
2189 if(!strcmp(argv[0], "tthl"))
2191 if((start != 0) || (numbytes % 24 != 0))
2193 /* Weird. Bail out. */
2197 if(peer->timeout != NULL)
2198 canceltimer(peer->timeout);
2199 peer->state = PEER_TTHL;
2200 peer->totalsize = numbytes;
2202 peer->fetchingtthl = 0;
2203 inittigertree(&peer->tth);
2205 } else if(!strcmp(argv[0], "file")) {
2206 if(start != peer->transfer->curpos)
2211 if(start + numbytes != peer->transfer->size)
2213 transfersetsize(peer->transfer, start + numbytes);
2218 if(peer->inbufdata > 0)
2220 sockpushdata(sk, peer->inbuf, peer->inbufdata);
2221 peer->inbufdata = 0;
2222 transread(sk, peer);
2225 /* We certainly didn't request this...*/
2234 static void cmd_sending(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2238 if(peer->transfer == NULL)
2243 numbytes = atoi(args);
2244 if(peer->transfer->size - peer->transfer->curpos != numbytes)
2246 transfersetsize(peer->transfer, peer->transfer->curpos + numbytes);
2251 if(peer->inbufdata > 0)
2253 sockpushdata(sk, peer->inbuf, peer->inbufdata);
2254 peer->inbufdata = 0;
2255 transread(sk, peer);
2261 static void cmd_(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
2266 hubhandleaction(sk, fn, cmd, args);
2270 static void cmd_(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2276 static int hubreqconn(struct fnetpeer *peer)
2281 if((peer->fn->state != FNN_EST) || (peer->fn->fnet != &dcnet))
2286 if((hub = peer->fn->data) == NULL)
2291 if((mbsnick = icwcstombs(peer->id, hub->charset)) == NULL)
2292 return(1); /* Shouldn't happen, of course, but who knows... */
2295 sendctm(peer->fn->sk, mbsnick);
2296 expectpeer(mbsnick, peer->fn);
2298 qstrf(peer->fn->sk, "$RevConnectToMe %s %s|", hub->nativenick, mbsnick);
2304 static int hubsendchat(struct fnetnode *fn, int public, wchar_t *to, wchar_t *string)
2307 char *mbsstring, *mbsto;
2310 if((mbsto = icwcstombs(to, hub->charset)) == NULL)
2315 if((mbsstring = icwcstombs(string, hub->charset)) == NULL)
2320 if((strchr(mbsto, '|') != NULL) || (strchr(mbsto, ' ') != NULL))
2327 if(strchr(mbsstring, '|') != NULL)
2338 qstrf(fn->sk, "<%s> %s|", hub->nativenick, mbsstring);
2340 qstrf(fn->sk, "$To: %s From: %s $<%s> %s|", mbsto, hub->nativenick, hub->nativenick, mbsstring);
2343 qstrf(fn->sk, "$To: %s From: %s $<%s> %s|", mbsto, hub->nativenick, hub->nativenick, mbsstring);
2350 static void findsizelimit(struct sexpr *sexpr, int *min, int *max)
2352 int minl, maxl, minr, maxr, retmin, retmax;
2357 findsizelimit(sexpr->l, &minl, &maxl);
2358 findsizelimit(sexpr->r, &minr, &maxr);
2359 retmin = (minl > minr)?minl:minr;
2360 if((maxl != -1) && (maxr != -1))
2361 retmax = (maxl < maxr)?maxl:maxr;
2370 findsizelimit(sexpr->l, &minl, &maxl);
2371 findsizelimit(sexpr->r, &minr, &maxr);
2372 retmin = (minl < minr)?minl:minr;
2373 if((maxl == -1) || (maxr == -1))
2376 retmax = (maxl > maxr)?maxl:maxr;
2379 findsizelimit(sexpr->l, &minl, &maxl);
2380 if((minl == 0) && (maxl == -1)) /* Interval is unspecified */
2384 } else if((minl == 0) && (maxl != -1)) {
2387 } else if((minl != 0) && (maxl == -1)) {
2390 } else { /* This would yield two seperate intervals, which DC cannot handle */
2396 retmax = sexpr->d.n - 1;
2399 retmin = sexpr->d.n;
2400 retmax = sexpr->d.n;
2403 retmin = sexpr->d.n + 1;
2417 static struct hash *findsehash(struct sexpr *sexpr)
2419 struct hash *h1, *h2;
2424 if((h1 = findsehash(sexpr->l)) != NULL)
2426 if((h1 = findsehash(sexpr->r)) != NULL)
2430 if((h1 = findsehash(sexpr->l)) == NULL)
2432 if((h2 = findsehash(sexpr->r)) == NULL)
2438 if(!wcscmp(sexpr->d.hash->algo, L"TTH"))
2439 return(sexpr->d.hash);
2446 static int hubsearch(struct fnetnode *fn, struct search *srch, struct srchfnnlist *ln)
2449 struct wcslist *list, *cur;
2450 char *sstr, *buf, *p;
2451 size_t sstrsize, sstrdata;
2452 struct sockaddr *name;
2454 int minsize, maxsize;
2458 if((fn->state != FNN_EST) || (fn->sk == NULL) || (fn->sk->state != SOCK_EST))
2460 list = findsexprstrs(srch->sexpr);
2461 findsizelimit(srch->sexpr, &minsize, &maxsize);
2462 hash = findsehash(srch->sexpr);
2463 if((minsize != 0) && (maxsize != -1))
2465 /* Choose either minsize or maxsize by trying to determine
2466 * which choice will be most restrictive. The result can be
2467 * approximative at best anyway, so don't try too hard... */
2468 if((50000000 - maxsize) > (minsize - 50000000))
2474 sstrsize = sstrdata = 0;
2475 if((hash != NULL) && (hash->len == 24))
2477 /* Prioritize hash searches above all else */
2478 bufcat(sstr, "F?T?0?9?TTH:", 12);
2479 buf = base32encode(hash->buf, hash->len);
2481 bufcat(sstr, buf, 39);
2486 sizebuf2(sstr, sstrdata + 32, 1);
2487 sstrdata += snprintf(sstr + sstrdata, sstrsize - sstrdata, "T?F?%i?1?", minsize);
2488 } else if(maxsize != -1) {
2489 sizebuf2(sstr, sstrdata + 32, 1);
2490 sstrdata += snprintf(sstr + sstrdata, sstrsize - sstrdata, "T?T?%i?1?", maxsize);
2492 bufcat(sstr, "F?F?0?1?", 8);
2496 for(cur = list; cur != NULL; cur = cur->next)
2498 /* Use DCCHARSET in $Get paths until further researched... */
2499 if((buf = icwcstombs(cur->str, DCCHARSET)) == NULL)
2501 /* Can't find anything anyway if the search expression
2502 * requires characters outside DC's charset. There's
2503 * nothing technically wrong with the search itself,
2504 * however, so return success. This should be
2505 * considered as an optimization. */
2512 addtobuf(sstr, '$');
2514 * It probably doesn't hurt if buf contains any extra
2515 * dollar signs - it will just result in extra search
2516 * terms, and the extraneous results will be filtered by
2517 * the search layer anyway. It hurts if it contains any
2518 * pipes, though, so let's sell them for money.
2520 for(p = buf; *p; p++)
2525 bufcat(sstr, buf, strlen(buf));
2529 /* Will match all files... :-/ */
2530 addtobuf(sstr, '.');
2536 if(sockgetremotename2(udpsock, fn->sk, &name, &namelen) < 0)
2538 flog(LOG_WARNING, "cannot get address of UDP socket");
2540 qstrf(fn->sk, "$Search %s %s|", formataddress(name, namelen), sstr);
2544 qstrf(fn->sk, "$Search Hub:%s %s|", hub->nativenick, sstr);
2548 fn->lastsrch = time(NULL);
2556 #define cc(c) ((void (*)(struct socket *, void *, char *, char *))(c))
2557 static struct command hubcmds[] =
2559 {"$Lock", cc(cmd_lock)},
2560 {"$HubName", cc(cmd_hubname)},
2561 {"$Hello", cc(cmd_hello)},
2562 {"$Quit", cc(cmd_quit)},
2563 {"$NickList", cc(cmd_nicklist)},
2564 {"$OpList", cc(cmd_oplist)},
2565 {"$MyINFO", cc(cmd_myinfo)},
2566 {"$ForceMove", cc(cmd_forcemove)},
2567 {"$Search", cc(cmd_search)},
2568 {"$MultiSearch", cc(cmd_search)},
2569 {"$ConnectToMe", cc(cmd_connecttome)},
2570 {"$RevConnectToMe", cc(cmd_revconnecttome)},
2571 {"$GetNetInfo", cc(cmd_getnetinfo)},
2572 {"$To:", cc(cmd_to)},
2573 {"$SR", cc(cmd_sr)},
2574 {"$UserCommand", cc(cmd_usercommand)},
2575 {"$GetPass", cc(cmd_getpass)},
2576 {"$LogedIn", cc(cmd_logedin)}, /* sic */
2580 static struct command peercmds[] =
2582 {"$MyNick", cc(cmd_mynick)},
2583 {"$Lock", cc(cmd_peerlock)},
2584 {"$Direction", cc(cmd_direction)},
2585 {"$Key", cc(cmd_key)},
2586 {"$FileLength", cc(cmd_filelength)},
2587 {"$Error", cc(cmd_error)},
2588 {"$MaxedOut", cc(cmd_maxedout)},
2589 {"$Get", cc(cmd_get)},
2590 {"$Send", cc(cmd_send)},
2591 {"$Supports", cc(cmd_supports)},
2592 {"$GetBlock", cc(cmd_getblock)},
2593 {"$UGetBlock", cc(cmd_getblock)},
2594 {"$GetZBlock", cc(cmd_getblock)},
2595 {"$UGetZBlock", cc(cmd_getblock)},
2596 {"$ADCGET", cc(cmd_adcget)},
2597 {"$ADCSND", cc(cmd_adcsnd), 1},
2598 {"$Sending", cc(cmd_sending), 1},
2603 static void dctransdetach(struct transfer *transfer, struct dcpeer *peer)
2605 CBUNREG(transfer, trans_filterout, peer);
2608 peer->transfer = NULL;
2612 static void dctransgotdata(struct transfer *transfer, struct dcpeer *peer)
2616 unsigned char outbuf[1024];
2620 if((peer->state == PEER_TRNS) || (peer->state == PEER_SYNC))
2622 if(sockqueuesize(peer->sk) < 65536)
2624 if((buf = transfergetdata(transfer, &bufsize)) != NULL)
2626 if(peer->compress == CPRS_NONE)
2628 sockqueue(peer->sk, buf, bufsize);
2629 } else if(peer->compress == CPRS_ZLIB) {
2630 cstr = peer->cprsdata;
2631 cstr->next_in = buf;
2632 cstr->avail_in = bufsize;
2633 while(cstr->avail_in > 0)
2635 cstr->next_out = outbuf;
2636 cstr->avail_out = sizeof(outbuf);
2637 if((ret = deflate(cstr, 0)) != Z_OK)
2639 flog(LOG_WARNING, "bug? deflate() did not return Z_OK (but rather %i)", ret);
2643 sockqueue(peer->sk, outbuf, sizeof(outbuf) - cstr->avail_out);
2648 if(peer->state == PEER_SYNC)
2650 if(peer->compress == CPRS_ZLIB)
2652 cstr = peer->cprsdata;
2653 cstr->next_in = NULL;
2657 cstr->next_out = outbuf;
2658 cstr->avail_out = sizeof(outbuf);
2659 ret = deflate(cstr, Z_FINISH);
2660 if((ret != Z_OK) && (ret != Z_STREAM_END))
2662 flog(LOG_WARNING, "bug? deflate(Z_FINISH) did not return Z_OK (but rather %i)", ret);
2666 sockqueue(peer->sk, outbuf, sizeof(outbuf) - cstr->avail_out);
2667 } while(ret != Z_STREAM_END);
2673 if(peer->timeout == NULL)
2674 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
2675 peer->state = PEER_CMD;
2677 transfersetstate(transfer, TRNS_HS);
2678 socksettos(peer->sk, confgetint("fnet", "fnptos"));
2679 transfer->flags.b.minislot = 0;
2680 peer->sk->writecb = NULL;
2687 static void dctransendofdata(struct transfer *transfer, struct dcpeer *peer)
2689 peer->state = PEER_SYNC;
2690 dctransgotdata(transfer, peer);
2693 static void dcwantdata(struct transfer *transfer, struct dcpeer *peer)
2695 if(transferdatasize(transfer) < 65536)
2696 peer->sk->ignread = 0;
2699 static void transread(struct socket *sk, struct dcpeer *peer)
2703 struct transfer *transfer;
2705 if((buf = sockgetinbuf(sk, &bufsize)) == NULL)
2707 if(peer->transfer == NULL)
2713 transferputdata(peer->transfer, buf, bufsize);
2715 if(peer->transfer->curpos >= peer->transfer->size)
2717 transfer = peer->transfer;
2718 transferdetach(transfer);
2719 transferendofdata(transfer);
2722 if(transferdatasize(peer->transfer) > 65535)
2726 static void transerr(struct socket *sk, int err, struct dcpeer *peer)
2728 struct transfer *transfer;
2730 if((transfer = peer->transfer) == NULL)
2735 transferdetach(transfer);
2736 transferendofdata(transfer);
2739 static void transwrite(struct socket *sk, struct dcpeer *peer)
2741 if((peer->state != PEER_TRNS) && (peer->state != PEER_SYNC))
2743 if(peer->transfer == NULL)
2748 dctransgotdata(peer->transfer, peer);
2751 static void udpread(struct socket *sk, void *data)
2753 char *buf, *p, *p2, *hashbuf;
2754 size_t buflen, hashlen;
2755 char *nick, *filename, *hubname;
2756 struct sockaddr_in hubaddr;
2758 struct fnetnode *fn, *myfn;
2761 wchar_t *wnick, *wfile;
2764 if((buf = sockgetinbuf(sk, &buflen)) == NULL)
2766 buf = srealloc(buf, buflen + 1);
2768 if(!strncmp(buf, "$SR ", 4))
2772 if((p2 = strchr(p, ' ')) == NULL)
2780 if((p2 = strchr(p, 5)) == NULL)
2787 if((p2 = strchr(p, ' ')) == NULL)
2795 if((p2 = strchr(p, '/')) == NULL)
2803 if((p2 = strchr(p, 5)) == NULL)
2810 if((p2 = strstr(p, " (")) == NULL)
2817 if((p2 = strchr(p, ':')) == NULL)
2823 hubaddr.sin_family = AF_INET;
2824 if(!inet_aton(p, &hubaddr.sin_addr))
2830 if((p2 = strchr(p, ')')) == NULL)
2836 hubaddr.sin_port = htons(atoi(p));
2837 /* Use DCCHARSET in $Get paths until further researched... */
2838 if((wfile = icmbstowcs(filename, DCCHARSET)) == NULL)
2845 if(!strncmp(hubname, "TTH:", 4))
2847 if((hashbuf = base32decode(hubname + 4, &hashlen)) != NULL)
2850 hash = newhash(L"TTH", 24, hashbuf);
2854 for(fn = fnetnodes; fn != NULL; fn = fn->next)
2856 if((fn->fnet == &dcnet) && ((hub = fn->data) != NULL))
2858 if((hub->nativename != NULL) && !strcmp(hub->nativename, hubname))
2873 for(fn = fnetnodes; fn != NULL; fn = fn->next)
2875 if((fn->fnet == &dcnet) && (fn->sk != NULL) && addreq(fn->sk->remote, (struct sockaddr *)&hubaddr))
2885 if((wnick = icmbstowcs(nick, (hub == NULL)?DCCHARSET:(hub->charset))) == NULL)
2890 sr = newsrchres(&dcnet, wfile, wnick);
2891 if(sr->peernick != NULL)
2893 sr->peernick = swcsdup(wnick);
2899 getfnetnode(sr->fn = myfn);
2908 static void hubread(struct socket *sk, struct fnetnode *fn)
2915 hub = (struct dchub *)fn->data;
2916 if((newbuf = sockgetinbuf(sk, &datalen)) == NULL)
2918 if(hub->inbufdata > 500000) /* Discard possible malicious data */
2920 sizebuf2(hub->inbuf, hub->inbufdata + datalen, 1);
2921 memcpy(hub->inbuf + hub->inbufdata, newbuf, datalen);
2923 p = hub->inbuf + hub->inbufdata;
2924 hub->inbufdata += datalen;
2925 while((datalen > 0) && ((p = memchr(p, '|', datalen)) != NULL))
2928 newqcmd(&hub->queue, hub->inbuf);
2929 memmove(hub->inbuf, p, hub->inbufdata -= p - hub->inbuf);
2930 datalen = hub->inbufdata;
2935 static void huberr(struct socket *sk, int err, struct fnetnode *fn)
2940 static int hubsetnick(struct fnetnode *fn, wchar_t *newnick)
2946 if((buf = icwcstombs(newnick, (hub == NULL)?DCCHARSET:(hub->charset))) == NULL)
2948 if((strchr(buf, ' ') != NULL) || (strchr(buf, '|') != NULL) || (strchr(buf, '$') != NULL))
2953 if(hub == NULL) /* Not yet connected */
2958 if(hub->nativenick != NULL)
2959 free(hub->nativenick);
2960 hub->nativenick = buf;
2964 static struct dchub *newdchub(struct fnetnode *fn)
2971 new = smalloc(sizeof(*new));
2972 memset(new, 0, sizeof(*new));
2974 if(confgetint("dc", "dcppemu"))
2976 if((emu = wpfind(fn->args, L"dcppemu")) != NULL)
2984 if((wcharset = wpfind(fn->args, L"charset")) != NULL)
2986 if((charset = icwcstombs(wcharset, "US-ASCII")) != NULL)
2988 if(!havecharset(charset))
2996 new->charset = charset;
2998 new->charset = sstrdup(DCCHARSET);
2999 if(hubsetnick(fn, fn->mynick))
3000 fnetsetnick(fn, L"DoldaConnectUser-IN");
3001 /* IN as in Invalid Nick */
3005 static struct dcpeer *newdcpeer(struct socket *sk)
3009 new = smalloc(sizeof(*new));
3010 memset(new, 0, sizeof(*new));
3011 new->transfer = NULL;
3014 if(confgetint("dc", "dcppemu"))
3025 static void freedcpeer(struct dcpeer *peer)
3028 struct qcommand *qcmd;
3033 if(peer->next != NULL)
3034 peer->next->prev = peer->prev;
3035 if(peer->prev != NULL)
3036 peer->prev->next = peer->next;
3037 if(peer->transfer != NULL)
3039 if(peer->transfer->dir == TRNSD_UP)
3040 peer->transfer->close = 1;
3041 if(peer->transfer->dir == TRNSD_DOWN)
3042 resettransfer(peer->transfer);
3043 transferdetach(peer->transfer);
3045 if(peer->timeout != NULL)
3046 canceltimer(peer->timeout);
3047 if(peer->sk->data == peer)
3048 peer->sk->data = NULL;
3049 peer->sk->readcb = NULL;
3050 peer->sk->writecb = NULL;
3051 peer->sk->errcb = NULL;
3054 if(peer->supports != NULL)
3056 for(i = 0; peer->supports[i] != NULL; i++)
3057 free(peer->supports[i]);
3058 free(peer->supports);
3060 if(peer->inbuf != NULL)
3062 if(peer->key != NULL)
3064 if(peer->wcsname != NULL)
3065 free(peer->wcsname);
3066 if(peer->nativename != NULL)
3067 free(peer->nativename);
3068 if(peer->charset != NULL)
3069 free(peer->charset);
3070 if(peer->fn != NULL)
3071 putfnetnode(peer->fn);
3072 while((qcmd = ulqcmd(&peer->queue)) != NULL)
3078 static void hubconnect(struct fnetnode *fn)
3080 fn->sk->readcb = (void (*)(struct socket *, void *))hubread;
3081 fn->sk->errcb = (void (*)(struct socket *, int, void *))huberr;
3083 fn->data = newdchub(fn);
3088 static void hubdestroy(struct fnetnode *fn)
3091 struct qcommand *qcmd;
3093 hub = (struct dchub *)fn->data;
3094 if((fn->sk != NULL) && (fn->sk->data == fn))
3096 fn->sk->data = 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, "%i", 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=\"%i\"", 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() + 300, 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 {CONF_VAR_STRING, "desc", {.str = L""}},
3713 {CONF_VAR_STRING, "speedstring", {.str = L"LAN(T1)"}},
3714 {CONF_VAR_STRING, "email", {.str = L"spam@spam.org"}},
3715 {CONF_VAR_INT, "udpport", {.num = 0}},
3716 {CONF_VAR_INT, "tcpport", {.num = 0}},
3717 {CONF_VAR_BOOL, "dcppemu", {.num = 0}},
3721 static struct module me =
3730 .terminate = terminate,