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;
162 static void peerconnect(struct socket *sk, int err, struct fnetnode *fn);
163 static void freedcpeer(struct dcpeer *peer);
164 static void transread(struct socket *sk, struct dcpeer *peer);
165 static void transerr(struct socket *sk, int err, struct dcpeer *peer);
166 static void transwrite(struct socket *sk, struct dcpeer *peer);
167 static void updatehmlist(void);
168 static void updatexmllist(void);
169 static void updatexmlbz2list(void);
170 static void requestfile(struct dcpeer *peer);
172 static int reservedchar(unsigned char c)
174 return((c == 0) || (c == 5) || (c == 124) || (c == 96) || (c == 126) || (c == 36));
177 /* Oh, how I despise having to do this... */
178 static char *dcmakekey(char *lock)
184 buf = smalloc(strlen(lock));
187 for(i = 0; lock[i]; i++)
189 buf[i] = lock[i] ^ save;
190 buf[i] = ((buf[i] & 0x0F) << 4) | ((buf[i] & 0xF0) >> 4);
192 if((i != 0) && reservedchar(buf[i]))
197 buf[0] ^= buf[i - 1];
198 if(reservedchar(buf[0]))
202 key = smalloc(len + 1);
204 for(i = 0; lock[i] != 0; i++)
206 if(reservedchar(buf[i]))
207 offset += sprintf(key + offset, "/%%DCN%03i%%/", buf[i]);
209 key[offset++] = buf[i];
216 static char *pathnmdc2adc(char *path)
219 size_t retsize, retdata;
221 if(!strcmp(path, "files.xml") || !strcmp(path, "files.xml.bz2") || !strcmp(path, "MyList.DcLst"))
222 return(sstrdup(path));
224 retsize = retdata = 0;
231 addtobuf(ret, *path);
237 static int isdchash(struct hash *hash)
239 if(wcscmp(hash->algo, L"TTH"))
246 static int supports(struct dcpeer *peer, char *cap)
250 if(peer->supports == NULL)
252 for(p = peer->supports; *p != NULL; p++)
254 if(!strcasecmp(*p, cap))
260 static void endcompress(struct dcpeer *peer)
262 if(peer->compress == CPRS_ZLIB)
264 deflateEnd(peer->cprsdata);
265 free(peer->cprsdata);
267 peer->compress = CPRS_NONE;
270 static void initcompress(struct dcpeer *peer, int algo)
275 peer->compress = algo;
276 if(algo == CPRS_ZLIB)
278 peer->cprsdata = smalloc(sizeof(z_stream));
279 memset(peer->cprsdata, 0, sizeof(z_stream));
280 if((ret = deflateInit(peer->cprsdata, 3)) != Z_OK)
282 flog(LOG_CRIT, "Aiya! zlib refuses to init (%i)!", ret);
288 static void unquote(wchar_t *in)
292 for(p = in; *p != L'\0'; p++)
296 for(p2 = p + 1; (*p2 != L'\0') && (*p2 != L';') && (*p2 != L'&'); p2++);
303 if(!wcscmp(p + 1, L"amp"))
306 } else if(p[1] == L'#') {
307 nc = ucptowc(wcstol(p + 2, NULL, 10));
316 memmove(p + 1, p2 + 1, (wcslen(p2 + 1) + 1) * sizeof(wchar_t));
321 static void freeexppeer(struct dcexppeer *ep)
324 ep->next->prev = ep->prev;
326 ep->prev->next = ep->next;
331 if(ep->expire != NULL)
332 canceltimer(ep->expire);
336 static void exppeerexpire(int cancelled, struct dcexppeer *ep)
343 static struct dcexppeer *expectpeer(char *nick, struct fnetnode *fn)
345 struct dcexppeer *ep;
347 ep = smalloc(sizeof(*ep));
348 ep->nick = sstrdup(nick);
349 getfnetnode(ep->fn = fn);
350 ep->expire = timercallback(ntime() + 300, (void (*)(int, void *))exppeerexpire, ep);
359 static struct qcommand *newqcmd(struct qcommand **queue, char *string)
361 struct qcommand *new;
363 while(*queue != NULL)
364 queue = &(*queue)->next;
365 new = smalloc(sizeof(*new));
366 new->string = sstrdup(string);
372 static struct qcommand *ulqcmd(struct qcommand **queue)
374 struct qcommand *qcmd;
376 if((qcmd = *queue) == NULL)
382 static void freeqcmd(struct qcommand *qcmd)
388 static void hubrecvchat(struct socket *sk, struct fnetnode *fn, char *from, char *string)
390 wchar_t *chat, *wfrom, *wpeer;
392 struct fnetpeer *peer;
396 end = string + strlen(string);
397 while((p = strchr(string, 13)) != NULL)
398 memmove(p, p + 1, (end-- - p));
401 if((strlen(string) > strlen(from) + 2) && (*string == '<') && !memcmp(string + 1, from, strlen(from)) && (*(string + strlen(from) + 1) == '>'))
402 string += strlen(from) + 2;
403 if((wfrom = icmbstowcs(from, hub->charset)) == NULL)
405 wpeer = swcsdup(wfrom);
411 for(p = string + 1; *p; p++)
413 if((*p == ' ') || (*p == '>'))
421 if((wpeer = icmbstowcs(string + 1, hub->charset)) == NULL)
427 wpeer = swcsdup(L"");
429 if((chat = icmbstowcs(string, hub->charset)) == NULL)
439 if((peer = fnetfindpeer(fn, wfrom)) == NULL) /* Assume public chat */
440 fnethandlechat(fn, 1, wfrom, wpeer, chat);
442 fnethandlechat(fn, 0, wfrom, wpeer, chat);
444 fnethandlechat(fn, 1, L"", wpeer, chat);
452 static void peertimeout(int cancelled, struct dcpeer *peer)
454 peer->timeout = NULL;
460 static void sendadc(struct socket *sk, char *arg)
463 size_t bufsize, bufdata;
466 bufsize = bufdata = 0;
472 bufcat(buf, "\\s", 2);
473 } else if(*arg == '\n') {
474 bufcat(buf, "\\n", 2);
475 } else if(*arg == '\\') {
476 bufcat(buf, "\\\\", 2);
481 sockqueue(sk, buf, bufdata);
485 static void sendadcf(struct socket *sk, char *arg, ...)
491 buf = vsprintf2(arg, args);
499 static char **parseadc(char *args)
502 size_t retbufsize, retbufdata;
504 size_t bufsize, bufdata;
509 retbufsize = retbufdata = bufsize = bufdata = 0;
518 else if(*args != ' ')
522 if((*args == ' ') || (*args == 0))
525 addtobuf(retbuf, buf);
527 bufsize = bufdata = 0;
530 } else if(*args == '\\') {
533 addtobuf(buf, *args);
542 addtobuf(retbuf, NULL);
545 } else if((*args == 's') || (*args == ' ')) {
547 } else if(*args == 'n') {
549 } else if(*args == '\\') {
559 addtobuf(retbuf, NULL);
563 /* Macros useful in command handlers */
564 #define skipspace(s) ({if(((s) = strchr((s), ' ')) == NULL) return; else (s)++;})
565 #define qstr(sk, str) sockqueue(sk, str, strlen(str))
566 #define qstrf(sk, strandargs...) \
569 if((__buf__ = sprintf2(strandargs)) != NULL) { \
570 sockqueue(sk, __buf__, strlen(__buf__)); \
575 static char *tr(char *str, char *trans)
579 for(; *trans; trans += 2)
581 for(p = strchr(str, trans[0]); p != NULL; p = strchr(p, trans[0]))
587 static char *getadcid(struct dcpeer *peer)
594 if(!wcscmp(peer->transfer->path, L"files.xml") || !wcscmp(peer->transfer->path, L"files.xml.bz2") || !wcscmp(peer->transfer->path, L"MyList.DcLst"))
596 if(!isfilelist && (peer->transfer->hash != NULL) && isdchash(peer->transfer->hash) && supports(peer, "tthf"))
598 buf = base32encode(peer->transfer->hash->buf, 24);
599 ret = sprintf2("TTH/%.39s", buf);
602 if((buf = icwcstombs(peer->transfer->path, "UTF-8")) == NULL)
604 ret = pathnmdc2adc(buf);
611 static int trresumecb(struct transfer *transfer, wchar_t *cmd, wchar_t *arg, struct dcpeer *peer)
613 if(!wcscmp(cmd, L"resume"))
617 flog(LOG_WARNING, "filter returned no position for \"resume\" on transfer %i", transfer->id);
620 transfer->curpos = wcstol(arg, NULL, 10);
629 static void sendmynick(struct dcpeer *peer)
635 qstrf(peer->sk, "$MyNick %s|", icswcstombs(confgetstr("cli", "defnick"), peer->charset, "DoldaConnectUser-IN"));
637 qstrf(peer->sk, "$MyNick %s|", icswcstombs(fn->mynick, peer->charset, "DoldaConnectUser-IN"));
640 static void sendpeerlock(struct dcpeer *peer)
643 qstrf(peer->sk, "$Lock EXTENDEDPROTOCOLABCABCABCABCABCABC Pk=DCPLUSPLUS0.674ABCABC|");
645 qstrf(peer->sk, "$Lock EXTENDEDPROTOCOLABCABCABCABCABCABC Pk=DOLDA%sABCABCABC|", VERSION);
648 static void sendsupports(struct dcpeer *peer)
651 qstr(peer->sk, "$Supports MiniSlots XmlBZList ADCGet TTHL TTHF GetZBlock ZLIG |");
653 qstr(peer->sk, "$Supports MiniSlots XmlBZList ADCGet TTHL TTHF GetZBlock ZLIG|");
656 static void requestfile(struct dcpeer *peer)
660 if(peer->transfer->size == -1)
662 /* Use DCCHARSET for $Get paths until further researched... */
663 if((buf = icswcstombs(peer->transfer->path, DCCHARSET, NULL)) == NULL)
665 transferseterror(peer->transfer, TRNSE_NOTFOUND);
669 /* The transfer will be restarted later from
670 * cmd_filelength when it detects that the sizes
672 qstrf(peer->sk, "$Get %s$1|", buf);
675 if((peer->transfer->hash == NULL) && !peer->notthl)
677 if(supports(peer, "adcget") && supports(peer, "tthl"))
679 qstr(peer->sk, "$ADCGET");
680 sendadc(peer->sk, "tthl");
681 if((buf = getadcid(peer)) == NULL)
683 transferseterror(peer->transfer, TRNSE_NOTFOUND);
687 sendadc(peer->sk, buf);
689 sendadc(peer->sk, "0");
690 sendadc(peer->sk, "-1");
692 peer->fetchingtthl = 1;
698 if(forkfilter(peer->transfer))
700 flog(LOG_WARNING, "could not fork filter for transfer %i: %s", peer->transfer->id, strerror(errno));
704 CBREG(peer->transfer, trans_filterout, (int (*)(struct transfer *, wchar_t *, wchar_t *, void *))trresumecb, NULL, peer);
707 if(supports(peer, "adcget"))
709 qstr(peer->sk, "$ADCGET");
710 sendadc(peer->sk, "file");
711 if((buf = getadcid(peer)) == NULL)
713 transferseterror(peer->transfer, TRNSE_NOTFOUND);
717 sendadc(peer->sk, buf);
719 sendadcf(peer->sk, "%i", peer->transfer->curpos);
720 sendadcf(peer->sk, "%i", peer->transfer->size - peer->transfer->curpos);
722 } else if(supports(peer, "xmlbzlist")) {
723 if((buf = icswcstombs(peer->transfer->path, "UTF-8", NULL)) == NULL)
725 transferseterror(peer->transfer, TRNSE_NOTFOUND);
729 qstrf(peer->sk, "$UGetBlock %i %i %s|", peer->transfer->curpos, peer->transfer->size - peer->transfer->curpos, buf);
731 /* Use DCCHARSET for $Get paths until further researched... */
732 if((buf = icswcstombs(peer->transfer->path, DCCHARSET, NULL)) == NULL)
734 transferseterror(peer->transfer, TRNSE_NOTFOUND);
738 qstrf(peer->sk, "$Get %s$%i|", buf, peer->transfer->curpos + 1);
742 static void sendmyinfo(struct socket *sk, struct fnetnode *fn)
746 struct fnetnode *cfn;
750 qstrf(sk, "$MyINFO $ALL %s ", hub->nativenick);
751 buf = tr(icswcstombs(confgetstr("dc", "desc"), hub->charset, "Charset_conv_failure"), "$_|_");
752 qstrf(sk, "%s", buf);
754 for(cfn = fnetnodes; cfn != NULL; cfn = cfn->next)
756 if((cfn->state == FNN_EST) || (cfn->state == FNN_HS))
758 if(cfn->regstatus == FNNS_OP)
760 else if(cfn->regstatus == FNNS_REG)
766 qstrf(sk, "<%s V:%s,M:%c,H:%i/%i/%i,S:%i>",
767 (hub->dcppemu)?"++":"Dolda",
768 (hub->dcppemu)?"0.674":VERSION,
769 (tcpsock == NULL)?'P':'A',
771 confgetint("transfer", "slots")
774 buf = tr(icswcstombs(confgetstr("dc", "speedstring"), hub->charset, "Charset_conv_failure"), "$_|_");
775 qstrf(sk, "%s\x01$", buf);
776 buf = tr(icswcstombs(confgetstr("dc", "email"), hub->charset, "Charset_conv_failure"), "$_|_");
777 qstrf(sk, "%s$", buf);
778 qstrf(sk, "%llu$|", sharesize);
781 static void hubhandleaction(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
786 if(!strcmp(cmd, "$Lock"))
788 qstrf(sk, "$ValidateNick %s|", hub->nativenick);
789 } else if(!strcmp(cmd, "$Hello")) {
790 if(fn->state == FNN_HS)
792 qstrf(sk, "$Version 1,0091|");
793 qstrf(sk, "$GetNickList|");
795 fnetsetstate(fn, FNN_EST);
797 qstrf(sk, "$GetINFO %s %s|", args, hub->nativenick);
802 static void cmd_lock(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
809 if(!strncmp(args, "EXTENDEDPROTOCOL", 16))
811 if((p = strchr(args, ' ')) != NULL)
816 qstrf(sk, "$Supports UserCommand NoGetINFO NoHello UserIP2 TTHSearch GetZBlock |");
818 qstrf(sk, "$Supports UserCommand NoGetINFO NoHello UserIP2 TTHSearch GetZBlock|");
820 key = dcmakekey(args);
821 qstrf(sk, "$Key %s|", key);
823 hubhandleaction(sk, fn, cmd, args);
826 static void cmd_hubname(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
832 if(hub->nativename == NULL)
833 free(hub->nativename);
834 hub->nativename = sstrdup(args);
835 buf = icmbstowcs(args, hub->charset);
836 fnetsetname(fn, (buf == NULL)?L"Hubname conv error":buf);
839 hubhandleaction(sk, fn, cmd, args);
842 static void cmd_hello(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
848 if((nick = icmbstowcs(args, hub->charset)) == NULL)
850 if(strcmp(args, hub->nativenick) && (fnetfindpeer(fn, nick) == NULL))
851 fnetaddpeer(fn, nick, nick);
853 hubhandleaction(sk, fn, cmd, args);
856 static void cmd_quit(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
859 struct fnetpeer *peer;
863 if((nick = icmbstowcs(args, hub->charset)) == NULL)
865 if((peer = fnetfindpeer(fn, nick)) != NULL)
868 hubhandleaction(sk, fn, cmd, args);
871 static void cmd_nicklist(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
876 struct fnetpeer *peer, *npeer;
879 for(peer = fn->peers; peer != NULL; peer = peer->next)
880 peer->flags.b.delete = 1;
881 while((p = strstr(args, "$$")) != NULL)
884 if((buf = icmbstowcs(args, hub->charset)) != NULL)
886 if((peer = fnetfindpeer(fn, buf)) == NULL)
887 peer = fnetaddpeer(fn, buf, buf);
889 peer->flags.b.delete = 0;
891 qstrf(sk, "$GetINFO %s %s|", args, hub->nativenick);
895 for(peer = fn->peers; peer != NULL; peer = npeer)
898 if(peer->flags.b.delete)
901 hubhandleaction(sk, fn, cmd, args);
904 static void cmd_oplist(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
909 struct fnetpeer *peer;
912 for(peer = fn->peers; peer != NULL; peer = peer->next)
913 peer->flags.b.op = 0;
914 while((p = strstr(args, "$$")) != NULL)
917 if((buf = icmbstowcs(args, hub->charset)) != NULL)
919 if((peer = fnetfindpeer(fn, buf)) != NULL)
920 peer->flags.b.op = 1;
925 hubhandleaction(sk, fn, cmd, args);
928 static void cmd_myinfo(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
931 wchar_t *buf, *wp, *wp2;
933 struct fnetpeer *peer;
938 if(strncmp(p, "$ALL ", 5))
941 if((p2 = strchr(p, ' ')) == NULL)
944 if((buf = icmbstowcs(p, hub->charset)) == NULL)
946 if((peer = fnetfindpeer(fn, buf)) == NULL)
947 peer = fnetaddpeer(fn, buf, buf);
950 if((p2 = strstr(p, "$ $")) == NULL)
953 if((buf = icmbstowcs(p, hub->charset)) == NULL)
955 if((wcslen(buf) > 0) && (buf[wcslen(buf) - 1] == L'>') && ((wp = wcsrchr(buf, L'<')) != NULL))
957 buf[wcslen(buf) - 1] = L'\0';
959 if((wp2 = wcschr(wp, L' ')) != NULL)
962 fnetpeersetstr(peer, L"dc-client", wp);
966 if((wp2 = wcschr(wp, L',')) != NULL)
970 swprintf(abuf, 10, L"dc-tag-%lc", wp[0]);
971 fnetpeersetstr(peer, abuf, wp + 2);
973 } while(wp2 != NULL);
976 fnetpeersetstr(peer, L"descr", buf);
979 if((p2 = strchr(p, '$')) == NULL)
982 if((buf = icmbstowcs(p, hub->charset)) == NULL)
984 fnetpeersetstr(peer, L"dc-speed", buf);
987 if((p2 = strchr(p, '$')) == NULL)
990 if((buf = icmbstowcs(p, hub->charset)) == NULL)
992 fnetpeersetstr(peer, L"email", buf);
997 fnetpeersetlnum(peer, L"share", strtoll(p, NULL, 10));
998 hubhandleaction(sk, fn, cmd, args);
1001 /* I do not implement the fully in that I do not disconnect from the
1002 * old hub. I do this since I believe that if the hub owner really
1003 * wants to get rid of us, then it is his responsibility to disconnect
1005 static void cmd_forcemove(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1008 struct fnetnode *newfn;
1012 if(strchr(args, ':') == NULL)
1014 args = strcpy(smalloc(strlen(args) + 5), args);
1015 strcat(args, ":411");
1020 if((newfn = fnetinitconnect(L"dc", args, NULL)) != NULL)
1022 linkfnetnode(newfn);
1025 hubhandleaction(sk, fn, cmd, args);
1030 static char *getdcpath(struct sharecache *node, size_t *retlen, char *charset)
1035 if(node->parent == NULL)
1037 if(node->parent == shareroot)
1039 if((buf = icwcstombs(node->name, charset)) == NULL)
1042 *retlen = strlen(buf);
1045 if((buf2 = icwcstombs(node->name, charset)) == NULL)
1047 if((buf = getdcpath(node->parent, &len, charset)) == NULL)
1052 len2 = strlen(buf2);
1053 buf = srealloc(buf, len + 1 + len2 + 1);
1055 strcpy(buf + len, buf2);
1056 buf[len + len2] = 0;
1059 *retlen = len + len2;
1065 * This is the main share searching function for Direct Connect
1066 * peers. Feel free to optimize it if you feel the need for it. I
1067 * haven't ever seen it take any noticable CPU time anyway, so I
1068 * haven't felt that need.
1070 * It may feel dubious to just return the directory when all terms are
1071 * satisfied rather than all the files in it, but it really benefits
1072 * everyone: Less cycles used for us, less UDP squelching for active
1073 * searchers, and less bandwidth waste for hubs when serving passive
1076 static void cmd_search(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1081 char *prefix, *infix, *postfix, *buf, *buf2;
1083 struct sockaddr_in addr;
1084 struct sharecache *node;
1085 int minsize, maxsize;
1088 int termnum, satisfied, skipcheck;
1089 int level, tersat[32];
1094 if((p = strchr(args, ' ')) == NULL)
1098 memset(terms, 0, sizeof(terms));
1099 prefix = infix = postfix = NULL;
1103 if(!strncmp(args, "Hub:", 4))
1105 if(!strcmp(cmd, "$MultiSearch"))
1107 if(!strcmp(args + 4, hub->nativenick))
1109 prefix = sprintf2("$SR %s ", hub->nativenick);
1110 infix = sprintf2(" %i/%i\005", slotsleft(), confgetint("transfer", "slots"));
1111 postfix = sprintf2(" (%s)\005%s|", formataddress(fn->sk->remote, fn->sk->remotelen), args + 4);
1115 if((p2 = strchr(args, ':')) == NULL)
1118 addr.sin_family = AF_INET;
1119 if(!inet_aton(args, &addr.sin_addr))
1121 addr.sin_port = htons(atoi(p2));
1122 prefix = sprintf2("$SR %s ", hub->nativenick);
1123 infix = sprintf2(" %i/%i\005", slotsleft(), confgetint("transfer", "slots"));
1124 postfix = sprintf2(" (%s)|", formataddress(fn->sk->remote, fn->sk->remotelen));
1125 netdgramconn(dsk = netdupsock(udpsock), (struct sockaddr *)&addr, sizeof(addr));
1128 minsize = maxsize = -1;
1137 if((*(p++) == 'T') && (minsize == 0))
1144 if((p2 = strchr(p, '?')) == NULL)
1159 if((*p2 == 0) || (*p2 == '$'))
1167 if(!dotth && !strncmp(p, "TTH:", 4))
1170 if(((buf = base32decode(p + 4, &buflen)) == NULL) || (buflen != 24))
1175 memcpy(hashtth, buf, 24);
1178 if((terms[termnum] = icmbstowcs(p, hub->charset)) != NULL)
1189 node = shareroot->child;
1191 for(i = 0; i < termnum; i++)
1197 if(node->f.b.type == FILE_REG)
1199 if((minsize >= 0) && (node->size < minsize))
1201 if((maxsize >= 0) && (node->size > maxsize))
1204 if(!skipcheck && dotth)
1206 if((node->f.b.type != FILE_REG) || (node->f.b.hastth && memcmp(hashtth, node->hashtth, 24)))
1211 for(i = 0; i < termnum; i++)
1215 if(wcsexists(node->name, terms[i]))
1219 } else if(node->child == NULL) {
1224 if(!skipcheck && (satisfied == termnum))
1226 /* Use DCCHARSET in $Get paths until further researched... */
1227 if((buf = getdcpath(node, NULL, DCCHARSET)) != NULL)
1229 if(node->f.b.hastth)
1231 buf2 = base32encode(node->hashtth, 24);
1232 qstrf(dsk, "%s%s\005%i%sTTH:%.39s%s", prefix, buf, node->size, infix, buf2, postfix);
1235 qstrf(dsk, "%s%s\005%i%s%s%s", prefix, buf, node->size, infix, hub->nativename, postfix);
1240 if((!skipcheck && (satisfied == termnum)) || (node->child == NULL))
1242 while(node->next == NULL)
1244 if((node = node->parent) == shareroot)
1248 if(node == shareroot)
1250 for(i = 0; i < termnum; i++)
1252 if(tersat[i] >= level)
1265 hubhandleaction(sk, fn, cmd, args);
1276 for(i = 0; (i < 32) && (terms[i] != NULL); i++)
1280 static void cmd_connecttome(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1284 struct socket *newsk;
1285 struct sockaddr_in addr;
1288 if((p = strchr(args, ' ')) == NULL)
1291 if(strcmp(args, hub->nativenick))
1293 addr.sin_family = AF_INET;
1295 if((p = strchr(args, ':')) == NULL)
1298 addr.sin_port = htons(atoi(p));
1299 if(!inet_aton(args, &addr.sin_addr))
1301 newsk = netcsconn((struct sockaddr *)&addr, sizeof(addr), (void (*)(struct socket *, int, void *))peerconnect, fn);
1303 hubhandleaction(sk, fn, cmd, args);
1306 static void sendctm(struct socket *sk, char *nick)
1308 struct sockaddr *addr;
1313 if(sockgetremotename2(tcpsock, sk, &addr, &addrlen) < 0)
1315 if(addr->sa_family == AF_INET)
1316 qstrf(sk, "$ConnectToMe %s %s|", nick, formataddress(addr, addrlen));
1318 flog(LOG_WARNING, "Direct Connect TCP socket is suddenly not AF_INET, but %i", addr->sa_family);
1322 static void cmd_revconnecttome(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1328 if((p = strchr(args, ' ')) == NULL)
1331 if(strcmp(p, hub->nativenick))
1334 expectpeer(args, fn);
1335 hubhandleaction(sk, fn, cmd, args);
1338 static void cmd_getnetinfo(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1341 struct fnetnode *node;
1346 for(node = fnetnodes; node != NULL; node = node->next)
1348 if(node->state == FNN_EST)
1351 qstrf(sk, "$NetInfo %i$%i$%c$0|", confgetint("transfer", "slots"), numhubs, (tcpsock == NULL)?'P':'A');
1352 hubhandleaction(sk, fn, cmd, args);
1355 static void cmd_to(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1362 if((p2 = strchr(p, ' ')) == NULL)
1366 if((p2 = strchr(p, ' ')) == NULL)
1369 if(strcmp(p, "From:"))
1372 if((p2 = strstr(p, " $")) == NULL)
1376 hubrecvchat(fn->sk, fn, p, p2);
1377 hubhandleaction(sk, fn, cmd, args);
1380 static void cmd_sr(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1384 char *nick, *filename, *hubname;
1388 wchar_t *wnick, *wfile;
1392 if((p2 = strchr(p, ' ')) == NULL)
1397 if((p2 = strchr(p, 5)) == NULL)
1401 if((p2 = strchr(p, ' ')) == NULL)
1406 if((p2 = strchr(p, '/')) == NULL)
1411 if((p2 = strchr(p, 5)) == NULL)
1415 if((p2 = strstr(p, " (")) == NULL)
1418 if((wnick = icmbstowcs(nick, hub->charset)) == NULL)
1420 /* Use DCCHARSET in $Get paths until further researched... */
1421 if((wfile = icmbstowcs(filename, DCCHARSET)) == NULL)
1426 sr = newsrchres(&dcnet, wfile, wnick);
1427 if(sr->peernick != NULL)
1429 sr->peernick = swcsdup(wnick);
1434 if(!strncmp(hubname, "TTH:", 4))
1436 if((buf = base32decode(hubname + 4, &buflen)) != NULL)
1439 sr->hash = newhash(L"TTH", 24, buf);
1443 getfnetnode(sr->fn = fn);
1446 hubhandleaction(sk, fn, cmd, args);
1449 static void cmd_usercommand(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1451 /* Do nothing for now. */
1454 static void cmd_getpass(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1461 pw = wpfind(fn->args, L"password");
1462 if((pw == NULL) || ((mbspw = icwcstombs(pw, hub->charset)) == NULL))
1467 qstrf(sk, "$MyPass %s|", mbspw);
1469 fn->regstatus = FNNS_REG;
1470 hubhandleaction(sk, fn, cmd, args);
1473 static void cmd_logedin(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
1478 fn->regstatus = FNNS_OP;
1479 hubhandleaction(sk, fn, cmd, args);
1482 static void cmd_mynick(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1484 struct dcexppeer *expect;
1487 if(peer->nativename != NULL)
1488 free(peer->nativename);
1489 peer->nativename = sstrdup(args);
1490 if(peer->wcsname != NULL)
1491 free(peer->wcsname);
1492 if((peer->wcsname = icmbstowcs(peer->nativename, peer->charset)) == NULL)
1499 for(expect = expected; expect != NULL; expect = expect->next)
1501 if(!strcmp(expect->nick, args))
1508 hub = expect->fn->data;
1509 peer->fn = expect->fn;
1510 getfnetnode(peer->fn);
1511 peer->dcppemu = hub->dcppemu;
1512 freeexppeer(expect);
1517 static void cmd_direction(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1521 struct transfer *transfer;
1523 if((p = strchr(args, ' ')) == NULL)
1526 if(!strcmp(args, "Upload"))
1528 if(!strcmp(args, "Download"))
1532 if((peer->transfer == NULL) || (mydir != peer->direction))
1537 if(peer->direction == TRNSD_DOWN)
1540 if(peer->wcsname == NULL)
1545 peer->direction = mydir;
1546 if(peer->direction == TRNSD_UP)
1548 transfer = newupload(peer->fn, &dcnet, peer->wcsname, &dctransfer, peer);
1550 if((transfer = finddownload(peer->wcsname)) == NULL)
1555 transferattach(transfer, &dctransfer, peer);
1556 transfersetstate(transfer, TRNS_HS);
1558 transfersetnick(transfer, peer->wcsname);
1559 peer->transfer = transfer;
1562 qstrf(sk, "$Direction %s %i|", (peer->direction == TRNSD_UP)?"Upload":"Download", rand() % 10000);
1563 if(peer->key != NULL)
1564 qstrf(sk, "$Key %s|", peer->key);
1565 if(peer->direction == TRNSD_DOWN)
1570 static void cmd_peerlock(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1573 struct transfer *transfer;
1575 if((p = strchr(args, ' ')) == NULL)
1578 if(!strncmp(args, "EXTENDEDPROTOCOL", 16))
1580 key = dcmakekey(args);
1583 if(peer->wcsname == NULL)
1592 if((transfer = finddownload(peer->wcsname)) == NULL)
1594 peer->direction = TRNSD_UP;
1595 transfer = newupload(peer->fn, &dcnet, peer->wcsname, &dctransfer, peer);
1597 peer->direction = TRNSD_DOWN;
1598 transferattach(transfer, &dctransfer, peer);
1599 transfersetstate(transfer, TRNS_HS);
1601 transfersetnick(transfer, peer->wcsname);
1602 peer->transfer = transfer;
1603 qstrf(sk, "$Direction %s %i|", (peer->direction == TRNSD_UP)?"Upload":"Download", rand() % 10000);
1604 qstrf(sk, "$Key %s|", key);
1607 if(peer->key != NULL)
1613 static void cmd_key(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1618 static void startdl(struct dcpeer *peer)
1620 if(peer->timeout != NULL)
1621 canceltimer(peer->timeout);
1622 peer->state = PEER_TRNS;
1623 transferstartdl(peer->transfer, peer->sk);
1624 peer->sk->readcb = (void (*)(struct socket *, void *))transread;
1625 peer->sk->errcb = (void (*)(struct socket *, int, void *))transerr;
1628 static void startul(struct dcpeer *peer)
1630 if(peer->timeout != NULL)
1631 canceltimer(peer->timeout);
1632 peer->state = PEER_TRNS;
1633 transferstartul(peer->transfer, peer->sk);
1634 peer->sk->writecb = (void (*)(struct socket *, void *))transwrite;
1637 static void cmd_filelength(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1640 struct transfer *transfer;
1642 if(peer->transfer == NULL)
1648 if(peer->transfer->size != size)
1650 transfersetsize(peer->transfer, size);
1651 transfer = peer->transfer;
1653 trytransferbypeer(transfer->fnet, transfer->peerid);
1657 qstr(peer->sk, "$Send|");
1660 static void cmd_error(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1662 if(peer->fetchingtthl)
1664 peer->fetchingtthl = 0;
1669 if((peer->transfer != NULL) && (peer->transfer->dir == TRNSD_DOWN))
1671 transferseterror(peer->transfer, TRNSE_NOTFOUND);
1672 resettransfer(peer->transfer);
1678 static void cmd_maxedout(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1680 if((peer->transfer != NULL) && (peer->transfer->dir == TRNSD_DOWN))
1682 transferseterror(peer->transfer, TRNSE_NOSLOTS);
1683 resettransfer(peer->transfer);
1696 {"MyList.DcLst", &hmlistname, updatehmlist},
1697 {"files.xml", &xmllistname, updatexmllist},
1698 {"files.xml.bz2", &xmlbz2listname, updatexmlbz2list},
1702 static int openfilelist(char *name)
1707 for(i = 0; lists[i].name != NULL; i++)
1709 if(!strcmp(name, lists[i].name))
1713 if(lists[i].name == NULL)
1716 if((*lists[i].file == NULL) || ((fd = open(*lists[i].file, O_RDONLY)) < 0))
1718 if((fd < 0) && ((*lists[i].file == NULL) || ((fd = open(*lists[i].file, O_RDONLY)) < 0)))
1721 flog(LOG_ERR, "could not open filelist tempfile: %s", strerror(errno));
1728 static struct sharecache *findbytth(char *tth32)
1732 struct sharecache *node;
1734 if((buf = base32decode(tth32, &buflen)) == NULL)
1741 for(node = shareroot->child; node != NULL; node = nextscnode(node))
1743 if(node->f.b.hastth && !memcmp(node->hashtth, buf, 24))
1750 static struct sharecache *resdcpath(char *path, char *charset, char sep)
1752 struct sharecache *node;
1759 if((p2 = strchr(p, sep)) != NULL)
1761 if((node = findcache(node, icsmbstowcs(p, charset, L""))) == NULL)
1768 static void cmd_get(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1773 struct sharecache *node;
1774 struct socket *lesk;
1778 if(peer->transfer == NULL)
1783 if((p = strchr(args, '$')) == NULL)
1789 if((offset = (atoi(p) - 1)) < 0)
1794 if(((fd = openfilelist(args)) < 0) && (errno != 0))
1796 qstr(sk, "$Error Could not send file list|");
1799 } else if(fd >= 0) {
1800 if((buf2 = icsmbstowcs(args, DCCHARSET, NULL)) != NULL)
1801 transfersetpath(peer->transfer, buf2);
1802 peer->transfer->flags.b.minislot = 1;
1806 /* Use DCCHARSET in $Get paths until further researched... */
1807 if((node = resdcpath(args, DCCHARSET, '\\')) == NULL)
1809 qstrf(sk, "$Error File not in share|");
1813 if((fd = opensharecache(node)) < 0)
1815 qstrf(sk, "$Error %s|", strerror(errno));
1819 buf = getfspath(node);
1820 if((buf2 = icsmbstowcs(buf, NULL, NULL)) == NULL)
1821 flog(LOG_WARNING, "could not convert native path into a wcs (%s): %s", buf, strerror(errno));
1823 transfersetpath(peer->transfer, buf2);
1826 if(fstat(fd, &sb) < 0)
1829 flog(LOG_WARNING, "could not stat file %ls: %s", node->name, strerror(errno));
1830 qstrf(sk, "$Error|");
1834 if(sb.st_size < 65536)
1835 peer->transfer->flags.b.minislot = 1;
1836 if(!peer->transfer->flags.b.minislot && (slotsleft() < 1)) {
1838 qstr(sk, "$MaxedOut|");
1842 if((offset != 0) && (lseek(fd, offset, SEEK_SET) < 0))
1845 qstrf(sk, "$Error Offset out of range|");
1849 lesk = wrapsock(fd);
1850 transferprepul(peer->transfer, sb.st_size, offset, -1, lesk);
1852 qstrf(sk, "$FileLength %i|", peer->transfer->size);
1855 static void cmd_send(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1857 if(peer->transfer == NULL)
1862 if(peer->transfer->localend == NULL)
1871 static void cmd_supports(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1876 size_t arrsize, arrdata;
1878 if(peer->supports != NULL)
1880 for(i = 0; peer->supports[i] != NULL; i++)
1881 free(peer->supports[i]);
1882 free(peer->supports);
1885 arrsize = arrdata = 0;
1889 if((p2 = strchr(p, ' ')) != NULL)
1893 addtobuf(arr, sstrdup(p));
1894 } while((p = p2) != NULL);
1895 addtobuf(arr, NULL);
1896 peer->supports = arr;
1899 static void cmd_getblock(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
1903 int start, numbytes;
1904 char *charset, *buf;
1906 struct sharecache *node;
1908 struct socket *lesk;
1910 if(peer->transfer == NULL)
1916 if((p2 = strchr(p, ' ')) == NULL)
1924 if((p2 = strchr(p, ' ')) == NULL)
1932 if(!strcmp(cmd, "$UGetBlock") || !strcmp(cmd, "$UGetZBlock"))
1935 /* Use DCCHARSET in $Get paths until further researched... */
1936 charset = DCCHARSET;
1937 if(!strcmp(cmd, "$GetZBlock") || !strcmp(cmd, "$UGetZBlock"))
1938 initcompress(peer, CPRS_ZLIB);
1939 if(((fd = openfilelist(p)) < 0) && (errno != 0))
1941 qstr(sk, "$Error Could not send file list|");
1943 } else if(fd >= 0) {
1944 if((buf2 = icsmbstowcs(args, charset, NULL)) != NULL)
1945 transfersetpath(peer->transfer, buf2);
1946 peer->transfer->flags.b.minislot = 1;
1950 if((node = resdcpath(p, charset, '\\')) == NULL)
1952 qstr(sk, "$Error File not in cache|");
1955 if((fd = opensharecache(node)) < 0)
1957 qstrf(sk, "$Error %s|", strerror(errno));
1960 buf = getfspath(node);
1961 if((buf2 = icsmbstowcs(buf, NULL, NULL)) == NULL)
1962 flog(LOG_WARNING, "could not convert native path into a wcs (%s): %s", buf, strerror(errno));
1964 transfersetpath(peer->transfer, buf2);
1967 if(fstat(fd, &sb) < 0)
1970 flog(LOG_WARNING, "could not stat file %ls: %s", node->name, strerror(errno));
1971 qstr(sk, "$Error|");
1974 if(sb.st_size < 65536)
1975 peer->transfer->flags.b.minislot = 1;
1976 if(!peer->transfer->flags.b.minislot && (slotsleft() < 1)) {
1978 qstr(sk, "$MaxedOut|");
1981 if((start != 0) && ((start >= sb.st_size) || (lseek(fd, start, SEEK_SET) < 0)))
1984 qstr(sk, "$Error Offset out of range|");
1987 if((numbytes < 0) || (start + numbytes > sb.st_size))
1988 numbytes = sb.st_size - start;
1989 lesk = wrapsock(fd);
1990 transferprepul(peer->transfer, sb.st_size, start, start + numbytes, lesk);
1992 qstrf(sk, "$Sending %i|", numbytes);
1996 static void cmd_adcget(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2000 int start, numbytes;
2001 struct sharecache *node;
2003 struct socket *lesk;
2007 if(peer->transfer == NULL)
2012 if((argv = parseadc(args)) == NULL)
2017 if(parrlen(argv) < 4)
2022 start = atoi(argv[2]);
2023 numbytes = atoi(argv[3]);
2026 if(((fd = openfilelist(argv[1])) < 0) && (errno != 0))
2028 qstr(sk, "$Error Could not send file list|");
2030 } else if(fd >= 0) {
2031 if((wbuf = icsmbstowcs(argv[1], "UTF-8", NULL)) != NULL)
2032 transfersetpath(peer->transfer, wbuf);
2033 peer->transfer->flags.b.minislot = 1;
2037 if(!strncmp(argv[1], "TTH/", 4))
2039 if((node = findbytth(argv[1] + 4)) == NULL)
2041 qstr(sk, "$Error File not in cache|");
2045 if((node = resdcpath((argv[1][0] == '/')?(argv[1] + 1):(argv[1]), "UTF-8", '/')) == NULL)
2047 qstr(sk, "$Error File not in cache|");
2051 if((fd = opensharecache(node)) < 0)
2053 qstrf(sk, "$Error %s|", strerror(errno));
2056 buf = getfspath(node);
2057 if((wbuf = icsmbstowcs(buf, NULL, NULL)) == NULL)
2058 flog(LOG_WARNING, "could not convert native path into a wcs (%s): %s", buf, strerror(errno));
2060 transfersetpath(peer->transfer, wbuf);
2063 if(!strcmp(argv[0], "file"))
2065 for(i = 4; argv[i] != NULL; i++)
2067 if(!strcmp(argv[i], "ZL1"))
2068 initcompress(peer, CPRS_ZLIB);
2070 if(fstat(fd, &sb) < 0)
2072 flog(LOG_WARNING, "could not stat file %ls: %s", node->name, strerror(errno));
2073 qstr(sk, "$Error|");
2076 if(sb.st_size < 65536)
2077 peer->transfer->flags.b.minislot = 1;
2078 if(!peer->transfer->flags.b.minislot && (slotsleft() < 1)) {
2079 qstr(sk, "$MaxedOut|");
2082 if((start != 0) && ((start >= sb.st_size) || (lseek(fd, start, SEEK_SET) < 0)))
2084 qstr(sk, "$Error Offset out of range|");
2087 if((numbytes < 0) || (start + numbytes > sb.st_size))
2088 numbytes = sb.st_size - start;
2089 lesk = wrapsock(fd);
2090 transferprepul(peer->transfer, sb.st_size, start, start + numbytes, lesk);
2093 qstr(sk, "$ADCSND");
2094 sendadc(sk, "file");
2095 sendadc(sk, argv[1]);
2096 sendadcf(sk, "%i", start);
2097 sendadcf(sk, "%i", numbytes);
2098 if(peer->compress == CPRS_ZLIB)
2102 } else if(!strcmp(argv[0], "tthl")) {
2104 * XXX: Implement full TTHL support.
2106 * In the meantime, this is better than nothing, since it at
2107 * least allows fetching of the TTH root if it isn't already
2112 qstr(sk, "$Error no TTHL data for virtual files|");
2115 qstr(sk, "$ADCSND");
2116 sendadc(sk, "tthl");
2117 sendadc(sk, argv[1]);
2121 sockqueue(sk, node->hashtth, 24);
2123 qstr(sk, "$Error Namespace not implemented|");
2133 static void handletthl(struct dcpeer *peer)
2137 while(peer->inbufdata >= 24)
2139 pushtigertree(&peer->tth, peer->inbuf);
2140 memmove(peer->inbuf, peer->inbuf + 24, peer->inbufdata -= 24);
2141 peer->curread += 24;
2143 if(peer->curread >= peer->totalsize)
2145 if(peer->timeout == NULL)
2146 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
2147 peer->state = PEER_CMD;
2148 synctigertree(&peer->tth);
2149 restigertree(&peer->tth, buf);
2150 transfersethash(peer->transfer, newhash(L"TTH", 24, buf));
2155 static void cmd_adcsnd(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2158 int start, numbytes;
2160 if(peer->transfer == NULL)
2165 if((argv = parseadc(args)) == NULL)
2170 if(parrlen(argv) < 4)
2175 start = atoi(argv[2]);
2176 numbytes = atoi(argv[3]);
2177 if(!strcmp(argv[0], "tthl"))
2179 if((start != 0) || (numbytes % 24 != 0))
2181 /* Weird. Bail out. */
2185 if(peer->timeout != NULL)
2186 canceltimer(peer->timeout);
2187 peer->state = PEER_TTHL;
2188 peer->totalsize = numbytes;
2190 peer->fetchingtthl = 0;
2191 inittigertree(&peer->tth);
2193 } else if(!strcmp(argv[0], "file")) {
2194 if(start != peer->transfer->curpos)
2199 if(start + numbytes != peer->transfer->size)
2201 transfersetsize(peer->transfer, start + numbytes);
2206 if(peer->inbufdata > 0)
2208 sockpushdata(sk, peer->inbuf, peer->inbufdata);
2209 peer->inbufdata = 0;
2210 transread(sk, peer);
2213 /* We certainly didn't request this...*/
2222 static void cmd_sending(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2226 if(peer->transfer == NULL)
2231 numbytes = atoi(args);
2232 if(peer->transfer->size - peer->transfer->curpos != numbytes)
2234 transfersetsize(peer->transfer, peer->transfer->curpos + numbytes);
2239 if(peer->inbufdata > 0)
2241 sockpushdata(sk, peer->inbuf, peer->inbufdata);
2242 peer->inbufdata = 0;
2243 transread(sk, peer);
2249 static void cmd_(struct socket *sk, struct fnetnode *fn, char *cmd, char *args)
2254 hubhandleaction(sk, fn, cmd, args);
2258 static void cmd_(struct socket *sk, struct dcpeer *peer, char *cmd, char *args)
2264 static int hubreqconn(struct fnetpeer *peer)
2269 if((peer->fn->state != FNN_EST) || (peer->fn->fnet != &dcnet))
2274 if((hub = peer->fn->data) == NULL)
2279 if((mbsnick = icwcstombs(peer->id, hub->charset)) == NULL)
2280 return(1); /* Shouldn't happen, of course, but who knows... */
2283 sendctm(peer->fn->sk, mbsnick);
2284 expectpeer(mbsnick, peer->fn);
2286 qstrf(peer->fn->sk, "$RevConnectToMe %s %s|", hub->nativenick, mbsnick);
2292 static int hubsendchat(struct fnetnode *fn, int public, wchar_t *to, wchar_t *string)
2295 char *mbsstring, *mbsto;
2298 if((mbsto = icwcstombs(to, hub->charset)) == NULL)
2303 if((mbsstring = icwcstombs(string, hub->charset)) == NULL)
2308 if((strchr(mbsto, '|') != NULL) || (strchr(mbsto, ' ') != NULL))
2315 if(strchr(mbsstring, '|') != NULL)
2326 qstrf(fn->sk, "<%s> %s|", hub->nativenick, mbsstring);
2328 qstrf(fn->sk, "$To: %s From: %s $<%s> %s|", mbsto, hub->nativenick, hub->nativenick, mbsstring);
2331 qstrf(fn->sk, "$To: %s From: %s $<%s> %s|", mbsto, hub->nativenick, hub->nativenick, mbsstring);
2338 static void findsizelimit(struct sexpr *sexpr, int *min, int *max)
2340 int minl, maxl, minr, maxr, retmin, retmax;
2345 findsizelimit(sexpr->l, &minl, &maxl);
2346 findsizelimit(sexpr->r, &minr, &maxr);
2347 retmin = (minl > minr)?minl:minr;
2348 if((maxl != -1) && (maxr != -1))
2349 retmax = (maxl < maxr)?maxl:maxr;
2358 findsizelimit(sexpr->l, &minl, &maxl);
2359 findsizelimit(sexpr->r, &minr, &maxr);
2360 retmin = (minl < minr)?minl:minr;
2361 if((maxl == -1) || (maxr == -1))
2364 retmax = (maxl > maxr)?maxl:maxr;
2367 findsizelimit(sexpr->l, &minl, &maxl);
2368 if((minl == 0) && (maxl == -1)) /* Interval is unspecified */
2372 } else if((minl == 0) && (maxl != -1)) {
2375 } else if((minl != 0) && (maxl == -1)) {
2378 } else { /* This would yield two seperate intervals, which DC cannot handle */
2384 retmax = sexpr->d.n - 1;
2387 retmin = sexpr->d.n;
2388 retmax = sexpr->d.n;
2391 retmin = sexpr->d.n + 1;
2405 static struct hash *findsehash(struct sexpr *sexpr)
2407 struct hash *h1, *h2;
2412 if((h1 = findsehash(sexpr->l)) != NULL)
2414 if((h1 = findsehash(sexpr->r)) != NULL)
2418 h1 = findsehash(sexpr->l);
2419 h2 = findsehash(sexpr->r);
2424 if(!wcscmp(sexpr->d.hash->algo, L"TTH"))
2425 return(sexpr->d.hash);
2432 static int hubsearch(struct fnetnode *fn, struct search *srch, struct srchfnnlist *ln)
2435 struct wcslist *list, *cur;
2436 char *sstr, *buf, *p;
2437 size_t sstrsize, sstrdata;
2438 struct sockaddr *name;
2440 int minsize, maxsize;
2444 if((fn->state != FNN_EST) || (fn->sk == NULL) || (fn->sk->state != SOCK_EST))
2446 list = findsexprstrs(srch->sexpr);
2447 findsizelimit(srch->sexpr, &minsize, &maxsize);
2448 hash = findsehash(srch->sexpr);
2449 if((minsize != 0) && (maxsize != -1))
2451 /* Choose either minsize or maxsize by trying to determine
2452 * which choice will be most restrictive. The result can be
2453 * approximative at best anyway, so don't try too hard... */
2454 if((50000000 - maxsize) > (minsize - 50000000))
2460 sstrsize = sstrdata = 0;
2461 if((hash != NULL) && (hash->len == 24))
2463 /* Prioritize hash searches above all else */
2464 bufcat(sstr, "F?T?0?9?TTH:", 12);
2465 buf = base32encode(hash->buf, hash->len);
2467 bufcat(sstr, buf, 39);
2472 sizebuf2(sstr, sstrdata + 32, 1);
2473 sstrdata += snprintf(sstr + sstrdata, sstrsize - sstrdata, "T?F?%i?1?", minsize);
2474 } else if(maxsize != -1) {
2475 sizebuf2(sstr, sstrdata + 32, 1);
2476 sstrdata += snprintf(sstr + sstrdata, sstrsize - sstrdata, "T?T?%i?1?", maxsize);
2478 bufcat(sstr, "F?F?0?1?", 8);
2482 for(cur = list; cur != NULL; cur = cur->next)
2484 /* Use DCCHARSET in $Get paths until further researched... */
2485 if((buf = icwcstombs(cur->str, DCCHARSET)) == NULL)
2487 /* Can't find anything anyway if the search expression
2488 * requires characters outside DC's charset. There's
2489 * nothing technically wrong with the search itself,
2490 * however, so return success. This should be
2491 * considered as an optimization. */
2498 addtobuf(sstr, '$');
2500 * It probably doesn't hurt if buf contains any extra
2501 * dollar signs - it will just result in extra search
2502 * terms, and the extraneous results will be filtered by
2503 * the search layer anyway. It hurts if it contains any
2504 * pipes, though, so let's sell them for money.
2506 for(p = buf; *p; p++)
2511 bufcat(sstr, buf, strlen(buf));
2515 /* Will match all files... :-/ */
2516 addtobuf(sstr, '.');
2522 if(sockgetremotename2(udpsock, fn->sk, &name, &namelen) < 0)
2524 flog(LOG_WARNING, "cannot get address of UDP socket");
2526 qstrf(fn->sk, "$Search %s %s|", formataddress(name, namelen), sstr);
2530 qstrf(fn->sk, "$Search Hub:%s %s|", hub->nativenick, sstr);
2534 fn->lastsrch = time(NULL);
2542 #define cc(c) ((void (*)(struct socket *, void *, char *, char *))(c))
2543 static struct command hubcmds[] =
2545 {"$Lock", cc(cmd_lock)},
2546 {"$HubName", cc(cmd_hubname)},
2547 {"$Hello", cc(cmd_hello)},
2548 {"$Quit", cc(cmd_quit)},
2549 {"$NickList", cc(cmd_nicklist)},
2550 {"$OpList", cc(cmd_oplist)},
2551 {"$MyINFO", cc(cmd_myinfo)},
2552 {"$ForceMove", cc(cmd_forcemove)},
2553 {"$Search", cc(cmd_search)},
2554 {"$MultiSearch", cc(cmd_search)},
2555 {"$ConnectToMe", cc(cmd_connecttome)},
2556 {"$RevConnectToMe", cc(cmd_revconnecttome)},
2557 {"$GetNetInfo", cc(cmd_getnetinfo)},
2558 {"$To:", cc(cmd_to)},
2559 {"$SR", cc(cmd_sr)},
2560 {"$UserCommand", cc(cmd_usercommand)},
2561 {"$GetPass", cc(cmd_getpass)},
2562 {"$LogedIn", cc(cmd_logedin)}, /* sic */
2566 static struct command peercmds[] =
2568 {"$MyNick", cc(cmd_mynick)},
2569 {"$Lock", cc(cmd_peerlock)},
2570 {"$Direction", cc(cmd_direction)},
2571 {"$Key", cc(cmd_key)},
2572 {"$FileLength", cc(cmd_filelength)},
2573 {"$Error", cc(cmd_error)},
2574 {"$MaxedOut", cc(cmd_maxedout)},
2575 {"$Get", cc(cmd_get)},
2576 {"$Send", cc(cmd_send)},
2577 {"$Supports", cc(cmd_supports)},
2578 {"$GetBlock", cc(cmd_getblock)},
2579 {"$UGetBlock", cc(cmd_getblock)},
2580 {"$GetZBlock", cc(cmd_getblock)},
2581 {"$UGetZBlock", cc(cmd_getblock)},
2582 {"$ADCGET", cc(cmd_adcget)},
2583 {"$ADCSND", cc(cmd_adcsnd), 1},
2584 {"$Sending", cc(cmd_sending), 1},
2589 static void dctransdetach(struct transfer *transfer, struct dcpeer *peer)
2591 CBUNREG(transfer, trans_filterout, peer);
2594 peer->transfer = NULL;
2598 static void dctransgotdata(struct transfer *transfer, struct dcpeer *peer)
2602 unsigned char outbuf[1024];
2606 if((peer->state == PEER_TRNS) || (peer->state == PEER_SYNC))
2608 if(sockqueuesize(peer->sk) < 65536)
2610 if((buf = transfergetdata(transfer, &bufsize)) != NULL)
2612 if(peer->compress == CPRS_NONE)
2614 sockqueue(peer->sk, buf, bufsize);
2615 } else if(peer->compress == CPRS_ZLIB) {
2616 cstr = peer->cprsdata;
2617 cstr->next_in = buf;
2618 cstr->avail_in = bufsize;
2619 while(cstr->avail_in > 0)
2621 cstr->next_out = outbuf;
2622 cstr->avail_out = sizeof(outbuf);
2623 if((ret = deflate(cstr, 0)) != Z_OK)
2625 flog(LOG_WARNING, "bug? deflate() did not return Z_OK (but rather %i)", ret);
2629 sockqueue(peer->sk, outbuf, sizeof(outbuf) - cstr->avail_out);
2634 if(peer->state == PEER_SYNC)
2636 if(peer->compress == CPRS_ZLIB)
2638 cstr = peer->cprsdata;
2639 cstr->next_in = NULL;
2643 cstr->next_out = outbuf;
2644 cstr->avail_out = sizeof(outbuf);
2645 ret = deflate(cstr, Z_FINISH);
2646 if((ret != Z_OK) && (ret != Z_STREAM_END))
2648 flog(LOG_WARNING, "bug? deflate(Z_FINISH) did not return Z_OK (but rather %i)", ret);
2652 sockqueue(peer->sk, outbuf, sizeof(outbuf) - cstr->avail_out);
2653 } while(ret != Z_STREAM_END);
2659 if(peer->timeout == NULL)
2660 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
2661 peer->state = PEER_CMD;
2663 transfersetstate(transfer, TRNS_HS);
2664 socksettos(peer->sk, confgetint("fnet", "fnptos"));
2665 transfer->flags.b.minislot = 0;
2666 peer->sk->writecb = NULL;
2673 static void dctransendofdata(struct transfer *transfer, struct dcpeer *peer)
2675 peer->state = PEER_SYNC;
2676 dctransgotdata(transfer, peer);
2679 static void dcwantdata(struct transfer *transfer, struct dcpeer *peer)
2681 if(transferdatasize(transfer) < 65536)
2682 peer->sk->ignread = 0;
2685 static void transread(struct socket *sk, struct dcpeer *peer)
2689 struct transfer *transfer;
2691 if((buf = sockgetinbuf(sk, &bufsize)) == NULL)
2693 if(peer->transfer == NULL)
2699 transferputdata(peer->transfer, buf, bufsize);
2701 if(peer->transfer->curpos >= peer->transfer->size)
2703 transfer = peer->transfer;
2704 transferdetach(transfer);
2705 transferendofdata(transfer);
2708 if(transferdatasize(peer->transfer) > 65535)
2712 static void transerr(struct socket *sk, int err, struct dcpeer *peer)
2714 struct transfer *transfer;
2716 if((transfer = peer->transfer) == NULL)
2721 transferdetach(transfer);
2722 transferendofdata(transfer);
2725 static void transwrite(struct socket *sk, struct dcpeer *peer)
2727 if((peer->state != PEER_TRNS) && (peer->state != PEER_SYNC))
2729 if(peer->transfer == NULL)
2734 dctransgotdata(peer->transfer, peer);
2737 static void udpread(struct socket *sk, void *data)
2739 char *buf, *p, *p2, *hashbuf;
2740 size_t buflen, hashlen;
2741 char *nick, *filename, *hubname;
2742 struct sockaddr_in hubaddr;
2744 struct fnetnode *fn, *myfn;
2747 wchar_t *wnick, *wfile;
2750 if((buf = sockgetinbuf(sk, &buflen)) == NULL)
2752 buf = srealloc(buf, buflen + 1);
2754 if(!strncmp(buf, "$SR ", 4))
2758 if((p2 = strchr(p, ' ')) == NULL)
2766 if((p2 = strchr(p, 5)) == NULL)
2773 if((p2 = strchr(p, ' ')) == NULL)
2781 if((p2 = strchr(p, '/')) == NULL)
2789 if((p2 = strchr(p, 5)) == NULL)
2796 if((p2 = strstr(p, " (")) == NULL)
2803 if((p2 = strchr(p, ':')) == NULL)
2809 hubaddr.sin_family = AF_INET;
2810 if(!inet_aton(p, &hubaddr.sin_addr))
2816 if((p2 = strchr(p, ')')) == NULL)
2822 hubaddr.sin_port = htons(atoi(p));
2823 /* Use DCCHARSET in $Get paths until further researched... */
2824 if((wfile = icmbstowcs(filename, DCCHARSET)) == NULL)
2831 if(!strncmp(hubname, "TTH:", 4))
2833 if((hashbuf = base32decode(hubname + 4, &hashlen)) != NULL)
2836 hash = newhash(L"TTH", 24, hashbuf);
2840 for(fn = fnetnodes; fn != NULL; fn = fn->next)
2842 if((fn->fnet == &dcnet) && ((hub = fn->data) != NULL))
2844 if((hub->nativename != NULL) && !strcmp(hub->nativename, hubname))
2859 for(fn = fnetnodes; fn != NULL; fn = fn->next)
2861 if((fn->fnet == &dcnet) && (fn->sk != NULL) && addreq(fn->sk->remote, (struct sockaddr *)&hubaddr))
2871 if((wnick = icmbstowcs(nick, (hub == NULL)?DCCHARSET:(hub->charset))) == NULL)
2876 sr = newsrchres(&dcnet, wfile, wnick);
2877 if(sr->peernick != NULL)
2879 sr->peernick = swcsdup(wnick);
2885 getfnetnode(sr->fn = myfn);
2894 static void hubread(struct socket *sk, struct fnetnode *fn)
2901 hub = (struct dchub *)fn->data;
2902 if((newbuf = sockgetinbuf(sk, &datalen)) == NULL)
2904 if(hub->inbufdata > 500000) /* Discard possible malicious data */
2906 sizebuf2(hub->inbuf, hub->inbufdata + datalen, 1);
2907 memcpy(hub->inbuf + hub->inbufdata, newbuf, datalen);
2909 p = hub->inbuf + hub->inbufdata;
2910 hub->inbufdata += datalen;
2911 while((datalen > 0) && ((p = memchr(p, '|', datalen)) != NULL))
2914 newqcmd(&hub->queue, hub->inbuf);
2915 memmove(hub->inbuf, p, hub->inbufdata -= p - hub->inbuf);
2916 datalen = hub->inbufdata;
2921 static void huberr(struct socket *sk, int err, struct fnetnode *fn)
2926 static int hubsetnick(struct fnetnode *fn, wchar_t *newnick)
2932 if((buf = icwcstombs(newnick, (hub == NULL)?DCCHARSET:(hub->charset))) == NULL)
2934 if((strchr(buf, ' ') != NULL) || (strchr(buf, '|') != NULL) || (strchr(buf, '$') != NULL))
2939 if(hub == NULL) /* Not yet connected */
2944 if(hub->nativenick != NULL)
2945 free(hub->nativenick);
2946 hub->nativenick = buf;
2950 static struct dchub *newdchub(struct fnetnode *fn)
2957 new = smalloc(sizeof(*new));
2958 memset(new, 0, sizeof(*new));
2960 if(confgetint("dc", "dcppemu"))
2962 if((emu = wpfind(fn->args, L"dcppemu")) != NULL)
2970 if((wcharset = wpfind(fn->args, L"charset")) != NULL)
2972 if((charset = icwcstombs(wcharset, "US-ASCII")) != NULL)
2974 if(!havecharset(charset))
2982 new->charset = charset;
2984 new->charset = sstrdup(DCCHARSET);
2985 if(hubsetnick(fn, fn->mynick))
2986 fnetsetnick(fn, L"DoldaConnectUser-IN");
2987 /* IN as in Invalid Nick */
2991 static struct dcpeer *newdcpeer(struct socket *sk)
2995 new = smalloc(sizeof(*new));
2996 memset(new, 0, sizeof(*new));
2997 new->transfer = NULL;
3000 if(confgetint("dc", "dcppemu"))
3011 static void freedcpeer(struct dcpeer *peer)
3014 struct qcommand *qcmd;
3019 if(peer->next != NULL)
3020 peer->next->prev = peer->prev;
3021 if(peer->prev != NULL)
3022 peer->prev->next = peer->next;
3023 if(peer->transfer != NULL)
3025 if(peer->transfer->dir == TRNSD_UP)
3026 peer->transfer->close = 1;
3027 if(peer->transfer->dir == TRNSD_DOWN)
3028 resettransfer(peer->transfer);
3029 transferdetach(peer->transfer);
3031 if(peer->timeout != NULL)
3032 canceltimer(peer->timeout);
3033 if(peer->sk->data == peer)
3034 peer->sk->data = NULL;
3035 peer->sk->readcb = NULL;
3036 peer->sk->writecb = NULL;
3037 peer->sk->errcb = NULL;
3040 if(peer->supports != NULL)
3042 for(i = 0; peer->supports[i] != NULL; i++)
3043 free(peer->supports[i]);
3044 free(peer->supports);
3046 if(peer->inbuf != NULL)
3048 if(peer->key != NULL)
3050 if(peer->wcsname != NULL)
3051 free(peer->wcsname);
3052 if(peer->nativename != NULL)
3053 free(peer->nativename);
3054 if(peer->charset != NULL)
3055 free(peer->charset);
3056 if(peer->fn != NULL)
3057 putfnetnode(peer->fn);
3058 while((qcmd = ulqcmd(&peer->queue)) != NULL)
3064 static void hubconnect(struct fnetnode *fn)
3066 fn->sk->readcb = (void (*)(struct socket *, void *))hubread;
3067 fn->sk->errcb = (void (*)(struct socket *, int, void *))huberr;
3069 fn->data = newdchub(fn);
3074 static void hubdestroy(struct fnetnode *fn)
3077 struct qcommand *qcmd;
3079 hub = (struct dchub *)fn->data;
3080 if((fn->sk != NULL) && (fn->sk->data == fn))
3082 fn->sk->data = NULL;
3087 while((qcmd = ulqcmd(&hub->queue)) != NULL)
3089 if(hub->nativename != NULL)
3090 free(hub->nativename);
3091 if(hub->nativenick != NULL)
3092 free(hub->nativenick);
3093 if(hub->charset != NULL)
3095 if(hub->inbuf != NULL)
3100 static wchar_t *dcbasename(wchar_t *filename)
3104 if((ret = wcsrchr(filename, L'\\')) != NULL)
3109 static struct transferiface dctransfer =
3111 .detach = (void (*)(struct transfer *, void *))dctransdetach,
3112 .gotdata = (void (*)(struct transfer *, void *))dctransgotdata,
3113 .endofdata = (void (*)(struct transfer *, void *))dctransendofdata,
3114 .wantdata = (void (*)(struct transfer *, void *))dcwantdata
3117 static struct fnet dcnet =
3120 .connect = hubconnect,
3121 .destroy = hubdestroy,
3122 .setnick = hubsetnick,
3123 .reqconn = hubreqconn,
3124 .sendchat = hubsendchat,
3125 .search = hubsearch,
3126 .filebasename = dcbasename
3129 static void peerread(struct socket *sk, struct dcpeer *peer)
3133 struct command *cmd;
3135 if((newbuf = sockgetinbuf(sk, &datalen)) == NULL)
3137 sizebuf2(peer->inbuf, peer->inbufdata + datalen, 1);
3138 memcpy(peer->inbuf + peer->inbufdata, newbuf, datalen);
3140 peer->inbufdata += datalen;
3141 if(peer->state == PEER_CMD)
3144 while((peer->inbufdata > 0) && (p = memchr(peer->inbuf, '|', peer->inbufdata)) != NULL)
3147 newqcmd(&peer->queue, peer->inbuf);
3148 for(cmd = peercmds; cmd->handler != NULL; cmd++)
3150 if(!memcmp(peer->inbuf, cmd->name, strlen(cmd->name)) && ((peer->inbuf[strlen(cmd->name)] == ' ') || (peer->inbuf[strlen(cmd->name)] == '|')))
3153 memmove(peer->inbuf, p, peer->inbufdata -= p - peer->inbuf);
3156 peer->state = PEER_STOP;
3160 } else if(peer->state == PEER_TTHL) {
3165 static void peererror(struct socket *sk, int err, struct dcpeer *peer)
3170 static void peerconnect(struct socket *sk, int err, struct fnetnode *fn)
3172 struct dcpeer *peer;
3182 peer = newdcpeer(sk);
3185 peer->dcppemu = hub->dcppemu;
3186 sk->readcb = (void (*)(struct socket *, void *))peerread;
3187 sk->errcb = (void (*)(struct socket *, int, void *))peererror;
3189 socksettos(sk, confgetint("fnet", "fnptos"));
3191 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
3196 static void peeraccept(struct socket *sk, struct socket *newsk, void *data)
3198 struct dcpeer *peer;
3200 peer = newdcpeer(newsk);
3202 newsk->readcb = (void (*)(struct socket *, void *))peerread;
3203 newsk->errcb = (void (*)(struct socket *, int, void *))peererror;
3205 socksettos(newsk, confgetint("fnet", "fnptos"));
3206 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
3209 static void updatehmlist(void)
3211 int i, lev, ic, ret;
3212 struct sharecache *node;
3213 char *buf, *buf2, numbuf[32];
3214 size_t bufsize, bufdata;
3218 buf = smalloc(bufsize = 65536);
3219 node = shareroot->child;
3224 /* Use DCCHARSET in $Get paths until further researched... */
3225 if((buf2 = icwcstombs(node->name, DCCHARSET)) != NULL)
3227 for(i = 0; i < lev; i++)
3229 bufcat(buf, buf2, strlen(buf2));
3231 if(node->f.b.type == FILE_REG)
3234 sprintf(numbuf, "%i", node->size);
3235 bufcat(buf, numbuf, strlen(numbuf));
3242 if((node->child != NULL) && !ic)
3246 } else if(node->next != NULL) {
3249 while(node->next == NULL)
3252 node = node->parent;
3253 if(node == shareroot)
3256 if(node == shareroot)
3261 if(hmlistname != NULL)
3266 hmlistname = sstrdup("/tmp/dc-filelist-hm-XXXXXX");
3267 if((fd = mkstemp(hmlistname)) < 0)
3269 flog(LOG_WARNING, "could not create HM file list tempfile: %s", strerror(errno));
3274 * I do not want to implement a good Huffman encoder, and it's not
3275 * like Huffman encoding actually yields any impressive results
3276 * for DC file lists anyway, so I'll just output a bogus
3277 * tree. Implement a good encoder if you want to.
3279 write(fd, "HE3\r\0", 5);
3280 write(fd, &bufdata, 4);
3282 write(fd, &ibuf, 2);
3284 for(i = 0; i < 256; i++)
3287 write(fd, &ibuf, 1);
3289 for(i = 0; i < 256; i++)
3291 for(buf2 = buf; bufdata > 0;)
3293 if((ret = write(fd, buf2, bufdata)) < 0)
3295 flog(LOG_WARNING, "could not write file list: %s", strerror(errno));
3306 static struct xmlent
3313 /* {L'\'', L"""}, Emulate DC++ escaping by omitting this. */
3317 static wchar_t *escapexml(wchar_t *src)
3319 static wchar_t *buf = NULL;;
3322 size_t bufsize, bufdata;
3328 bufsize = bufdata = 0;
3329 for(; *src != L'\0'; src++)
3332 if((c > 0) && (c < 32))
3334 bufcat(buf, L"&#", 2);
3335 ret = swprintf(nbuf, (sizeof(nbuf) / sizeof(*nbuf)), L"%i", c);
3336 bufcat(buf, nbuf, ret);
3337 addtobuf(buf, L';');
3339 for(ent = entities; ent->ent != NULL; ent++)
3343 bufcat(buf, ent->ent, wcslen(ent->ent));
3347 if(ent->ent == NULL)
3348 addtobuf(buf, *src);
3351 addtobuf(buf, L'\0');
3355 static void updatexmllist(void)
3359 char cidbuf[14], *namebuf;
3361 struct sharecache *node;
3363 if(xmllistname != NULL)
3365 unlink(xmllistname);
3368 xmllistname = sstrdup("/tmp/dc-filelist-dcxml-XXXXXX");
3369 if((fd = mkstemp(xmllistname)) < 0)
3371 flog(LOG_WARNING, "could not create XML file list tempfile: %s", strerror(errno));
3376 if((fs = fdopen(fd, "w")) == NULL)
3378 flog(LOG_WARNING, "could not fdopen XML list fd %i: %s", fd, strerror(errno));
3379 unlink(xmllistname);
3385 fprintf(fs, "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?>\r\n");
3386 for(i = 0; i < sizeof(cidbuf) - 1; i++)
3387 cidbuf[i] = (rand() % ('Z' - 'A' + 1)) + 'A';
3389 if(confgetint("dc", "dcppemu"))
3390 fprintf(fs, "<FileListing Version=\"1\" CID=\"%s\" Base=\"/\" Generator=\"DC++ 0.674\">\r\n", cidbuf);
3392 fprintf(fs, "<FileListing Version=\"1\" CID=\"%s\" Base=\"/\" Generator=\"%s\">\r\n", cidbuf, "DoldaConnect" VERSION);
3394 node = shareroot->child;
3398 if((namebuf = icswcstombs(escapexml(node->name), "UTF-8", NULL)) != NULL)
3400 for(i = 0; i < lev; i++)
3402 if(node->child != NULL)
3404 fprintf(fs, "<Directory Name=\"%s\">\r\n", namebuf);
3409 fprintf(fs, "<File Name=\"%s\" Size=\"%i\"", namebuf, node->size);
3410 if(node->f.b.hastth)
3412 hashbuf = base32encode(node->hashtth, 24);
3413 fprintf(fs, " TTH=\"%.39s\"", hashbuf);
3416 fprintf(fs, "/>\r\n");
3418 while(node->next == NULL)
3420 node = node->parent;
3421 if(node == shareroot)
3426 for(i = 0; i < lev; i++)
3428 fprintf(fs, "</Directory>\r\n");
3431 if(node == shareroot)
3437 if(confgetint("dc", "dcppemu"))
3438 fprintf(fs, "</FileListing>");
3440 fprintf(fs, "</FileListing>\r\n");
3444 static void updatexmlbz2list(void)
3453 if(xmllistname == NULL)
3455 if((in = fopen(xmllistname, "r")) == NULL)
3457 flog(LOG_WARNING, "could not open XML file list for bzipping: %s", strerror(errno));
3460 if(xmlbz2listname != NULL)
3462 unlink(xmlbz2listname);
3463 free(xmlbz2listname);
3465 xmlbz2listname = sstrdup("/tmp/dc-filelist-dcxmlbz2-XXXXXX");
3466 if((fd = mkstemp(xmlbz2listname)) < 0)
3468 flog(LOG_WARNING, "could not create bzipped XML file list tempfile: %s", strerror(errno));
3469 free(xmlbz2listname);
3470 xmlbz2listname = NULL;
3474 if((real = fdopen(fd, "w")) == NULL)
3476 flog(LOG_WARNING, "could not fdopen bzipped XML list fd %i: %s", fd, strerror(errno));
3478 unlink(xmlbz2listname);
3479 free(xmlbz2listname);
3480 xmlbz2listname = NULL;
3484 out = BZ2_bzWriteOpen(&err, real, 9, 0, 0);
3487 flog(LOG_WARNING, "could not open bzip2 stream from XML list");
3489 unlink(xmlbz2listname);
3490 free(xmlbz2listname);
3491 xmlbz2listname = NULL;
3497 bufdata = fread(buf, 1, sizeof(buf), in);
3498 BZ2_bzWrite(&err, out, buf, bufdata);
3501 BZ2_bzWriteClose(&err, out, 0, NULL, NULL);
3505 static int shareupdate(unsigned long long uusharesize, void *data)
3513 static void dispatchcommand(struct qcommand *qcmd, struct command *cmdlist, struct socket *sk, void *data)
3516 struct command *cmd;
3518 if((p = strchr(qcmd->string, ' ')) != NULL)
3520 for(cmd = cmdlist; cmd->handler != NULL; cmd++)
3522 if(!strcmp(cmd->name, qcmd->string))
3525 if(cmd->handler != NULL)
3526 cmd->handler(sk, data, qcmd->string, p);
3529 flog(LOG_DEBUG, "Unimplemented DC command: %s \"%s\"", qcmd->string, p?p:"noargs");
3533 static int run(void)
3535 struct fnetnode *fn, *nextfn;
3537 struct dcpeer *peer, *nextpeer;
3538 struct qcommand *qcmd;
3542 for(fn = fnetnodes; fn != NULL; fn = nextfn)
3545 if(fn->fnet != &dcnet)
3547 if(fn->data == NULL)
3549 hub = (struct dchub *)fn->data;
3550 if((qcmd = ulqcmd(&hub->queue)) != NULL)
3552 if(*qcmd->string == '$')
3554 if((fn->sk != NULL) && (fn->sk->state == SOCK_EST))
3555 dispatchcommand(qcmd, hubcmds, fn->sk, fn);
3556 } else if(*qcmd->string != 0) {
3557 hubrecvchat(fn->sk, fn, NULL, qcmd->string);
3564 for(peer = peers; peer != NULL; peer = nextpeer)
3566 nextpeer = peer->next;
3567 if((qcmd = ulqcmd(&peer->queue)) != NULL)
3569 if(peer->timeout != NULL)
3570 canceltimer(peer->timeout);
3571 peer->timeout = timercallback(ntime() + 180, (void (*)(int, void *))peertimeout, peer);
3572 if(*qcmd->string == '$')
3573 dispatchcommand(qcmd, peercmds, peer->sk, peer);
3582 static void preinit(int hup)
3589 static int updateudpport(struct configvar *var, void *uudata)
3591 struct sockaddr_in addr;
3592 struct socket *newsock;
3594 memset(&addr, 0, sizeof(addr));
3595 addr.sin_family = AF_INET;
3596 addr.sin_port = htons(var->val.num);
3597 if((newsock = netcsdgram((struct sockaddr *)&addr, sizeof(addr))) == NULL)
3599 flog(LOG_WARNING, "could not create new DC UDP socket, reverting to old: %s", strerror(errno));
3602 newsock->readcb = udpread;
3609 static int updatetcpport(struct configvar *var, void *uudata)
3611 struct sockaddr_in addr;
3612 struct socket *newsock;
3614 memset(&addr, 0, sizeof(addr));
3615 addr.sin_family = AF_INET;
3616 addr.sin_port = htons(var->val.num);
3617 if((newsock = netcslisten(SOCK_STREAM, (struct sockaddr *)&addr, sizeof(addr), peeraccept, NULL)) == NULL)
3618 flog(LOG_INFO, "could not listen to a remote address, going into passive mode");
3625 static int init(int hup)
3627 struct sockaddr_in addr;
3631 GCBREG(sharechangecb, shareupdate, NULL);
3636 addr.sin_family = AF_INET;
3637 memset(&addr.sin_addr, 0, sizeof(addr.sin_addr));
3638 addr.sin_port = htons(confgetint("dc", "udpport"));
3639 if((udpsock = netcsdgram((struct sockaddr *)&addr, sizeof(addr))) == NULL)
3641 flog(LOG_CRIT, "could not create DC UDP socket: %s", strerror(errno));
3644 udpsock->readcb = udpread;
3645 addr.sin_port = htons(confgetint("dc", "tcpport"));
3646 if((tcpsock = netcslisten(SOCK_STREAM, (struct sockaddr *)&addr, sizeof(addr), peeraccept, NULL)) == NULL)
3647 flog(LOG_INFO, "could not listen to a remote address, going into passive mode");
3648 CBREG(confgetvar("dc", "udpport"), conf_update, updateudpport, NULL, NULL);
3649 CBREG(confgetvar("dc", "tcpport"), conf_update, updatetcpport, NULL, NULL);
3650 CBREG(confgetvar("net", "mode"), conf_update, updatetcpport, NULL, NULL);
3655 static void terminate(void)
3657 if(hmlistname != NULL)
3662 if(xmllistname != NULL)
3664 unlink(xmllistname);
3667 if(xmlbz2listname != NULL)
3669 unlink(xmlbz2listname);
3670 free(xmlbz2listname);
3674 static struct configvar myvars[] =
3676 {CONF_VAR_STRING, "desc", {.str = L""}},
3677 {CONF_VAR_STRING, "speedstring", {.str = L"LAN(T1)"}},
3678 {CONF_VAR_STRING, "email", {.str = L"spam@spam.org"}},
3679 {CONF_VAR_INT, "udpport", {.num = 0}},
3680 {CONF_VAR_INT, "tcpport", {.num = 0}},
3681 {CONF_VAR_BOOL, "dcppemu", {.num = 0}},
3685 static struct module me =
3694 .terminate = terminate,