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 h1 = findsehash(sexpr->l);
2431 h2 = findsehash(sexpr->r);
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;
3099 while((qcmd = ulqcmd(&hub->queue)) != NULL)
3101 if(hub->nativename != NULL)
3102 free(hub->nativename);
3103 if(hub->nativenick != NULL)
3104 free(hub->nativenick);
3105 if(hub->charset != NULL)
3107 if(hub->inbuf != NULL)
3112 static wchar_t *dcbasename(wchar_t *filename)
3116 if((ret = wcsrchr(filename, L'\\')) != NULL)
3121 static struct transferiface dctransfer =
3123 .detach = (void (*)(struct transfer *, void *))dctransdetach,
3124 .gotdata = (void (*)(struct transfer *, void *))dctransgotdata,
3125 .endofdata = (void (*)(struct transfer *, void *))dctransendofdata,
3126 .wantdata = (void (*)(struct transfer *, void *))dcwantdata
3129 static struct fnet dcnet =
3132 .connect = hubconnect,
3133 .destroy = hubdestroy,
3134 .setnick = hubsetnick,
3135 .reqconn = hubreqconn,
3136 .sendchat = hubsendchat,
3137 .search = hubsearch,
3138 .filebasename = dcbasename
3141 static void peerread(struct socket *sk, struct dcpeer *peer)
3145 struct command *cmd;
3147 if((newbuf = sockgetinbuf(sk, &datalen)) == NULL)
3149 sizebuf2(peer->inbuf, peer->inbufdata + datalen, 1);
3150 memcpy(peer->inbuf + peer->inbufdata, newbuf, datalen);
3152 peer->inbufdata += datalen;
3153 if(peer->state == PEER_CMD)
3156 while((peer->inbufdata > 0) && (p = memchr(peer->inbuf, '|', peer->inbufdata)) != NULL)
3159 newqcmd(&peer->queue, peer->inbuf);
3160 for(cmd = peercmds; cmd->handler != NULL; cmd++)
3162 if(!memcmp(peer->inbuf, cmd->name, strlen(cmd->name)) && ((peer->inbuf[strlen(cmd->name)] == ' ') || (peer->inbuf[strlen(cmd->name)] == '|')))
3165 memmove(peer->inbuf, p, peer->inbufdata -= p - peer->inbuf);
3168 peer->state = PEER_STOP;
3172 } else if(peer->state == PEER_TTHL) {
3177 static void peererror(struct socket *sk, int err, struct dcpeer *peer)
3182 static void peerconnect(struct socket *sk, int err, struct fnetnode *fn)
3184 struct dcpeer *peer;
3194 peer = newdcpeer(sk);
3197 peer->dcppemu = hub->dcppemu;
3198 sk->readcb = (void (*)(struct socket *, void *))peerread;
3199 sk->errcb = (void (*)(struct socket *, int, void *))peererror;
3201 socksettos(sk, confgetint("fnet", "fnptos"));
3203 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
3208 static void peeraccept(struct socket *sk, struct socket *newsk, void *data)
3210 struct dcpeer *peer;
3212 peer = newdcpeer(newsk);
3214 newsk->readcb = (void (*)(struct socket *, void *))peerread;
3215 newsk->errcb = (void (*)(struct socket *, int, void *))peererror;
3217 socksettos(newsk, confgetint("fnet", "fnptos"));
3218 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
3221 static void updatehmlist(void)
3223 int i, lev, ic, ret;
3224 struct sharecache *node;
3225 char *buf, *buf2, numbuf[32];
3226 size_t bufsize, bufdata;
3230 buf = smalloc(bufsize = 65536);
3231 node = shareroot->child;
3236 /* Use DCCHARSET in $Get paths until further researched... */
3237 if((buf2 = icwcstombs(node->name, DCCHARSET)) != NULL)
3239 for(i = 0; i < lev; i++)
3241 bufcat(buf, buf2, strlen(buf2));
3243 if(node->f.b.type == FILE_REG)
3246 sprintf(numbuf, "%i", node->size);
3247 bufcat(buf, numbuf, strlen(numbuf));
3254 if((node->child != NULL) && !ic)
3258 } else if(node->next != NULL) {
3261 while(node->next == NULL)
3264 node = node->parent;
3265 if(node == shareroot)
3268 if(node == shareroot)
3273 if(hmlistname != NULL)
3278 hmlistname = sstrdup("/tmp/dc-filelist-hm-XXXXXX");
3279 if((fd = mkstemp(hmlistname)) < 0)
3281 flog(LOG_WARNING, "could not create HM file list tempfile: %s", strerror(errno));
3286 * I do not want to implement a good Huffman encoder, and it's not
3287 * like Huffman encoding actually yields any impressive results
3288 * for DC file lists anyway, so I'll just output a bogus
3289 * tree. Implement a good encoder if you want to.
3291 write(fd, "HE3\r\0", 5);
3292 write(fd, &bufdata, 4);
3294 write(fd, &ibuf, 2);
3296 for(i = 0; i < 256; i++)
3299 write(fd, &ibuf, 1);
3301 for(i = 0; i < 256; i++)
3303 for(buf2 = buf; bufdata > 0;)
3305 if((ret = write(fd, buf2, bufdata)) < 0)
3307 flog(LOG_WARNING, "could not write file list: %s", strerror(errno));
3318 static struct xmlent
3325 /* {L'\'', L"""}, Emulate DC++ escaping by omitting this. */
3329 static wchar_t *escapexml(wchar_t *src)
3331 static wchar_t *buf = NULL;;
3334 size_t bufsize, bufdata;
3340 bufsize = bufdata = 0;
3341 for(; *src != L'\0'; src++)
3344 if((c > 0) && (c < 32))
3346 bufcat(buf, L"&#", 2);
3347 ret = swprintf(nbuf, (sizeof(nbuf) / sizeof(*nbuf)), L"%i", c);
3348 bufcat(buf, nbuf, ret);
3349 addtobuf(buf, L';');
3351 for(ent = entities; ent->ent != NULL; ent++)
3355 bufcat(buf, ent->ent, wcslen(ent->ent));
3359 if(ent->ent == NULL)
3360 addtobuf(buf, *src);
3363 addtobuf(buf, L'\0');
3367 static void updatexmllist(void)
3371 char cidbuf[14], *namebuf;
3373 struct sharecache *node;
3375 if(xmllistname != NULL)
3377 unlink(xmllistname);
3380 xmllistname = sstrdup("/tmp/dc-filelist-dcxml-XXXXXX");
3381 if((fd = mkstemp(xmllistname)) < 0)
3383 flog(LOG_WARNING, "could not create XML file list tempfile: %s", strerror(errno));
3388 if((fs = fdopen(fd, "w")) == NULL)
3390 flog(LOG_WARNING, "could not fdopen XML list fd %i: %s", fd, strerror(errno));
3391 unlink(xmllistname);
3397 fprintf(fs, "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>\r\n");
3398 for(i = 0; i < sizeof(cidbuf) - 1; i++)
3399 cidbuf[i] = (rand() % ('Z' - 'A' + 1)) + 'A';
3401 if(confgetint("dc", "dcppemu"))
3402 fprintf(fs, "<FileListing Version=\"1\" CID=\"%s\" Base=\"/\" Generator=\"DC++ 0.674\">\r\n", cidbuf);
3404 fprintf(fs, "<FileListing Version=\"1\" CID=\"%s\" Base=\"/\" Generator=\"%s\">\r\n", cidbuf, "DoldaConnect" VERSION);
3406 node = shareroot->child;
3410 if((namebuf = icswcstombs(escapexml(node->name), "UTF-8", NULL)) != NULL)
3412 for(i = 0; i < lev; i++)
3414 if(node->child != NULL)
3416 fprintf(fs, "<Directory Name=\"%s\">\r\n", namebuf);
3421 fprintf(fs, "<File Name=\"%s\" Size=\"%i\"", namebuf, node->size);
3422 if(node->f.b.hastth)
3424 hashbuf = base32encode(node->hashtth, 24);
3425 fprintf(fs, " TTH=\"%.39s\"", hashbuf);
3428 fprintf(fs, "/>\r\n");
3430 while(node->next == NULL)
3432 node = node->parent;
3433 if(node == shareroot)
3438 for(i = 0; i < lev; i++)
3440 fprintf(fs, "</Directory>\r\n");
3443 if(node == shareroot)
3449 if(confgetint("dc", "dcppemu"))
3450 fprintf(fs, "</FileListing>");
3452 fprintf(fs, "</FileListing>\r\n");
3456 static void updatexmlbz2list(void)
3465 if(xmllistname == NULL)
3467 if((in = fopen(xmllistname, "r")) == NULL)
3469 flog(LOG_WARNING, "could not open XML file list for bzipping: %s", strerror(errno));
3472 if(xmlbz2listname != NULL)
3474 unlink(xmlbz2listname);
3475 free(xmlbz2listname);
3477 xmlbz2listname = sstrdup("/tmp/dc-filelist-dcxmlbz2-XXXXXX");
3478 if((fd = mkstemp(xmlbz2listname)) < 0)
3480 flog(LOG_WARNING, "could not create bzipped XML file list tempfile: %s", strerror(errno));
3481 free(xmlbz2listname);
3482 xmlbz2listname = NULL;
3486 if((real = fdopen(fd, "w")) == NULL)
3488 flog(LOG_WARNING, "could not fdopen bzipped XML list fd %i: %s", fd, strerror(errno));
3490 unlink(xmlbz2listname);
3491 free(xmlbz2listname);
3492 xmlbz2listname = NULL;
3496 out = BZ2_bzWriteOpen(&err, real, 9, 0, 0);
3499 flog(LOG_WARNING, "could not open bzip2 stream from XML list");
3501 unlink(xmlbz2listname);
3502 free(xmlbz2listname);
3503 xmlbz2listname = NULL;
3509 bufdata = fread(buf, 1, sizeof(buf), in);
3510 BZ2_bzWrite(&err, out, buf, bufdata);
3513 BZ2_bzWriteClose(&err, out, 0, NULL, NULL);
3517 static void listtimercb(int cancelled, void *uudata)
3519 listwritetimer = NULL;
3524 static void updatelists(int now)
3528 if(listwritetimer == NULL)
3529 listwritetimer = timercallback(ntime() + 300, listtimercb, NULL);
3532 if(listwritetimer != NULL)
3533 canceltimer(listwritetimer);
3539 static int shareupdate(unsigned long long uusharesize, void *data)
3545 static void dispatchcommand(struct qcommand *qcmd, struct command *cmdlist, struct socket *sk, void *data)
3548 struct command *cmd;
3550 if((p = strchr(qcmd->string, ' ')) != NULL)
3552 for(cmd = cmdlist; cmd->handler != NULL; cmd++)
3554 if(!strcmp(cmd->name, qcmd->string))
3557 if(cmd->handler != NULL)
3558 cmd->handler(sk, data, qcmd->string, p);
3561 flog(LOG_DEBUG, "Unimplemented DC command: %s \"%s\"", qcmd->string, p?p:"noargs");
3565 static int run(void)
3567 struct fnetnode *fn, *nextfn;
3569 struct dcpeer *peer, *nextpeer;
3570 struct qcommand *qcmd;
3574 for(fn = fnetnodes; fn != NULL; fn = nextfn)
3577 if(fn->fnet != &dcnet)
3579 if(fn->data == NULL)
3581 hub = (struct dchub *)fn->data;
3582 if((qcmd = ulqcmd(&hub->queue)) != NULL)
3584 if(*qcmd->string == '$')
3586 if((fn->sk != NULL) && (fn->sk->state == SOCK_EST))
3587 dispatchcommand(qcmd, hubcmds, fn->sk, fn);
3588 } else if(*qcmd->string != 0) {
3589 hubrecvchat(fn->sk, fn, NULL, qcmd->string);
3596 for(peer = peers; peer != NULL; peer = nextpeer)
3598 nextpeer = peer->next;
3599 if((qcmd = ulqcmd(&peer->queue)) != NULL)
3601 if(peer->timeout != NULL)
3602 canceltimer(peer->timeout);
3603 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
3604 if(*qcmd->string == '$')
3605 dispatchcommand(qcmd, peercmds, peer->sk, peer);
3614 static void preinit(int hup)
3621 static int updateudpport(struct configvar *var, void *uudata)
3623 struct sockaddr_in addr;
3624 struct socket *newsock;
3626 memset(&addr, 0, sizeof(addr));
3627 addr.sin_family = AF_INET;
3628 addr.sin_port = htons(var->val.num);
3629 if((newsock = netcsdgram((struct sockaddr *)&addr, sizeof(addr))) == NULL)
3631 flog(LOG_WARNING, "could not create new DC UDP socket, reverting to old: %s", strerror(errno));
3634 newsock->readcb = udpread;
3641 static int updatetcpport(struct configvar *var, void *uudata)
3643 struct sockaddr_in addr;
3644 struct socket *newsock;
3646 memset(&addr, 0, sizeof(addr));
3647 addr.sin_family = AF_INET;
3648 addr.sin_port = htons(var->val.num);
3649 if((newsock = netcslisten(SOCK_STREAM, (struct sockaddr *)&addr, sizeof(addr), peeraccept, NULL)) == NULL)
3650 flog(LOG_INFO, "could not listen to a remote address, going into passive mode");
3657 static int init(int hup)
3659 struct sockaddr_in addr;
3663 GCBREG(sharechangecb, shareupdate, NULL);
3668 addr.sin_family = AF_INET;
3669 memset(&addr.sin_addr, 0, sizeof(addr.sin_addr));
3670 addr.sin_port = htons(confgetint("dc", "udpport"));
3671 if((udpsock = netcsdgram((struct sockaddr *)&addr, sizeof(addr))) == NULL)
3673 flog(LOG_CRIT, "could not create DC UDP socket: %s", strerror(errno));
3676 udpsock->readcb = udpread;
3677 addr.sin_port = htons(confgetint("dc", "tcpport"));
3678 if((tcpsock = netcslisten(SOCK_STREAM, (struct sockaddr *)&addr, sizeof(addr), peeraccept, NULL)) == NULL)
3679 flog(LOG_INFO, "could not listen to a remote address, going into passive mode");
3680 CBREG(confgetvar("dc", "udpport"), conf_update, updateudpport, NULL, NULL);
3681 CBREG(confgetvar("dc", "tcpport"), conf_update, updatetcpport, NULL, NULL);
3682 CBREG(confgetvar("net", "mode"), conf_update, updatetcpport, NULL, NULL);
3687 static void terminate(void)
3689 if(hmlistname != NULL)
3694 if(xmllistname != NULL)
3696 unlink(xmllistname);
3699 if(xmlbz2listname != NULL)
3701 unlink(xmlbz2listname);
3702 free(xmlbz2listname);
3706 static struct configvar myvars[] =
3708 {CONF_VAR_STRING, "desc", {.str = L""}},
3709 {CONF_VAR_STRING, "speedstring", {.str = L"LAN(T1)"}},
3710 {CONF_VAR_STRING, "email", {.str = L"spam@spam.org"}},
3711 {CONF_VAR_INT, "udpport", {.num = 0}},
3712 {CONF_VAR_INT, "tcpport", {.num = 0}},
3713 {CONF_VAR_BOOL, "dcppemu", {.num = 0}},
3717 static struct module me =
3726 .terminate = terminate,