Experimental IRC client, daemon and bot
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

kike.c 113KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052
  1. /*
  2. * kike.c: the experimental IRC daemon
  3. *
  4. * Copyright (c) 2014 - 2018, Přemysl Janouch <p@janouch.name>
  5. *
  6. * Permission to use, copy, modify, and/or distribute this software for any
  7. * purpose with or without fee is hereby granted.
  8. *
  9. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  10. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  11. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  12. * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  13. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
  14. * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  15. * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. *
  17. */
  18. #include "config.h"
  19. #define PROGRAM_NAME "kike"
  20. #define WANT_SYSLOG_LOGGING
  21. #include "common.c"
  22. #include "kike-replies.c"
  23. #include <nl_types.h>
  24. enum { PIPE_READ, PIPE_WRITE };
  25. // FIXME: don't use time_t to compute time deltas
  26. // --- Configuration (application-specific) ------------------------------------
  27. // Just get rid of the crappiest ciphers available by default
  28. #define DEFAULT_CIPHERS "DEFAULT:!MEDIUM:!LOW"
  29. static struct simple_config_item g_config_table[] =
  30. {
  31. { "pid_file", NULL, "Path or name of the PID file" },
  32. { "server_name", NULL, "Server name" },
  33. { "server_info", "My server", "Brief server description" },
  34. { "motd", NULL, "MOTD filename" },
  35. { "catalog", NULL, "catgets localization catalog" },
  36. { "bind_host", NULL, "Address of the IRC server" },
  37. { "bind_port", "6667", "Port of the IRC server" },
  38. { "tls_cert", NULL, "Server TLS certificate (PEM)" },
  39. { "tls_key", NULL, "Server TLS private key (PEM)" },
  40. { "tls_ciphers", DEFAULT_CIPHERS, "OpenSSL cipher list" },
  41. { "operators", NULL, "IRCop TLS cert. fingerprints" },
  42. { "max_connections", "0", "Global connection limit" },
  43. { "ping_interval", "180", "Interval between PINGs (sec)" },
  44. { NULL, NULL, NULL }
  45. };
  46. // --- Signals -----------------------------------------------------------------
  47. static int g_signal_pipe[2]; ///< A pipe used to signal... signals
  48. /// Program termination has been requested by a signal
  49. static volatile sig_atomic_t g_termination_requested;
  50. static void
  51. sigterm_handler (int signum)
  52. {
  53. (void) signum;
  54. g_termination_requested = true;
  55. int original_errno = errno;
  56. if (write (g_signal_pipe[1], "t", 1) == -1)
  57. soft_assert (errno == EAGAIN);
  58. errno = original_errno;
  59. }
  60. static void
  61. setup_signal_handlers (void)
  62. {
  63. if (pipe (g_signal_pipe) == -1)
  64. exit_fatal ("%s: %s", "pipe", strerror (errno));
  65. set_cloexec (g_signal_pipe[0]);
  66. set_cloexec (g_signal_pipe[1]);
  67. // So that the pipe cannot overflow; it would make write() block within
  68. // the signal handler, which is something we really don't want to happen.
  69. // The same holds true for read().
  70. set_blocking (g_signal_pipe[0], false);
  71. set_blocking (g_signal_pipe[1], false);
  72. signal (SIGPIPE, SIG_IGN);
  73. struct sigaction sa;
  74. sa.sa_flags = SA_RESTART;
  75. sigemptyset (&sa.sa_mask);
  76. sa.sa_handler = sigterm_handler;
  77. if (sigaction (SIGINT, &sa, NULL) == -1
  78. || sigaction (SIGTERM, &sa, NULL) == -1)
  79. exit_fatal ("%s: %s", "sigaction", strerror (errno));
  80. }
  81. // --- Rate limiter ------------------------------------------------------------
  82. struct flood_detector
  83. {
  84. unsigned interval; ///< Interval for the limit
  85. unsigned limit; ///< Maximum number of events allowed
  86. time_t *timestamps; ///< Timestamps of last events
  87. unsigned pos; ///< Index of the oldest event
  88. };
  89. static void
  90. flood_detector_init (struct flood_detector *self,
  91. unsigned interval, unsigned limit)
  92. {
  93. self->interval = interval;
  94. self->limit = limit;
  95. self->timestamps = xcalloc (limit + 1, sizeof *self->timestamps);
  96. self->pos = 0;
  97. }
  98. static void
  99. flood_detector_free (struct flood_detector *self)
  100. {
  101. free (self->timestamps);
  102. }
  103. static bool
  104. flood_detector_check (struct flood_detector *self)
  105. {
  106. time_t now = time (NULL);
  107. self->timestamps[self->pos++] = now;
  108. if (self->pos > self->limit)
  109. self->pos = 0;
  110. time_t begin = now - self->interval;
  111. size_t count = 0;
  112. for (size_t i = 0; i <= self->limit; i++)
  113. if (self->timestamps[i] >= begin)
  114. count++;
  115. return count <= self->limit;
  116. }
  117. // --- IRC token validation ----------------------------------------------------
  118. // Use the enum only if applicable and a simple boolean isn't sufficient.
  119. enum validation_result
  120. {
  121. VALIDATION_OK,
  122. VALIDATION_ERROR_EMPTY,
  123. VALIDATION_ERROR_TOO_LONG,
  124. VALIDATION_ERROR_INVALID
  125. };
  126. // Everything as per RFC 2812
  127. #define IRC_MAX_NICKNAME 9
  128. #define IRC_MAX_HOSTNAME 63
  129. #define IRC_MAX_CHANNEL_NAME 50
  130. #define IRC_MAX_MESSAGE_LENGTH 510
  131. static bool
  132. irc_regex_match (const char *regex, const char *s)
  133. {
  134. static struct str_map cache;
  135. static bool initialized;
  136. if (!initialized)
  137. {
  138. cache = regex_cache_make ();
  139. initialized = true;
  140. }
  141. struct error *e = NULL;
  142. bool result = regex_cache_match (&cache, regex,
  143. REG_EXTENDED | REG_NOSUB, s, &e);
  144. hard_assert (!e);
  145. return result;
  146. }
  147. static const char *
  148. irc_validate_to_str (enum validation_result result)
  149. {
  150. switch (result)
  151. {
  152. case VALIDATION_OK: return "success";
  153. case VALIDATION_ERROR_EMPTY: return "the value is empty";
  154. case VALIDATION_ERROR_INVALID: return "invalid format";
  155. case VALIDATION_ERROR_TOO_LONG: return "the value is too long";
  156. default: abort ();
  157. }
  158. }
  159. // Anything to keep it as short as possible
  160. // "shortname" from RFC 2812 doesn't work how its author thought it would.
  161. #define SN "[0-9A-Za-z](-*[0-9A-Za-z])*"
  162. #define N4 "[0-9]{1,3}"
  163. #define N6 "[0-9ABCDEFabcdef]{1,}"
  164. #define LE "A-Za-z"
  165. #define SP "][\\\\`_^{|}"
  166. static enum validation_result
  167. irc_validate_hostname (const char *hostname)
  168. {
  169. if (!*hostname)
  170. return VALIDATION_ERROR_EMPTY;
  171. if (!irc_regex_match ("^" SN "(\\." SN ")*$", hostname))
  172. return VALIDATION_ERROR_INVALID;
  173. if (strlen (hostname) > IRC_MAX_HOSTNAME)
  174. return VALIDATION_ERROR_TOO_LONG;
  175. return VALIDATION_OK;
  176. }
  177. static bool
  178. irc_is_valid_hostaddr (const char *hostaddr)
  179. {
  180. if (irc_regex_match ("^" N4 "\\." N4 "\\." N4 "\\." N4 "$", hostaddr)
  181. || irc_regex_match ("^" N6 ":" N6 ":" N6 ":" N6 ":"
  182. N6 ":" N6 ":" N6 ":" N6 "$", hostaddr)
  183. || irc_regex_match ("^0:0:0:0:0:(0|[Ff]{4}):"
  184. N4 "\\." N4 "\\." N4 "\\." N4 "$", hostaddr))
  185. return true;
  186. return false;
  187. }
  188. // TODO: we should actually use this, though what should we do on failure?
  189. static bool
  190. irc_is_valid_host (const char *host)
  191. {
  192. return irc_validate_hostname (host) == VALIDATION_OK
  193. || irc_is_valid_hostaddr (host);
  194. }
  195. // TODO: currently, we are almost encoding-agnostic (strings just need to be
  196. // ASCII-compatible). We should at least have an option to enforce a specific
  197. // encoding, such as UTF-8. Note that with Unicode we should not allow all
  198. // character clasess and exclude the likes of \pM with the goal of enforcing
  199. // NFC-normalized identifiers--utf8proc is a good candidate library to handle
  200. // the categorization and validation.
  201. static bool
  202. irc_is_valid_user (const char *user)
  203. {
  204. return irc_regex_match ("^[^\r\n @]+$", user);
  205. }
  206. static bool
  207. irc_validate_nickname (const char *nickname)
  208. {
  209. if (!*nickname)
  210. return VALIDATION_ERROR_EMPTY;
  211. if (!irc_regex_match ("^[" SP LE "][" SP LE "0-9-]*$", nickname))
  212. return VALIDATION_ERROR_INVALID;
  213. if (strlen (nickname) > IRC_MAX_NICKNAME)
  214. return VALIDATION_ERROR_TOO_LONG;
  215. return VALIDATION_OK;
  216. }
  217. static enum validation_result
  218. irc_validate_channel_name (const char *channel_name)
  219. {
  220. if (!*channel_name)
  221. return VALIDATION_ERROR_EMPTY;
  222. if (*channel_name != '#' || strpbrk (channel_name, "\7\r\n ,:"))
  223. return VALIDATION_ERROR_INVALID;
  224. if (strlen (channel_name) > IRC_MAX_CHANNEL_NAME)
  225. return VALIDATION_ERROR_TOO_LONG;
  226. return VALIDATION_OK;
  227. }
  228. static bool
  229. irc_is_valid_key (const char *key)
  230. {
  231. // XXX: should be 7-bit as well but whatever
  232. return irc_regex_match ("^[^\r\n\f\t\v ]{1,23}$", key);
  233. }
  234. #undef SN
  235. #undef N4
  236. #undef N6
  237. #undef LE
  238. #undef SP
  239. static bool
  240. irc_is_valid_user_mask (const char *mask)
  241. {
  242. return irc_regex_match ("^[^!@]+![^!@]+@[^@!]+$", mask);
  243. }
  244. static bool
  245. irc_is_valid_fingerprint (const char *fp)
  246. {
  247. return irc_regex_match ("^[a-fA-F0-9]{40}$", fp);
  248. }
  249. // --- Clients (equals users) --------------------------------------------------
  250. #define IRC_SUPPORTED_USER_MODES "aiwros"
  251. enum
  252. {
  253. IRC_USER_MODE_INVISIBLE = (1 << 0),
  254. IRC_USER_MODE_RX_WALLOPS = (1 << 1),
  255. IRC_USER_MODE_RESTRICTED = (1 << 2),
  256. IRC_USER_MODE_OPERATOR = (1 << 3),
  257. IRC_USER_MODE_RX_SERVER_NOTICES = (1 << 4)
  258. };
  259. enum
  260. {
  261. IRC_CAP_MULTI_PREFIX = (1 << 0),
  262. IRC_CAP_INVITE_NOTIFY = (1 << 1),
  263. IRC_CAP_ECHO_MESSAGE = (1 << 2),
  264. IRC_CAP_USERHOST_IN_NAMES = (1 << 3),
  265. IRC_CAP_SERVER_TIME = (1 << 4)
  266. };
  267. struct client
  268. {
  269. LIST_HEADER (struct client)
  270. struct server_context *ctx; ///< Server context
  271. time_t opened; ///< When the connection was opened
  272. size_t n_sent_messages; ///< Number of sent messages total
  273. size_t sent_bytes; ///< Number of sent bytes total
  274. size_t n_received_messages; ///< Number of received messages total
  275. size_t received_bytes; ///< Number of received bytes total
  276. int socket_fd; ///< The TCP socket
  277. struct str read_buffer; ///< Unprocessed input
  278. struct str write_buffer; ///< Output yet to be sent out
  279. struct poller_fd socket_event; ///< The socket can be read/written to
  280. struct poller_timer ping_timer; ///< We should send a ping
  281. struct poller_timer timeout_timer; ///< Connection seems to be dead
  282. struct poller_timer kill_timer; ///< Hard kill timeout
  283. unsigned long cap_version; ///< CAP protocol version
  284. unsigned caps_enabled; ///< Enabled capabilities
  285. unsigned initialized : 1; ///< Has any data been received yet?
  286. unsigned cap_negotiating : 1; ///< Negotiating capabilities
  287. unsigned registered : 1; ///< The user has registered
  288. unsigned closing_link : 1; ///< Closing link
  289. unsigned half_closed : 1; ///< Closing link: conn. is half-closed
  290. unsigned ssl_rx_want_tx : 1; ///< SSL_read() wants to write
  291. unsigned ssl_tx_want_rx : 1; ///< SSL_write() wants to read
  292. SSL *ssl; ///< SSL connection
  293. char *ssl_cert_fingerprint; ///< Client certificate fingerprint
  294. char *nickname; ///< IRC nickname (main identifier)
  295. char *username; ///< IRC username
  296. char *realname; ///< IRC realname (e-mail)
  297. char *hostname; ///< Hostname shown to the network
  298. char *port; ///< Port of the peer as a string
  299. char *address; ///< Full address
  300. unsigned mode; ///< User's mode
  301. char *away_message; ///< Away message
  302. time_t last_active; ///< Last PRIVMSG, to get idle time
  303. struct str_map invites; ///< Channel invitations by operators
  304. struct flood_detector antiflood; ///< Flood detector
  305. struct async_getnameinfo *gni; ///< Backwards DNS resolution
  306. struct poller_timer gni_timer; ///< Backwards DNS resolution timeout
  307. };
  308. static struct client *
  309. client_new (void)
  310. {
  311. struct client *self = xcalloc (1, sizeof *self);
  312. self->socket_fd = -1;
  313. self->read_buffer = str_make ();
  314. self->write_buffer = str_make ();
  315. self->cap_version = 301;
  316. // TODO: make this configurable and more fine-grained
  317. flood_detector_init (&self->antiflood, 10, 20);
  318. self->invites = str_map_make (NULL);
  319. self->invites.key_xfrm = irc_strxfrm;
  320. return self;
  321. }
  322. static void
  323. client_destroy (struct client *self)
  324. {
  325. if (!soft_assert (self->socket_fd == -1))
  326. xclose (self->socket_fd);
  327. if (self->ssl)
  328. SSL_free (self->ssl);
  329. str_free (&self->read_buffer);
  330. str_free (&self->write_buffer);
  331. free (self->ssl_cert_fingerprint);
  332. free (self->nickname);
  333. free (self->username);
  334. free (self->realname);
  335. free (self->hostname);
  336. free (self->port);
  337. free (self->address);
  338. free (self->away_message);
  339. flood_detector_free (&self->antiflood);
  340. str_map_free (&self->invites);
  341. if (self->gni)
  342. async_cancel (&self->gni->async);
  343. free (self);
  344. }
  345. static void client_close_link (struct client *c, const char *reason);
  346. static void client_kill (struct client *c, const char *reason);
  347. static void client_send (struct client *, const char *, ...)
  348. ATTRIBUTE_PRINTF (2, 3);
  349. static void client_cancel_timers (struct client *);
  350. static void client_set_kill_timer (struct client *);
  351. static void client_update_poller (struct client *, const struct pollfd *);
  352. // --- Channels ----------------------------------------------------------------
  353. #define IRC_SUPPORTED_CHAN_MODES "ov" "beI" "imnqpst" "kl"
  354. enum
  355. {
  356. IRC_CHAN_MODE_INVITE_ONLY = (1 << 0),
  357. IRC_CHAN_MODE_MODERATED = (1 << 1),
  358. IRC_CHAN_MODE_NO_OUTSIDE_MSGS = (1 << 2),
  359. IRC_CHAN_MODE_QUIET = (1 << 3),
  360. IRC_CHAN_MODE_PRIVATE = (1 << 4),
  361. IRC_CHAN_MODE_SECRET = (1 << 5),
  362. IRC_CHAN_MODE_PROTECTED_TOPIC = (1 << 6),
  363. IRC_CHAN_MODE_OPERATOR = (1 << 7),
  364. IRC_CHAN_MODE_VOICE = (1 << 8)
  365. };
  366. struct channel_user
  367. {
  368. LIST_HEADER (struct channel_user)
  369. unsigned modes;
  370. struct client *c;
  371. };
  372. struct channel
  373. {
  374. struct server_context *ctx; ///< Server context
  375. char *name; ///< Channel name
  376. unsigned modes; ///< Channel modes
  377. char *key; ///< Channel key
  378. long user_limit; ///< User limit or -1
  379. time_t created; ///< Creation time
  380. char *topic; ///< Channel topic
  381. char *topic_who; ///< Who set the topic
  382. time_t topic_time; ///< When the topic was set
  383. struct channel_user *users; ///< Channel users
  384. struct strv ban_list; ///< Ban list
  385. struct strv exception_list; ///< Exceptions from bans
  386. struct strv invite_list; ///< Exceptions from +I
  387. };
  388. static struct channel *
  389. channel_new (void)
  390. {
  391. struct channel *self = xcalloc (1, sizeof *self);
  392. self->user_limit = -1;
  393. self->topic = xstrdup ("");
  394. self->ban_list = strv_make ();
  395. self->exception_list = strv_make ();
  396. self->invite_list = strv_make ();
  397. return self;
  398. }
  399. static void
  400. channel_delete (struct channel *self)
  401. {
  402. free (self->name);
  403. free (self->key);
  404. free (self->topic);
  405. free (self->topic_who);
  406. struct channel_user *link, *tmp;
  407. for (link = self->users; link; link = tmp)
  408. {
  409. tmp = link->next;
  410. free (link);
  411. }
  412. strv_free (&self->ban_list);
  413. strv_free (&self->exception_list);
  414. strv_free (&self->invite_list);
  415. free (self);
  416. }
  417. static char *
  418. channel_get_mode (struct channel *self, bool disclose_secrets)
  419. {
  420. struct str mode = str_make ();
  421. unsigned m = self->modes;
  422. if (m & IRC_CHAN_MODE_INVITE_ONLY) str_append_c (&mode, 'i');
  423. if (m & IRC_CHAN_MODE_MODERATED) str_append_c (&mode, 'm');
  424. if (m & IRC_CHAN_MODE_NO_OUTSIDE_MSGS) str_append_c (&mode, 'n');
  425. if (m & IRC_CHAN_MODE_QUIET) str_append_c (&mode, 'q');
  426. if (m & IRC_CHAN_MODE_PRIVATE) str_append_c (&mode, 'p');
  427. if (m & IRC_CHAN_MODE_SECRET) str_append_c (&mode, 's');
  428. if (m & IRC_CHAN_MODE_PROTECTED_TOPIC) str_append_c (&mode, 't');
  429. if (self->user_limit != -1) str_append_c (&mode, 'l');
  430. if (self->key) str_append_c (&mode, 'k');
  431. // XXX: is it correct to split it? Try it on an existing implementation.
  432. if (disclose_secrets)
  433. {
  434. if (self->user_limit != -1)
  435. str_append_printf (&mode, " %ld", self->user_limit);
  436. if (self->key)
  437. str_append_printf (&mode, " %s", self->key);
  438. }
  439. return str_steal (&mode);
  440. }
  441. static struct channel_user *
  442. channel_get_user (const struct channel *chan, const struct client *c)
  443. {
  444. for (struct channel_user *iter = chan->users; iter; iter = iter->next)
  445. if (iter->c == c)
  446. return iter;
  447. return NULL;
  448. }
  449. static struct channel_user *
  450. channel_add_user (struct channel *chan, struct client *c)
  451. {
  452. struct channel_user *link = xcalloc (1, sizeof *link);
  453. link->c = c;
  454. LIST_PREPEND (chan->users, link);
  455. return link;
  456. }
  457. static void
  458. channel_remove_user (struct channel *chan, struct channel_user *user)
  459. {
  460. LIST_UNLINK (chan->users, user);
  461. free (user);
  462. }
  463. static size_t
  464. channel_user_count (const struct channel *chan)
  465. {
  466. size_t result = 0;
  467. for (struct channel_user *iter = chan->users; iter; iter = iter->next)
  468. result++;
  469. return result;
  470. }
  471. // --- IRC server context ------------------------------------------------------
  472. struct whowas_info
  473. {
  474. char *nickname; ///< IRC nickname
  475. char *username; ///< IRC username
  476. char *realname; ///< IRC realname
  477. char *hostname; ///< Hostname shown to the network
  478. };
  479. struct whowas_info *
  480. whowas_info_new (struct client *c)
  481. {
  482. struct whowas_info *self = xmalloc (sizeof *self);
  483. self->nickname = xstrdup (c->nickname);
  484. self->username = xstrdup (c->username);
  485. self->realname = xstrdup (c->realname);
  486. self->hostname = xstrdup (c->hostname);
  487. return self;
  488. }
  489. static void
  490. whowas_info_destroy (struct whowas_info *self)
  491. {
  492. free (self->nickname);
  493. free (self->username);
  494. free (self->realname);
  495. free (self->hostname);
  496. free (self);
  497. }
  498. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  499. struct irc_command
  500. {
  501. const char *name;
  502. bool requires_registration;
  503. void (*handler) (const struct irc_message *, struct client *);
  504. size_t n_received; ///< Number of commands received
  505. size_t bytes_received; ///< Number of bytes received total
  506. };
  507. struct server_context
  508. {
  509. int *listen_fds; ///< Listening socket FD's
  510. struct poller_fd *listen_events; ///< New connections available
  511. size_t n_listen_fds; ///< Number of listening sockets
  512. time_t started; ///< When has the server been started
  513. SSL_CTX *ssl_ctx; ///< SSL context
  514. struct client *clients; ///< Clients
  515. unsigned n_clients; ///< Current number of connections
  516. struct str_map users; ///< Maps nicknames to clients
  517. struct str_map channels; ///< Maps channel names to data
  518. struct str_map handlers; ///< Message handlers
  519. struct str_map cap_handlers; ///< CAP message handlers
  520. struct str_map whowas; ///< WHOWAS registry
  521. struct poller poller; ///< Manages polled description
  522. struct poller_timer quit_timer; ///< Quit timeout timer
  523. bool quitting; ///< User requested quitting
  524. bool polling; ///< The event loop is running
  525. struct poller_fd signal_event; ///< Got a signal
  526. struct str_map config; ///< Server configuration
  527. char *server_name; ///< Our server name
  528. unsigned ping_interval; ///< Ping interval in seconds
  529. unsigned max_connections; ///< Max. connections allowed or 0
  530. struct strv motd; ///< MOTD (none if empty)
  531. nl_catd catalog; ///< Message catalog for server msgs
  532. struct str_map operators; ///< TLS cert. fingerprints for IRCops
  533. };
  534. static void
  535. on_irc_quit_timeout (void *user_data)
  536. {
  537. struct server_context *ctx = user_data;
  538. struct client *iter, *next;
  539. for (iter = ctx->clients; iter; iter = next)
  540. {
  541. next = iter->next;
  542. // irc_initiate_quit() has already unregistered the client
  543. client_kill (iter, "Shutting down");
  544. }
  545. }
  546. static void
  547. server_context_init (struct server_context *self)
  548. {
  549. memset (self, 0, sizeof *self);
  550. self->users = str_map_make (NULL);
  551. self->users.key_xfrm = irc_strxfrm;
  552. self->channels = str_map_make ((str_map_free_fn) channel_delete);
  553. self->channels.key_xfrm = irc_strxfrm;
  554. self->handlers = str_map_make (NULL);
  555. self->handlers.key_xfrm = irc_strxfrm;
  556. self->cap_handlers = str_map_make (NULL);
  557. self->cap_handlers.key_xfrm = irc_strxfrm;
  558. self->whowas = str_map_make ((str_map_free_fn) whowas_info_destroy);
  559. self->whowas.key_xfrm = irc_strxfrm;
  560. poller_init (&self->poller);
  561. self->quit_timer = poller_timer_make (&self->poller);
  562. self->quit_timer.dispatcher = on_irc_quit_timeout;
  563. self->quit_timer.user_data = self;
  564. self->config = str_map_make (free);
  565. simple_config_load_defaults (&self->config, g_config_table);
  566. self->motd = strv_make ();
  567. self->catalog = (nl_catd) -1;
  568. self->operators = str_map_make (NULL);
  569. // The regular irc_strxfrm() is sufficient for fingerprints
  570. self->operators.key_xfrm = irc_strxfrm;
  571. }
  572. static void
  573. server_context_free (struct server_context *self)
  574. {
  575. str_map_free (&self->config);
  576. for (size_t i = 0; i < self->n_listen_fds; i++)
  577. {
  578. poller_fd_reset (&self->listen_events[i]);
  579. xclose (self->listen_fds[i]);
  580. }
  581. free (self->listen_fds);
  582. free (self->listen_events);
  583. hard_assert (!self->clients);
  584. if (self->ssl_ctx)
  585. SSL_CTX_free (self->ssl_ctx);
  586. free (self->server_name);
  587. str_map_free (&self->users);
  588. str_map_free (&self->channels);
  589. str_map_free (&self->handlers);
  590. str_map_free (&self->cap_handlers);
  591. str_map_free (&self->whowas);
  592. poller_free (&self->poller);
  593. strv_free (&self->motd);
  594. if (self->catalog != (nl_catd) -1)
  595. catclose (self->catalog);
  596. str_map_free (&self->operators);
  597. }
  598. static const char *
  599. irc_get_text (struct server_context *ctx, int id, const char *def)
  600. {
  601. if (!soft_assert (def != NULL))
  602. def = "";
  603. if (ctx->catalog == (nl_catd) -1)
  604. return def;
  605. return catgets (ctx->catalog, 1, id, def);
  606. }
  607. static void
  608. irc_try_finish_quit (struct server_context *ctx)
  609. {
  610. if (!ctx->n_clients && ctx->quitting)
  611. {
  612. poller_timer_reset (&ctx->quit_timer);
  613. ctx->polling = false;
  614. }
  615. }
  616. static void
  617. irc_initiate_quit (struct server_context *ctx)
  618. {
  619. print_status ("shutting down");
  620. for (size_t i = 0; i < ctx->n_listen_fds; i++)
  621. {
  622. poller_fd_reset (&ctx->listen_events[i]);
  623. xclose (ctx->listen_fds[i]);
  624. }
  625. ctx->n_listen_fds = 0;
  626. for (struct client *iter = ctx->clients; iter; iter = iter->next)
  627. if (!iter->closing_link)
  628. client_close_link (iter, "Shutting down");
  629. ctx->quitting = true;
  630. poller_timer_set (&ctx->quit_timer, 5000);
  631. irc_try_finish_quit (ctx);
  632. }
  633. static struct channel *
  634. irc_channel_create (struct server_context *ctx, const char *name)
  635. {
  636. struct channel *chan = channel_new ();
  637. chan->ctx = ctx;
  638. chan->name = xstrdup (name);
  639. chan->created = time (NULL);
  640. str_map_set (&ctx->channels, name, chan);
  641. return chan;
  642. }
  643. static void
  644. irc_channel_destroy_if_empty (struct server_context *ctx, struct channel *chan)
  645. {
  646. if (!chan->users)
  647. str_map_set (&ctx->channels, chan->name, NULL);
  648. }
  649. static void
  650. irc_send_to_roommates (struct client *c, const char *message)
  651. {
  652. struct str_map targets = str_map_make (NULL);
  653. targets.key_xfrm = irc_strxfrm;
  654. struct str_map_iter iter = str_map_iter_make (&c->ctx->channels);
  655. struct channel *chan;
  656. while ((chan = str_map_iter_next (&iter)))
  657. {
  658. if (chan->modes & IRC_CHAN_MODE_QUIET
  659. || !channel_get_user (chan, c))
  660. continue;
  661. for (struct channel_user *iter = chan->users; iter; iter = iter->next)
  662. str_map_set (&targets, iter->c->nickname, iter->c);
  663. }
  664. iter = str_map_iter_make (&targets);
  665. struct client *target;
  666. while ((target = str_map_iter_next (&iter)))
  667. if (target != c)
  668. client_send (target, "%s", message);
  669. str_map_free (&targets);
  670. }
  671. // --- Clients (continued) -----------------------------------------------------
  672. static void
  673. client_mode_to_str (unsigned m, struct str *out)
  674. {
  675. if (m & IRC_USER_MODE_INVISIBLE) str_append_c (out, 'i');
  676. if (m & IRC_USER_MODE_RX_WALLOPS) str_append_c (out, 'w');
  677. if (m & IRC_USER_MODE_RESTRICTED) str_append_c (out, 'r');
  678. if (m & IRC_USER_MODE_OPERATOR) str_append_c (out, 'o');
  679. if (m & IRC_USER_MODE_RX_SERVER_NOTICES) str_append_c (out, 's');
  680. }
  681. static char *
  682. client_get_mode (struct client *self)
  683. {
  684. struct str mode = str_make ();
  685. if (self->away_message)
  686. str_append_c (&mode, 'a');
  687. client_mode_to_str (self->mode, &mode);
  688. return str_steal (&mode);
  689. }
  690. static void
  691. client_send_str (struct client *c, const struct str *s)
  692. {
  693. hard_assert (!c->closing_link);
  694. size_t old_sendq = c->write_buffer.len;
  695. // So far there's only one message tag we use, so we can do it simple;
  696. // note that a 1024-character limit applies to messages with tags on
  697. if (c->caps_enabled & IRC_CAP_SERVER_TIME)
  698. {
  699. long milliseconds; char buf[32]; struct tm tm;
  700. time_t now = unixtime_msec (&milliseconds);
  701. if (soft_assert (strftime (buf, sizeof buf,
  702. "%Y-%m-%dT%T", gmtime_r (&now, &tm))))
  703. str_append_printf (&c->write_buffer,
  704. "@time=%s.%03ldZ ", buf, milliseconds);
  705. }
  706. // TODO: kill the connection above some "SendQ" threshold (careful!)
  707. str_append_data (&c->write_buffer, s->str,
  708. MIN (s->len, IRC_MAX_MESSAGE_LENGTH));
  709. str_append (&c->write_buffer, "\r\n");
  710. // XXX: we might want to move this elsewhere, so that it doesn't get called
  711. // as often; it's going to cause a lot of syscalls with epoll.
  712. client_update_poller (c, NULL);
  713. // Technically we haven't sent it yet but that's a minor detail
  714. c->n_sent_messages++;
  715. c->sent_bytes += c->write_buffer.len - old_sendq;
  716. }
  717. static void
  718. client_send (struct client *c, const char *format, ...)
  719. {
  720. struct str tmp = str_make ();
  721. va_list ap;
  722. va_start (ap, format);
  723. str_append_vprintf (&tmp, format, ap);
  724. va_end (ap);
  725. client_send_str (c, &tmp);
  726. str_free (&tmp);
  727. }
  728. static void
  729. client_add_to_whowas (struct client *c)
  730. {
  731. // Only keeping one entry for each nickname
  732. // TODO: make sure this list doesn't get too long, for example by
  733. // putting them in a linked list ordered by time
  734. str_map_set (&c->ctx->whowas, c->nickname, whowas_info_new (c));
  735. }
  736. static void
  737. client_unregister (struct client *c, const char *reason)
  738. {
  739. if (!c->registered)
  740. return;
  741. char *message = xstrdup_printf (":%s!%s@%s QUIT :%s",
  742. c->nickname, c->username, c->hostname, reason);
  743. irc_send_to_roommates (c, message);
  744. free (message);
  745. struct str_map_unset_iter iter =
  746. str_map_unset_iter_make (&c->ctx->channels);
  747. struct channel *chan;
  748. while ((chan = str_map_unset_iter_next (&iter)))
  749. {
  750. struct channel_user *user;
  751. if (!(user = channel_get_user (chan, c)))
  752. continue;
  753. channel_remove_user (chan, user);
  754. irc_channel_destroy_if_empty (c->ctx, chan);
  755. }
  756. str_map_unset_iter_free (&iter);
  757. client_add_to_whowas (c);
  758. str_map_set (&c->ctx->users, c->nickname, NULL);
  759. cstr_set (&c->nickname, NULL);
  760. c->registered = false;
  761. }
  762. static void
  763. client_kill (struct client *c, const char *reason)
  764. {
  765. struct server_context *ctx = c->ctx;
  766. client_unregister (c, reason ? reason : "Client exited");
  767. if (c->address)
  768. // Only log the event if address resolution has finished
  769. print_debug ("closed connection to %s (%s)", c->address,
  770. reason ? reason : "");
  771. if (c->ssl)
  772. // Note that we might have already called this once, but that is fine
  773. (void) SSL_shutdown (c->ssl);
  774. xclose (c->socket_fd);
  775. c->socket_fd = -1;
  776. // We don't fork any children, this is okay
  777. c->socket_event.closed = true;
  778. poller_fd_reset (&c->socket_event);
  779. client_cancel_timers (c);
  780. LIST_UNLINK (ctx->clients, c);
  781. ctx->n_clients--;
  782. client_destroy (c);
  783. irc_try_finish_quit (ctx);
  784. }
  785. static void
  786. client_close_link (struct client *c, const char *reason)
  787. {
  788. // Let's just cut the connection, the client can try again later.
  789. // We also want to avoid accidentally setting poller events before
  790. // address resolution has finished.
  791. if (!c->initialized)
  792. {
  793. client_kill (c, reason);
  794. return;
  795. }
  796. if (!soft_assert (!c->closing_link))
  797. return;
  798. // We push an `ERROR' message to the write buffer and let the poller send
  799. // it, with some arbitrary timeout. The `closing_link' state makes sure
  800. // that a/ we ignore any successive messages, and b/ that the connection
  801. // is killed after the write buffer is transferred and emptied.
  802. client_send (c, "ERROR :Closing Link: %s[%s] (%s)",
  803. c->nickname ? c->nickname : "*",
  804. c->hostname /* TODO host IP? */, reason);
  805. c->closing_link = true;
  806. client_unregister (c, reason);
  807. client_set_kill_timer (c);
  808. }
  809. static bool
  810. client_in_mask_list (const struct client *c, const struct strv *mask)
  811. {
  812. char *client = xstrdup_printf ("%s!%s@%s",
  813. c->nickname, c->username, c->hostname);
  814. bool result = false;
  815. for (size_t i = 0; i < mask->len; i++)
  816. if (!irc_fnmatch (mask->vector[i], client))
  817. {
  818. result = true;
  819. break;
  820. }
  821. free (client);
  822. return result;
  823. }
  824. static char *
  825. client_get_ssl_cert_fingerprint (struct client *c)
  826. {
  827. if (!c->ssl)
  828. return NULL;
  829. X509 *peer_cert = SSL_get_peer_certificate (c->ssl);
  830. if (!peer_cert)
  831. return NULL;
  832. int cert_len = i2d_X509 (peer_cert, NULL);
  833. if (cert_len < 0)
  834. return NULL;
  835. unsigned char cert[cert_len], *p = cert;
  836. if (i2d_X509 (peer_cert, &p) < 0)
  837. return NULL;
  838. unsigned char hash[SHA_DIGEST_LENGTH];
  839. SHA1 (cert, cert_len, hash);
  840. struct str fingerprint = str_make ();
  841. for (size_t i = 0; i < sizeof hash; i++)
  842. str_append_printf (&fingerprint, "%02x", hash[i]);
  843. return str_steal (&fingerprint);
  844. }
  845. // --- Timers ------------------------------------------------------------------
  846. static void
  847. client_cancel_timers (struct client *c)
  848. {
  849. poller_timer_reset (&c->kill_timer);
  850. poller_timer_reset (&c->timeout_timer);
  851. poller_timer_reset (&c->ping_timer);
  852. poller_timer_reset (&c->gni_timer);
  853. }
  854. static void
  855. client_set_timer (struct client *c,
  856. struct poller_timer *timer, unsigned interval)
  857. {
  858. client_cancel_timers (c);
  859. poller_timer_set (timer, interval * 1000);
  860. }
  861. static void
  862. on_client_kill_timer (struct client *c)
  863. {
  864. hard_assert (!c->initialized || c->closing_link);
  865. client_kill (c, NULL);
  866. }
  867. static void
  868. client_set_kill_timer (struct client *c)
  869. {
  870. client_set_timer (c, &c->kill_timer, c->ctx->ping_interval);
  871. }
  872. static void
  873. on_client_timeout_timer (struct client *c)
  874. {
  875. char *reason = xstrdup_printf
  876. ("Ping timeout: >%u seconds", c->ctx->ping_interval);
  877. client_close_link (c, reason);
  878. free (reason);
  879. }
  880. static void
  881. on_client_ping_timer (struct client *c)
  882. {
  883. hard_assert (!c->closing_link);
  884. client_send (c, "PING :%s", c->ctx->server_name);
  885. client_set_timer (c, &c->timeout_timer, c->ctx->ping_interval);
  886. }
  887. static void
  888. client_set_ping_timer (struct client *c)
  889. {
  890. client_set_timer (c, &c->ping_timer, c->ctx->ping_interval);
  891. }
  892. // --- IRC command handling ----------------------------------------------------
  893. static void
  894. irc_make_reply (struct client *c, int id, va_list ap, struct str *output)
  895. {
  896. str_append_printf (output, ":%s %03d %s ",
  897. c->ctx->server_name, id, c->nickname ? c->nickname : "*");
  898. str_append_vprintf (output,
  899. irc_get_text (c->ctx, id, g_default_replies[id]), ap);
  900. }
  901. // XXX: this way we cannot typecheck the arguments, so we must be careful
  902. static void
  903. irc_send_reply (struct client *c, int id, ...)
  904. {
  905. struct str reply = str_make ();
  906. va_list ap;
  907. va_start (ap, id);
  908. irc_make_reply (c, id, ap, &reply);
  909. va_end (ap);
  910. client_send_str (c, &reply);
  911. str_free (&reply);
  912. }
  913. /// Send a space-separated list of words across as many replies as needed
  914. static void
  915. irc_send_reply_vector (struct client *c, int id, char **items, ...)
  916. {
  917. struct str common = str_make ();
  918. va_list ap;
  919. va_start (ap, items);
  920. irc_make_reply (c, id, ap, &common);
  921. va_end (ap);
  922. // We always send at least one message (there might be a client that
  923. // expects us to send this message at least once)
  924. do
  925. {
  926. struct str reply = str_make ();
  927. str_append_str (&reply, &common);
  928. // If not even a single item fits in the limit (which may happen,
  929. // in theory) it just gets cropped. We could also skip it.
  930. if (*items)
  931. str_append (&reply, *items++);
  932. // Append as many items as fits in a single message
  933. while (*items
  934. && reply.len + 1 + strlen (*items) <= IRC_MAX_MESSAGE_LENGTH)
  935. str_append_printf (&reply, " %s", *items++);
  936. client_send_str (c, &reply);
  937. str_free (&reply);
  938. }
  939. while (*items);
  940. str_free (&common);
  941. }
  942. #define RETURN_WITH_REPLY(c, ...) \
  943. BLOCK_START \
  944. irc_send_reply ((c), __VA_ARGS__); \
  945. return; \
  946. BLOCK_END
  947. static void
  948. irc_send_motd (struct client *c)
  949. {
  950. struct server_context *ctx = c->ctx;
  951. if (!ctx->motd.len)
  952. RETURN_WITH_REPLY (c, IRC_ERR_NOMOTD);
  953. irc_send_reply (c, IRC_RPL_MOTDSTART, ctx->server_name);
  954. for (size_t i = 0; i < ctx->motd.len; i++)
  955. irc_send_reply (c, IRC_RPL_MOTD, ctx->motd.vector[i]);
  956. irc_send_reply (c, IRC_RPL_ENDOFMOTD);
  957. }
  958. static void
  959. irc_send_lusers (struct client *c)
  960. {
  961. int n_users = 0, n_services = 0, n_opers = 0, n_unknown = 0;
  962. for (struct client *link = c->ctx->clients; link; link = link->next)
  963. {
  964. if (link->registered)
  965. n_users++;
  966. else
  967. n_unknown++;
  968. if (link->mode & IRC_USER_MODE_OPERATOR)
  969. n_opers++;
  970. }
  971. int n_channels = 0;
  972. struct str_map_iter iter = str_map_iter_make (&c->ctx->channels);
  973. struct channel *chan;
  974. while ((chan = str_map_iter_next (&iter)))
  975. if (!(chan->modes & IRC_CHAN_MODE_SECRET)
  976. || channel_get_user (chan, c))
  977. n_channels++;
  978. irc_send_reply (c, IRC_RPL_LUSERCLIENT,
  979. n_users, n_services, 1 /* servers total */);
  980. if (n_opers)
  981. irc_send_reply (c, IRC_RPL_LUSEROP, n_opers);
  982. if (n_unknown)
  983. irc_send_reply (c, IRC_RPL_LUSERUNKNOWN, n_unknown);
  984. if (n_channels)
  985. irc_send_reply (c, IRC_RPL_LUSERCHANNELS, n_channels);
  986. irc_send_reply (c, IRC_RPL_LUSERME,
  987. n_users + n_services + n_unknown, 0 /* peer servers */);
  988. }
  989. static bool
  990. irc_is_this_me (struct server_context *ctx, const char *target)
  991. {
  992. // Target servers can also be matched by their users
  993. return !irc_fnmatch (target, ctx->server_name)
  994. || str_map_find (&ctx->users, target);
  995. }
  996. static void
  997. irc_send_isupport (struct client *c)
  998. {
  999. // Only # channels, +e supported, +I supported, unlimited arguments to MODE
  1000. irc_send_reply (c, IRC_RPL_ISUPPORT, "CHANTYPES=# EXCEPTS INVEX MODES"
  1001. " TARGMAX=WHOIS:,LIST:,NAMES:,PRIVMSG:1,NOTICE:1,KICK:"
  1002. " NICKLEN=" XSTRINGIFY (IRC_MAX_NICKNAME)
  1003. " CHANNELLEN=" XSTRINGIFY (IRC_MAX_CHANNEL_NAME));
  1004. }
  1005. static void
  1006. irc_try_finish_registration (struct client *c)
  1007. {
  1008. struct server_context *ctx = c->ctx;
  1009. if (!c->nickname || !c->username || !c->realname)
  1010. return;
  1011. if (c->registered || c->cap_negotiating)
  1012. return;
  1013. c->registered = true;
  1014. irc_send_reply (c, IRC_RPL_WELCOME, c->nickname, c->username, c->hostname);
  1015. irc_send_reply (c, IRC_RPL_YOURHOST, ctx->server_name, PROGRAM_VERSION);
  1016. // The purpose of this message eludes me
  1017. irc_send_reply (c, IRC_RPL_CREATED, __DATE__);
  1018. irc_send_reply (c, IRC_RPL_MYINFO, ctx->server_name, PROGRAM_VERSION,
  1019. IRC_SUPPORTED_USER_MODES, IRC_SUPPORTED_CHAN_MODES);
  1020. irc_send_isupport (c);
  1021. irc_send_lusers (c);
  1022. irc_send_motd (c);
  1023. char *mode = client_get_mode (c);
  1024. if (*mode)
  1025. client_send (c, ":%s MODE %s :+%s", c->nickname, c->nickname, mode);
  1026. free (mode);
  1027. hard_assert (c->ssl_cert_fingerprint == NULL);
  1028. if ((c->ssl_cert_fingerprint = client_get_ssl_cert_fingerprint (c)))
  1029. client_send (c, ":%s NOTICE %s :"
  1030. "Your TLS client certificate fingerprint is %s",
  1031. ctx->server_name, c->nickname, c->ssl_cert_fingerprint);
  1032. str_map_set (&ctx->whowas, c->nickname, NULL);
  1033. }
  1034. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1035. // IRCv3 capability negotiation. See http://ircv3.org for details.
  1036. struct irc_cap_args
  1037. {
  1038. const char *subcommand; ///< The subcommand being processed
  1039. const char *full_params; ///< Whole parameter string
  1040. struct strv params; ///< Split parameters
  1041. const char *target; ///< Target parameter for replies
  1042. };
  1043. static struct
  1044. {
  1045. unsigned flag; ///< Flag
  1046. const char *name; ///< Name of the capability
  1047. }
  1048. irc_cap_table[] =
  1049. {
  1050. { IRC_CAP_MULTI_PREFIX, "multi-prefix" },
  1051. { IRC_CAP_INVITE_NOTIFY, "invite-notify" },
  1052. { IRC_CAP_ECHO_MESSAGE, "echo-message" },
  1053. { IRC_CAP_USERHOST_IN_NAMES, "userhost-in-names" },
  1054. { IRC_CAP_SERVER_TIME, "server-time" },
  1055. };
  1056. static void
  1057. irc_handle_cap_ls (struct client *c, struct irc_cap_args *a)
  1058. {
  1059. if (a->params.len == 1
  1060. && !xstrtoul (&c->cap_version, a->params.vector[0], 10))
  1061. irc_send_reply (c, IRC_ERR_INVALIDCAPCMD,
  1062. a->subcommand, "Ignoring invalid protocol version number");
  1063. c->cap_negotiating = true;
  1064. client_send (c, ":%s CAP %s LS :multi-prefix invite-notify echo-message"
  1065. " userhost-in-names server-time", c->ctx->server_name, a->target);
  1066. }
  1067. static void
  1068. irc_handle_cap_list (struct client *c, struct irc_cap_args *a)
  1069. {
  1070. struct strv caps = strv_make ();
  1071. for (size_t i = 0; i < N_ELEMENTS (irc_cap_table); i++)
  1072. if (c->caps_enabled & irc_cap_table[i].flag)
  1073. strv_append (&caps, irc_cap_table[i].name);
  1074. char *caps_str = strv_join (&caps, " ");
  1075. strv_free (&caps);
  1076. client_send (c, ":%s CAP %s LIST :%s",
  1077. c->ctx->server_name, a->target, caps_str);
  1078. free (caps_str);
  1079. }
  1080. static unsigned
  1081. irc_decode_capability (const char *name)
  1082. {
  1083. for (size_t i = 0; i < N_ELEMENTS (irc_cap_table); i++)
  1084. if (!strcmp (irc_cap_table[i].name, name))
  1085. return irc_cap_table[i].flag;
  1086. return 0;
  1087. }
  1088. static void
  1089. irc_handle_cap_req (struct client *c, struct irc_cap_args *a)
  1090. {
  1091. c->cap_negotiating = true;
  1092. unsigned new_caps = c->caps_enabled;
  1093. bool success = true;
  1094. for (size_t i = 0; i < a->params.len; i++)
  1095. {
  1096. bool removing = false;
  1097. const char *name = a->params.vector[i];
  1098. if (*name == '-')
  1099. {
  1100. removing = true;
  1101. name++;
  1102. }
  1103. unsigned cap;
  1104. if (!(cap = irc_decode_capability (name)))
  1105. success = false;
  1106. else if (removing)
  1107. new_caps &= ~cap;
  1108. else
  1109. new_caps |= cap;
  1110. }
  1111. if (success)
  1112. {
  1113. c->caps_enabled = new_caps;
  1114. client_send (c, ":%s CAP %s ACK :%s",
  1115. c->ctx->server_name, a->target, a->full_params);
  1116. }
  1117. else
  1118. client_send (c, ":%s CAP %s NAK :%s",
  1119. c->ctx->server_name, a->target, a->full_params);
  1120. }
  1121. static void
  1122. irc_handle_cap_ack (struct client *c, struct irc_cap_args *a)
  1123. {
  1124. if (a->params.len)
  1125. irc_send_reply (c, IRC_ERR_INVALIDCAPCMD,
  1126. a->subcommand, "No acknowledgable capabilities supported");
  1127. }
  1128. static void
  1129. irc_handle_cap_end (struct client *c, struct irc_cap_args *a)
  1130. {
  1131. (void) a;
  1132. c->cap_negotiating = false;
  1133. irc_try_finish_registration (c);
  1134. }
  1135. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1136. struct irc_cap_command
  1137. {
  1138. const char *name;
  1139. void (*handler) (struct client *, struct irc_cap_args *);
  1140. };
  1141. static void
  1142. irc_register_cap_handlers (struct server_context *ctx)
  1143. {
  1144. static const struct irc_cap_command cap_handlers[] =
  1145. {
  1146. { "LS", irc_handle_cap_ls },
  1147. { "LIST", irc_handle_cap_list },
  1148. { "REQ", irc_handle_cap_req },
  1149. { "ACK", irc_handle_cap_ack },
  1150. { "END", irc_handle_cap_end },
  1151. };
  1152. for (size_t i = 0; i < N_ELEMENTS (cap_handlers); i++)
  1153. {
  1154. const struct irc_cap_command *cmd = &cap_handlers[i];
  1155. str_map_set (&ctx->cap_handlers, cmd->name, (void *) cmd);
  1156. }
  1157. }
  1158. static void
  1159. irc_handle_cap (const struct irc_message *msg, struct client *c)
  1160. {
  1161. if (msg->params.len < 1)
  1162. RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
  1163. struct irc_cap_args args;
  1164. args.target = c->nickname ? c->nickname : "*";
  1165. args.subcommand = msg->params.vector[0];
  1166. args.full_params = "";
  1167. args.params = strv_make ();
  1168. if (msg->params.len > 1)
  1169. {
  1170. args.full_params = msg->params.vector[1];
  1171. cstr_split (args.full_params, " ", true, &args.params);
  1172. }
  1173. struct irc_cap_command *cmd =
  1174. str_map_find (&c->ctx->cap_handlers, args.subcommand);
  1175. if (!cmd)
  1176. irc_send_reply (c, IRC_ERR_INVALIDCAPCMD,
  1177. args.subcommand, "Invalid CAP subcommand");
  1178. else
  1179. cmd->handler (c, &args);
  1180. strv_free (&args.params);
  1181. }
  1182. static void
  1183. irc_handle_pass (const struct irc_message *msg, struct client *c)
  1184. {
  1185. if (c->registered)
  1186. irc_send_reply (c, IRC_ERR_ALREADYREGISTERED);
  1187. else if (msg->params.len < 1)
  1188. irc_send_reply (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
  1189. // We have TLS client certificates for this purpose; ignoring
  1190. }
  1191. static void
  1192. irc_handle_nick (const struct irc_message *msg, struct client *c)
  1193. {
  1194. struct server_context *ctx = c->ctx;
  1195. if (msg->params.len < 1)
  1196. RETURN_WITH_REPLY (c, IRC_ERR_NONICKNAMEGIVEN);
  1197. const char *nickname = msg->params.vector[0];
  1198. if (irc_validate_nickname (nickname) != VALIDATION_OK)
  1199. RETURN_WITH_REPLY (c, IRC_ERR_ERRONEOUSNICKNAME, nickname);
  1200. struct client *client = str_map_find (&ctx->users, nickname);
  1201. if (client && client != c)
  1202. RETURN_WITH_REPLY (c, IRC_ERR_NICKNAMEINUSE, nickname);
  1203. // Nothing to do here, let's not annoy roommates
  1204. if (c->nickname && !strcmp (c->nickname, nickname))
  1205. return;
  1206. if (c->registered)
  1207. {
  1208. client_add_to_whowas (c);
  1209. char *message = xstrdup_printf (":%s!%s@%s NICK :%s",
  1210. c->nickname, c->username, c->hostname, nickname);
  1211. irc_send_to_roommates (c, message);
  1212. client_send (c, "%s", message);
  1213. free (message);
  1214. }
  1215. // Release the old nickname and allocate a new one
  1216. if (c->nickname)
  1217. str_map_set (&ctx->users, c->nickname, NULL);
  1218. cstr_set (&c->nickname, xstrdup (nickname));
  1219. str_map_set (&ctx->users, nickname, c);
  1220. irc_try_finish_registration (c);
  1221. }
  1222. static void
  1223. irc_handle_user (const struct irc_message *msg, struct client *c)
  1224. {
  1225. if (c->registered)
  1226. RETURN_WITH_REPLY (c, IRC_ERR_ALREADYREGISTERED);
  1227. if (msg->params.len < 4)
  1228. RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
  1229. const char *username = msg->params.vector[0];
  1230. const char *mode = msg->params.vector[1];
  1231. const char *realname = msg->params.vector[3];
  1232. // Unfortunately the protocol doesn't give us any means of rejecting it
  1233. if (!irc_is_valid_user (username))
  1234. username = "xxx";
  1235. cstr_set (&c->username, xstrdup (username));
  1236. cstr_set (&c->realname, xstrdup (realname));
  1237. c->mode = 0;
  1238. unsigned long m;
  1239. if (xstrtoul (&m, mode, 10))
  1240. {
  1241. if (m & 4) c->mode |= IRC_USER_MODE_RX_WALLOPS;
  1242. if (m & 8) c->mode |= IRC_USER_MODE_INVISIBLE;
  1243. }
  1244. irc_try_finish_registration (c);
  1245. }
  1246. static void
  1247. irc_handle_userhost (const struct irc_message *msg, struct client *c)
  1248. {
  1249. if (msg->params.len < 1)
  1250. RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
  1251. struct str reply = str_make ();
  1252. for (size_t i = 0; i < 5 && i < msg->params.len; i++)
  1253. {
  1254. const char *nick = msg->params.vector[i];
  1255. struct client *target = str_map_find (&c->ctx->users, nick);
  1256. if (!target)
  1257. continue;
  1258. if (i)
  1259. str_append_c (&reply, ' ');
  1260. str_append (&reply, nick);
  1261. if (target->mode & IRC_USER_MODE_OPERATOR)
  1262. str_append_c (&reply, '*');
  1263. str_append_printf (&reply, "=%c%s@%s",
  1264. target->away_message ? '-' : '+',
  1265. target->username, target->hostname);
  1266. }
  1267. irc_send_reply (c, IRC_RPL_USERHOST, reply.str);
  1268. str_free (&reply);
  1269. }
  1270. static void
  1271. irc_handle_lusers (const struct irc_message *msg, struct client *c)
  1272. {
  1273. if (msg->params.len > 1 && !irc_is_this_me (c->ctx, msg->params.vector[1]))
  1274. irc_send_reply (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[1]);
  1275. else
  1276. irc_send_lusers (c);
  1277. }
  1278. static void
  1279. irc_handle_motd (const struct irc_message *msg, struct client *c)
  1280. {
  1281. if (msg->params.len > 0 && !irc_is_this_me (c->ctx, msg->params.vector[0]))
  1282. irc_send_reply (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[0]);
  1283. else
  1284. irc_send_motd (c);
  1285. }
  1286. static void
  1287. irc_handle_ping (const struct irc_message *msg, struct client *c)
  1288. {
  1289. // XXX: the RFC is pretty incomprehensible about the exact usage
  1290. if (msg->params.len > 1 && !irc_is_this_me (c->ctx, msg->params.vector[1]))
  1291. irc_send_reply (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[1]);
  1292. else if (msg->params.len < 1)
  1293. irc_send_reply (c, IRC_ERR_NOORIGIN);
  1294. else
  1295. client_send (c, ":%s PONG :%s",
  1296. c->ctx->server_name, msg->params.vector[0]);
  1297. }
  1298. static void
  1299. irc_handle_pong (const struct irc_message *msg, struct client *c)
  1300. {
  1301. // We are the only server, so we don't have to care too much
  1302. if (msg->params.len < 1)
  1303. irc_send_reply (c, IRC_ERR_NOORIGIN);
  1304. else
  1305. // Set a new timer to send another PING
  1306. client_set_ping_timer (c);
  1307. }
  1308. static void
  1309. irc_handle_quit (const struct irc_message *msg, struct client *c)
  1310. {
  1311. char *reason = xstrdup_printf ("Quit: %s",
  1312. msg->params.len > 0 ? msg->params.vector[0] : c->nickname);
  1313. client_close_link (c, reason);
  1314. free (reason);
  1315. }
  1316. static void
  1317. irc_handle_time (const struct irc_message *msg, struct client *c)
  1318. {
  1319. if (msg->params.len > 0 && !irc_is_this_me (c->ctx, msg->params.vector[0]))
  1320. RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[0]);
  1321. char buf[32] = "";
  1322. time_t now = time (NULL);
  1323. struct tm tm;
  1324. strftime (buf, sizeof buf, "%a %b %d %Y %T", localtime_r (&now, &tm));
  1325. irc_send_reply (c, IRC_RPL_TIME, c->ctx->server_name, buf);
  1326. }
  1327. static void
  1328. irc_handle_version (const struct irc_message *msg, struct client *c)
  1329. {
  1330. if (msg->params.len > 0 && !irc_is_this_me (c->ctx, msg->params.vector[0]))
  1331. RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[0]);
  1332. irc_send_reply (c, IRC_RPL_VERSION, PROGRAM_VERSION, g_debug_mode,
  1333. c->ctx->server_name, PROGRAM_NAME " " PROGRAM_VERSION);
  1334. irc_send_isupport (c);
  1335. }
  1336. static void
  1337. irc_channel_multicast (struct channel *chan, const char *message,
  1338. struct client *except)
  1339. {
  1340. for (struct channel_user *iter = chan->users; iter; iter = iter->next)
  1341. if (iter->c != except)
  1342. client_send (iter->c, "%s", message);
  1343. }
  1344. static bool
  1345. irc_modify_mode (unsigned *mask, unsigned mode, bool add)
  1346. {
  1347. unsigned orig = *mask;
  1348. if (add)
  1349. *mask |= mode;
  1350. else
  1351. *mask &= ~mode;
  1352. return *mask != orig;
  1353. }
  1354. static void
  1355. irc_update_user_mode (struct client *c, unsigned new_mode)
  1356. {
  1357. unsigned old_mode = c->mode;
  1358. c->mode = new_mode;
  1359. unsigned added = new_mode & ~old_mode;
  1360. unsigned removed = old_mode & ~new_mode;
  1361. struct str diff = str_make ();
  1362. if (added)
  1363. {
  1364. str_append_c (&diff, '+');
  1365. client_mode_to_str (added, &diff);
  1366. }
  1367. if (removed)
  1368. {
  1369. str_append_c (&diff, '-');
  1370. client_mode_to_str (removed, &diff);
  1371. }
  1372. if (diff.len)
  1373. client_send (c, ":%s MODE %s :%s",
  1374. c->nickname, c->nickname, diff.str);
  1375. str_free (&diff);
  1376. }
  1377. static void
  1378. irc_handle_user_mode_change (struct client *c, const char *mode_string)
  1379. {
  1380. unsigned new_mode = c->mode;
  1381. bool adding = true;
  1382. while (*mode_string)
  1383. switch (*mode_string++)
  1384. {
  1385. case '+': adding = true; break;
  1386. case '-': adding = false; break;
  1387. case 'a':
  1388. // Ignore, the client should use AWAY
  1389. break;
  1390. case 'i':
  1391. irc_modify_mode (&new_mode, IRC_USER_MODE_INVISIBLE, adding);
  1392. break;
  1393. case 'w':
  1394. irc_modify_mode (&new_mode, IRC_USER_MODE_RX_WALLOPS, adding);
  1395. break;
  1396. case 'r':
  1397. // It's not possible to un-restrict yourself
  1398. if (adding)
  1399. new_mode |= IRC_USER_MODE_RESTRICTED;
  1400. break;
  1401. case 'o':
  1402. if (!adding)
  1403. new_mode &= ~IRC_USER_MODE_OPERATOR;
  1404. else if (c->ssl_cert_fingerprint
  1405. && str_map_find (&c->ctx->operators, c->ssl_cert_fingerprint))
  1406. new_mode |= IRC_USER_MODE_OPERATOR;
  1407. else
  1408. client_send (c, ":%s NOTICE %s :Either you're not using an TLS"
  1409. " client certificate, or the fingerprint doesn't match",
  1410. c->ctx->server_name, c->nickname);
  1411. break;
  1412. case 's':
  1413. irc_modify_mode (&new_mode, IRC_USER_MODE_RX_SERVER_NOTICES, adding);
  1414. break;
  1415. default:
  1416. RETURN_WITH_REPLY (c, IRC_ERR_UMODEUNKNOWNFLAG);
  1417. }
  1418. irc_update_user_mode (c, new_mode);
  1419. }
  1420. static void
  1421. irc_send_channel_list (struct client *c, const char *channel_name,
  1422. const struct strv *list, int reply, int end_reply)
  1423. {
  1424. for (size_t i = 0; i < list->len; i++)
  1425. irc_send_reply (c, reply, channel_name, list->vector[i]);
  1426. irc_send_reply (c, end_reply, channel_name);
  1427. }
  1428. static char *
  1429. irc_check_expand_user_mask (const char *mask)
  1430. {
  1431. struct str result = str_make ();
  1432. str_append (&result, mask);
  1433. // Make sure it is a complete mask
  1434. if (!strchr (result.str, '!'))
  1435. str_append (&result, "!*");
  1436. if (!strchr (result.str, '@'))
  1437. str_append (&result, "@*");
  1438. // And validate whatever the result is
  1439. if (!irc_is_valid_user_mask (result.str))
  1440. {
  1441. str_free (&result);
  1442. return NULL;
  1443. }
  1444. return str_steal (&result);
  1445. }
  1446. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1447. // Channel MODE command handling. This is by far the worst command to implement
  1448. // from the whole RFC; don't blame me if it doesn't work exactly as expected.
  1449. struct mode_processor
  1450. {
  1451. // Inputs to set after initialization:
  1452. char **params; ///< Mode string parameters
  1453. struct client *c; ///< Who does the changes
  1454. struct channel *channel; ///< The channel we're modifying
  1455. struct channel_user *user; ///< Presence of the client in the chan
  1456. // Internals:
  1457. bool adding; ///< Currently adding modes
  1458. char mode_char; ///< Currently processed mode char
  1459. struct str added; ///< Added modes
  1460. struct str removed; ///< Removed modes
  1461. struct strv added_params; ///< Params for added modes
  1462. struct strv removed_params; ///< Params for removed modes
  1463. struct str *output; ///< "added" or "removed"
  1464. struct strv *output_params; ///< Similarly for "*_params"
  1465. };
  1466. static struct mode_processor
  1467. mode_processor_make (void)
  1468. {
  1469. return (struct mode_processor)
  1470. {
  1471. .added = str_make (), .added_params = strv_make (),
  1472. .removed = str_make (), .removed_params = strv_make (),
  1473. };
  1474. }
  1475. static void
  1476. mode_processor_free (struct mode_processor *self)
  1477. {
  1478. str_free (&self->added);
  1479. str_free (&self->removed);
  1480. strv_free (&self->added_params);
  1481. strv_free (&self->removed_params);
  1482. }
  1483. static const char *
  1484. mode_processor_next_param (struct mode_processor *self)
  1485. {
  1486. if (!*self->params)
  1487. return NULL;
  1488. return *self->params++;
  1489. }
  1490. static bool
  1491. mode_processor_check_operator (struct mode_processor *self)
  1492. {
  1493. if ((self->user && (self->user->modes & IRC_CHAN_MODE_OPERATOR))
  1494. || (self->c->mode & IRC_USER_MODE_OPERATOR))
  1495. return true;
  1496. irc_send_reply (self->c, IRC_ERR_CHANOPRIVSNEEDED, self->channel->name);
  1497. return false;
  1498. }
  1499. static void
  1500. mode_processor_do_user (struct mode_processor *self, int mode)
  1501. {
  1502. const char *target = mode_processor_next_param (self);
  1503. if (!mode_processor_check_operator (self) || !target)
  1504. return;
  1505. struct client *client;
  1506. struct channel_user *target_user;
  1507. if (!(client = str_map_find (&self->c->ctx->users, target)))
  1508. irc_send_reply (self->c, IRC_ERR_NOSUCHNICK, target);
  1509. else if (!(target_user = channel_get_user (self->channel, client)))
  1510. irc_send_reply (self->c, IRC_ERR_USERNOTINCHANNEL,
  1511. target, self->channel->name);
  1512. else if (irc_modify_mode (&target_user->modes, mode, self->adding))
  1513. {
  1514. str_append_c (self->output, self->mode_char);
  1515. strv_append (self->output_params, client->nickname);
  1516. }
  1517. }
  1518. static bool
  1519. mode_processor_do_chan (struct mode_processor *self, int mode)
  1520. {
  1521. if (!mode_processor_check_operator (self)
  1522. || !irc_modify_mode (&self->channel->modes, mode, self->adding))
  1523. return false;
  1524. str_append_c (self->output, self->mode_char);
  1525. return true;
  1526. }
  1527. static void
  1528. mode_processor_do_chan_remove
  1529. (struct mode_processor *self, char mode_char, int mode)
  1530. {
  1531. if (self->adding
  1532. && irc_modify_mode (&self->channel->modes, mode, false))
  1533. str_append_c (&self->removed, mode_char);
  1534. }
  1535. static void
  1536. mode_processor_do_list (struct mode_processor *self,
  1537. struct strv *list, int list_msg, int end_msg)
  1538. {
  1539. const char *target = mode_processor_next_param (self);
  1540. if (!target)
  1541. {
  1542. if (self->adding)
  1543. irc_send_channel_list (self->c, self->channel->name,
  1544. list, list_msg, end_msg);
  1545. return;
  1546. }
  1547. if (!mode_processor_check_operator (self))
  1548. return;
  1549. char *mask = irc_check_expand_user_mask (target);
  1550. if (!mask)
  1551. return;
  1552. size_t i;
  1553. for (i = 0; i < list->len; i++)
  1554. if (!irc_strcmp (list->vector[i], mask))
  1555. break;
  1556. bool found = i != list->len;
  1557. if (found != self->adding)
  1558. {
  1559. if (self->adding)
  1560. strv_append (list, mask);
  1561. else
  1562. strv_remove (list, i);
  1563. str_append_c (self->output, self->mode_char);
  1564. strv_append (self->output_params, mask);
  1565. }
  1566. free (mask);
  1567. }
  1568. static void
  1569. mode_processor_do_key (struct mode_processor *self)
  1570. {
  1571. const char *target = mode_processor_next_param (self);
  1572. if (!mode_processor_check_operator (self) || !target)
  1573. return;
  1574. if (!self->adding)
  1575. {
  1576. if (!self->channel->key || irc_strcmp (target, self->channel->key))
  1577. return;
  1578. str_append_c (&self->removed, self->mode_char);
  1579. strv_append (&self->removed_params, self->channel->key);
  1580. cstr_set (&self->channel->key, NULL);
  1581. }
  1582. else if (!irc_is_valid_key (target))
  1583. // TODO: we should notify the user somehow
  1584. return;
  1585. else if (self->channel->key)
  1586. irc_send_reply (self->c, IRC_ERR_KEYSET, self->channel->name);
  1587. else
  1588. {
  1589. self->channel->key = xstrdup (target);
  1590. str_append_c (&self->added, self->mode_char);
  1591. strv_append (&self->added_params, self->channel->key);
  1592. }
  1593. }
  1594. static void
  1595. mode_processor_do_limit (struct mode_processor *self)
  1596. {
  1597. if (!mode_processor_check_operator (self))
  1598. return;
  1599. const char *target;
  1600. if (!self->adding)
  1601. {
  1602. if (self->channel->user_limit == -1)
  1603. return;
  1604. self->channel->user_limit = -1;
  1605. str_append_c (&self->removed, self->mode_char);
  1606. }
  1607. else if ((target = mode_processor_next_param (self)))
  1608. {
  1609. unsigned long x;
  1610. if (xstrtoul (&x, target, 10) && x > 0 && x <= LONG_MAX)
  1611. {
  1612. self->channel->user_limit = x;
  1613. str_append_c (&self->added, self->mode_char);
  1614. strv_append (&self->added_params, target);
  1615. }
  1616. }
  1617. }
  1618. static bool
  1619. mode_processor_step (struct mode_processor *self, char mode_char)
  1620. {
  1621. switch ((self->mode_char = mode_char))
  1622. {
  1623. case '+':
  1624. self->adding = true;
  1625. self->output = &self->added;
  1626. self->output_params = &self->added_params;
  1627. break;
  1628. case '-':
  1629. self->adding = false;
  1630. self->output = &self->removed;
  1631. self->output_params = &self->removed_params;
  1632. break;
  1633. #define USER(mode) mode_processor_do_user (self, (mode))
  1634. #define CHAN(mode) mode_processor_do_chan (self, (mode))
  1635. case 'o': USER (IRC_CHAN_MODE_OPERATOR); break;
  1636. case 'v': USER (IRC_CHAN_MODE_VOICE); break;
  1637. case 'i': CHAN (IRC_CHAN_MODE_INVITE_ONLY); break;
  1638. case 'm': CHAN (IRC_CHAN_MODE_MODERATED); break;
  1639. case 'n': CHAN (IRC_CHAN_MODE_NO_OUTSIDE_MSGS); break;
  1640. case 'q': CHAN (IRC_CHAN_MODE_QUIET); break;
  1641. case 't': CHAN (IRC_CHAN_MODE_PROTECTED_TOPIC); break;
  1642. case 'p':
  1643. if (CHAN (IRC_CHAN_MODE_PRIVATE))
  1644. mode_processor_do_chan_remove (self, 's', IRC_CHAN_MODE_SECRET);
  1645. break;
  1646. case 's':
  1647. if (CHAN (IRC_CHAN_MODE_SECRET))
  1648. mode_processor_do_chan_remove (self, 'p', IRC_CHAN_MODE_PRIVATE);
  1649. break;
  1650. #undef USER
  1651. #undef CHAN
  1652. case 'b':
  1653. mode_processor_do_list (self, &self->channel->ban_list,
  1654. IRC_RPL_BANLIST, IRC_RPL_ENDOFBANLIST);
  1655. break;
  1656. case 'e':
  1657. mode_processor_do_list (self, &self->channel->exception_list,
  1658. IRC_RPL_EXCEPTLIST, IRC_RPL_ENDOFEXCEPTLIST);
  1659. break;
  1660. case 'I':
  1661. mode_processor_do_list (self, &self->channel->invite_list,
  1662. IRC_RPL_INVITELIST, IRC_RPL_ENDOFINVITELIST);
  1663. break;
  1664. case 'k':
  1665. mode_processor_do_key (self);
  1666. break;
  1667. case 'l':
  1668. mode_processor_do_limit (self);
  1669. break;
  1670. default:
  1671. // It's not safe to continue, results could be undesired
  1672. irc_send_reply (self->c, IRC_ERR_UNKNOWNMODE,
  1673. mode_char, self->channel->name);
  1674. return false;
  1675. }
  1676. return true;
  1677. }
  1678. static void
  1679. irc_handle_chan_mode_change
  1680. (struct client *c, struct channel *chan, char *params[])
  1681. {
  1682. struct mode_processor p = mode_processor_make ();
  1683. p.params = params;
  1684. p.channel = chan;
  1685. p.c = c;
  1686. p.user = channel_get_user (chan, c);
  1687. const char *mode_string;
  1688. while ((mode_string = mode_processor_next_param (&p)))
  1689. {
  1690. mode_processor_step (&p, '+');
  1691. while (*mode_string)
  1692. if (!mode_processor_step (&p, *mode_string++))
  1693. goto done_processing;
  1694. }
  1695. // TODO: limit to three changes with parameter per command
  1696. done_processing:
  1697. if (p.added.len || p.removed.len)
  1698. {
  1699. struct str message = str_make ();
  1700. str_append_printf (&message, ":%s!%s@%s MODE %s ",
  1701. p.c->nickname, p.c->username, p.c->hostname,
  1702. p.channel->name);
  1703. if (p.added.len)
  1704. str_append_printf (&message, "+%s", p.added.str);
  1705. if (p.removed.len)
  1706. str_append_printf (&message, "-%s", p.removed.str);
  1707. for (size_t i = 0; i < p.added_params.len; i++)
  1708. str_append_printf (&message, " %s", p.added_params.vector[i]);
  1709. for (size_t i = 0; i < p.removed_params.len; i++)
  1710. str_append_printf (&message, " %s", p.removed_params.vector[i]);
  1711. irc_channel_multicast (p.channel, message.str, NULL);
  1712. str_free (&message);
  1713. }
  1714. mode_processor_free (&p);
  1715. }
  1716. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  1717. static void
  1718. irc_handle_mode (const struct irc_message *msg, struct client *c)
  1719. {
  1720. if (msg->params.len < 1)
  1721. RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
  1722. const char *target = msg->params.vector[0];
  1723. struct client *client = str_map_find (&c->ctx->users, target);
  1724. struct channel *chan = str_map_find (&c->ctx->channels, target);
  1725. if (client)
  1726. {
  1727. if (irc_strcmp (target, c->nickname))
  1728. RETURN_WITH_REPLY (c, IRC_ERR_USERSDONTMATCH);
  1729. if (msg->params.len < 2)
  1730. {
  1731. char *mode = client_get_mode (client);
  1732. irc_send_reply (c, IRC_RPL_UMODEIS, mode);
  1733. free (mode);
  1734. }
  1735. else
  1736. irc_handle_user_mode_change (c, msg->params.vector[1]);
  1737. }
  1738. else if (chan)
  1739. {
  1740. if (msg->params.len < 2)
  1741. {
  1742. char *mode = channel_get_mode (chan, channel_get_user (chan, c));
  1743. irc_send_reply (c, IRC_RPL_CHANNELMODEIS, target, mode);
  1744. irc_send_reply (c, IRC_RPL_CREATIONTIME,
  1745. target, (long long) chan->created);
  1746. free (mode);
  1747. }
  1748. else
  1749. irc_handle_chan_mode_change (c, chan, &msg->params.vector[1]);
  1750. }
  1751. else
  1752. irc_send_reply (c, IRC_ERR_NOSUCHNICK, target);
  1753. }
  1754. static void
  1755. irc_handle_user_message (const struct irc_message *msg, struct client *c,
  1756. const char *command, bool allow_away_reply)
  1757. {
  1758. if (msg->params.len < 1)
  1759. RETURN_WITH_REPLY (c, IRC_ERR_NORECIPIENT, msg->command);
  1760. if (msg->params.len < 2 || !*msg->params.vector[1])
  1761. RETURN_WITH_REPLY (c, IRC_ERR_NOTEXTTOSEND);
  1762. const char *target = msg->params.vector[0];
  1763. const char *text = msg->params.vector[1];
  1764. struct client *client = str_map_find (&c->ctx->users, target);
  1765. if (client)
  1766. {
  1767. client_send (client, ":%s!%s@%s %s %s :%s",
  1768. c->nickname, c->username, c->hostname, command, target, text);
  1769. if (allow_away_reply && client->away_message)
  1770. irc_send_reply (c, IRC_RPL_AWAY, target, client->away_message);
  1771. // Acknowledging a message from the client to itself would be silly
  1772. if (client != c && (c->caps_enabled & IRC_CAP_ECHO_MESSAGE))
  1773. client_send (c, ":%s!%s@%s %s %s :%s",
  1774. c->nickname, c->username, c->hostname, command, target, text);
  1775. return;
  1776. }
  1777. struct channel *chan = str_map_find (&c->ctx->channels, target);
  1778. if (chan)
  1779. {
  1780. struct channel_user *user = channel_get_user (chan, c);
  1781. if ((chan->modes & IRC_CHAN_MODE_NO_OUTSIDE_MSGS) && !user)
  1782. RETURN_WITH_REPLY (c, IRC_ERR_CANNOTSENDTOCHAN, target);
  1783. if ((chan->modes & IRC_CHAN_MODE_MODERATED) && (!user ||
  1784. !(user->modes & (IRC_CHAN_MODE_VOICE | IRC_CHAN_MODE_OPERATOR))))
  1785. RETURN_WITH_REPLY (c, IRC_ERR_CANNOTSENDTOCHAN, target);
  1786. if (client_in_mask_list (c, &chan->ban_list)
  1787. && !client_in_mask_list (c, &chan->exception_list))
  1788. RETURN_WITH_REPLY (c, IRC_ERR_CANNOTSENDTOCHAN, target);
  1789. char *message = xstrdup_printf (":%s!%s@%s %s %s :%s",
  1790. c->nickname, c->username, c->hostname, command, target, text);
  1791. irc_channel_multicast (chan, message,
  1792. (c->caps_enabled & IRC_CAP_ECHO_MESSAGE) ? NULL : c);
  1793. free (message);
  1794. return;
  1795. }
  1796. irc_send_reply (c, IRC_ERR_NOSUCHNICK, target);
  1797. }
  1798. static void
  1799. irc_handle_privmsg (const struct irc_message *msg, struct client *c)
  1800. {
  1801. irc_handle_user_message (msg, c, "PRIVMSG", true);
  1802. // Let's not care too much about success or failure
  1803. c->last_active = time (NULL);
  1804. }
  1805. static void
  1806. irc_handle_notice (const struct irc_message *msg, struct client *c)
  1807. {
  1808. irc_handle_user_message (msg, c, "NOTICE", false);
  1809. }
  1810. static void
  1811. irc_send_rpl_list (struct client *c, const struct channel *chan)
  1812. {
  1813. int visible = 0;
  1814. for (struct channel_user *user = chan->users;
  1815. user; user = user->next)
  1816. // XXX: maybe we should skip IRC_USER_MODE_INVISIBLE
  1817. visible++;
  1818. irc_send_reply (c, IRC_RPL_LIST, chan->name, visible, chan->topic);
  1819. }
  1820. static void
  1821. irc_handle_list (const struct irc_message *msg, struct client *c)
  1822. {
  1823. if (msg->params.len > 1 && !irc_is_this_me (c->ctx, msg->params.vector[1]))
  1824. RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[1]);
  1825. struct channel *chan;
  1826. if (msg->params.len == 0)
  1827. {
  1828. struct str_map_iter iter = str_map_iter_make (&c->ctx->channels);
  1829. while ((chan = str_map_iter_next (&iter)))
  1830. if (!(chan->modes & (IRC_CHAN_MODE_PRIVATE | IRC_CHAN_MODE_SECRET))
  1831. || channel_get_user (chan, c))
  1832. irc_send_rpl_list (c, chan);
  1833. }
  1834. else
  1835. {
  1836. struct strv channels = strv_make ();
  1837. cstr_split (msg->params.vector[0], ",", true, &channels);
  1838. for (size_t i = 0; i < channels.len; i++)
  1839. if ((chan = str_map_find (&c->ctx->channels, channels.vector[i]))
  1840. && (!(chan->modes & IRC_CHAN_MODE_SECRET)
  1841. || channel_get_user (chan, c)))
  1842. irc_send_rpl_list (c, chan);
  1843. strv_free (&channels);
  1844. }
  1845. irc_send_reply (c, IRC_RPL_LISTEND);
  1846. }
  1847. static void
  1848. irc_append_prefixes (struct client *c, struct channel_user *user,
  1849. struct str *output)
  1850. {
  1851. struct str prefixes = str_make ();
  1852. if (user->modes & IRC_CHAN_MODE_OPERATOR) str_append_c (&prefixes, '@');
  1853. if (user->modes & IRC_CHAN_MODE_VOICE) str_append_c (&prefixes, '+');
  1854. if (prefixes.len)
  1855. {
  1856. if (c->caps_enabled & IRC_CAP_MULTI_PREFIX)
  1857. str_append (output, prefixes.str);
  1858. else
  1859. str_append_c (output, prefixes.str[0]);
  1860. }
  1861. str_free (&prefixes);
  1862. }
  1863. static char *
  1864. irc_make_rpl_namreply_item
  1865. (struct client *c, struct client *target, struct channel_user *user)
  1866. {
  1867. struct str result = str_make ();
  1868. if (user)
  1869. irc_append_prefixes (c, user, &result);
  1870. str_append (&result, target->nickname);
  1871. if (c->caps_enabled & IRC_CAP_USERHOST_IN_NAMES)
  1872. str_append_printf (&result,
  1873. "!%s@%s", target->username, target->hostname);
  1874. return str_steal (&result);
  1875. }
  1876. static void
  1877. irc_send_rpl_namreply (struct client *c, const struct channel *chan,
  1878. struct str_map *used_nicks)
  1879. {
  1880. char type = '=';
  1881. if (chan->modes & IRC_CHAN_MODE_SECRET)
  1882. type = '@';
  1883. else if (chan->modes & IRC_CHAN_MODE_PRIVATE)
  1884. type = '*';
  1885. bool on_channel = channel_get_user (chan, c);
  1886. struct strv nicks = strv_make ();
  1887. for (struct channel_user *iter = chan->users; iter; iter = iter->next)
  1888. {
  1889. if (!on_channel && (iter->c->mode & IRC_USER_MODE_INVISIBLE))
  1890. continue;
  1891. if (used_nicks)
  1892. str_map_set (used_nicks, iter->c->nickname, (void *) 1);
  1893. strv_append_owned (&nicks,
  1894. irc_make_rpl_namreply_item (c, iter->c, iter));
  1895. }
  1896. irc_send_reply_vector (c, IRC_RPL_NAMREPLY,
  1897. nicks.vector, type, chan->name, "");
  1898. strv_free (&nicks);
  1899. }
  1900. static void
  1901. irc_send_disassociated_names (struct client *c, struct str_map *used)
  1902. {
  1903. struct strv nicks = strv_make ();
  1904. struct str_map_iter iter = str_map_iter_make (&c->ctx->users);
  1905. struct client *target;
  1906. while ((target = str_map_iter_next (&iter)))
  1907. {
  1908. if ((target->mode & IRC_USER_MODE_INVISIBLE)
  1909. || str_map_find (used, target->nickname))
  1910. continue;
  1911. strv_append_owned (&nicks,
  1912. irc_make_rpl_namreply_item (c, target, NULL));
  1913. }
  1914. if (nicks.len)
  1915. irc_send_reply_vector (c, IRC_RPL_NAMREPLY,
  1916. nicks.vector, '*', "*", "");
  1917. strv_free (&nicks);
  1918. }
  1919. static void
  1920. irc_handle_names (const struct irc_message *msg, struct client *c)
  1921. {
  1922. if (msg->params.len > 1 && !irc_is_this_me (c->ctx, msg->params.vector[1]))
  1923. RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[1]);
  1924. struct channel *chan;
  1925. if (msg->params.len == 0)
  1926. {
  1927. struct str_map used = str_map_make (NULL);
  1928. used.key_xfrm = irc_strxfrm;
  1929. struct str_map_iter iter = str_map_iter_make (&c->ctx->channels);
  1930. while ((chan = str_map_iter_next (&iter)))
  1931. if (!(chan->modes & (IRC_CHAN_MODE_PRIVATE | IRC_CHAN_MODE_SECRET))
  1932. || channel_get_user (chan, c))
  1933. irc_send_rpl_namreply (c, chan, &used);
  1934. // Also send all visible users we haven't listed yet
  1935. irc_send_disassociated_names (c, &used);
  1936. str_map_free (&used);
  1937. irc_send_reply (c, IRC_RPL_ENDOFNAMES, "*");
  1938. }
  1939. else
  1940. {
  1941. struct strv channels = strv_make ();
  1942. cstr_split (msg->params.vector[0], ",", true, &channels);
  1943. for (size_t i = 0; i < channels.len; i++)
  1944. if ((chan = str_map_find (&c->ctx->channels, channels.vector[i]))
  1945. && (!(chan->modes & IRC_CHAN_MODE_SECRET)
  1946. || channel_get_user (chan, c)))
  1947. {
  1948. irc_send_rpl_namreply (c, chan, NULL);
  1949. irc_send_reply (c, IRC_RPL_ENDOFNAMES, channels.vector[i]);
  1950. }
  1951. strv_free (&channels);
  1952. }
  1953. }
  1954. static void
  1955. irc_send_rpl_whoreply (struct client *c, const struct channel *chan,
  1956. const struct client *target)
  1957. {
  1958. struct str chars = str_make ();
  1959. str_append_c (&chars, target->away_message ? 'G' : 'H');
  1960. if (target->mode & IRC_USER_MODE_OPERATOR)
  1961. str_append_c (&chars, '*');
  1962. struct channel_user *user;
  1963. if (chan && (user = channel_get_user (chan, target)))
  1964. irc_append_prefixes (c, user, &chars);
  1965. irc_send_reply (c, IRC_RPL_WHOREPLY, chan ? chan->name : "*",
  1966. target->username, target->hostname, target->ctx->server_name,
  1967. target->nickname, chars.str, 0 /* hop count */, target->realname);
  1968. str_free (&chars);
  1969. }
  1970. static void
  1971. irc_match_send_rpl_whoreply (struct client *c, struct client *target,
  1972. const char *mask)
  1973. {
  1974. bool is_roommate = false;
  1975. struct str_map_iter iter = str_map_iter_make (&c->ctx->channels);
  1976. struct channel *chan;
  1977. while ((chan = str_map_iter_next (&iter)))
  1978. if (channel_get_user (chan, target) && channel_get_user (chan, c))
  1979. {
  1980. is_roommate = true;
  1981. break;
  1982. }
  1983. if ((target->mode & IRC_USER_MODE_INVISIBLE) && !is_roommate)
  1984. return;
  1985. if (irc_fnmatch (mask, target->hostname)
  1986. && irc_fnmatch (mask, target->nickname)
  1987. && irc_fnmatch (mask, target->realname)
  1988. && irc_fnmatch (mask, c->ctx->server_name))
  1989. return;
  1990. // Try to find a channel they're on that's visible to us
  1991. struct channel *user_chan = NULL;
  1992. iter = str_map_iter_make (&c->ctx->channels);
  1993. while ((chan = str_map_iter_next (&iter)))
  1994. if (channel_get_user (chan, target)
  1995. && (!(chan->modes & (IRC_CHAN_MODE_PRIVATE | IRC_CHAN_MODE_SECRET))
  1996. || channel_get_user (chan, c)))
  1997. {
  1998. user_chan = chan;
  1999. break;
  2000. }
  2001. irc_send_rpl_whoreply (c, user_chan, target);
  2002. }
  2003. static void
  2004. irc_handle_who (const struct irc_message *msg, struct client *c)
  2005. {
  2006. bool only_ops = msg->params.len > 1 && !strcmp (msg->params.vector[1], "o");
  2007. const char *shown_mask = msg->params.vector[0], *used_mask;
  2008. if (!shown_mask)
  2009. used_mask = shown_mask = "*";
  2010. else if (!strcmp (shown_mask, "0"))
  2011. used_mask = "*";
  2012. else
  2013. used_mask = shown_mask;
  2014. struct channel *chan;
  2015. if ((chan = str_map_find (&c->ctx->channels, used_mask)))
  2016. {
  2017. bool on_chan = !!channel_get_user (chan, c);
  2018. if (on_chan || !(chan->modes & IRC_CHAN_MODE_SECRET))
  2019. for (struct channel_user *iter = chan->users;
  2020. iter; iter = iter->next)
  2021. {
  2022. if ((on_chan || !(iter->c->mode & IRC_USER_MODE_INVISIBLE))
  2023. && (!only_ops || (iter->c->mode & IRC_USER_MODE_OPERATOR)))
  2024. irc_send_rpl_whoreply (c, chan, iter->c);
  2025. }
  2026. }
  2027. else
  2028. {
  2029. struct str_map_iter iter = str_map_iter_make (&c->ctx->users);
  2030. struct client *target;
  2031. while ((target = str_map_iter_next (&iter)))
  2032. if (!only_ops || (target->mode & IRC_USER_MODE_OPERATOR))
  2033. irc_match_send_rpl_whoreply (c, target, used_mask);
  2034. }
  2035. irc_send_reply (c, IRC_RPL_ENDOFWHO, shown_mask);
  2036. }
  2037. static void
  2038. irc_send_whois_reply (struct client *c, const struct client *target)
  2039. {
  2040. const char *nick = target->nickname;
  2041. irc_send_reply (c, IRC_RPL_WHOISUSER, nick,
  2042. target->username, target->hostname, target->realname);
  2043. irc_send_reply (c, IRC_RPL_WHOISSERVER, nick, target->ctx->server_name,
  2044. str_map_find (&c->ctx->config, "server_info"));
  2045. if (target->mode & IRC_USER_MODE_OPERATOR)
  2046. irc_send_reply (c, IRC_RPL_WHOISOPERATOR, nick);
  2047. irc_send_reply (c, IRC_RPL_WHOISIDLE, nick,
  2048. (int) (time (NULL) - target->last_active));
  2049. if (target->away_message)
  2050. irc_send_reply (c, IRC_RPL_AWAY, nick, target->away_message);
  2051. struct strv channels = strv_make ();
  2052. struct str_map_iter iter = str_map_iter_make (&c->ctx->channels);
  2053. struct channel *chan;
  2054. struct channel_user *channel_user;
  2055. while ((chan = str_map_iter_next (&iter)))
  2056. if ((channel_user = channel_get_user (chan, target))
  2057. && (!(chan->modes & (IRC_CHAN_MODE_PRIVATE | IRC_CHAN_MODE_SECRET))
  2058. || channel_get_user (chan, c)))
  2059. {
  2060. struct str item = str_make ();
  2061. if (channel_user->modes & IRC_CHAN_MODE_OPERATOR)
  2062. str_append_c (&item, '@');
  2063. else if (channel_user->modes & IRC_CHAN_MODE_VOICE)
  2064. str_append_c (&item, '+');
  2065. str_append (&item, chan->name);
  2066. strv_append_owned (&channels, str_steal (&item));
  2067. }
  2068. irc_send_reply_vector (c, IRC_RPL_WHOISCHANNELS, channels.vector, nick, "");
  2069. strv_free (&channels);
  2070. irc_send_reply (c, IRC_RPL_ENDOFWHOIS, nick);
  2071. }
  2072. static void
  2073. irc_handle_whois (const struct irc_message *msg, struct client *c)
  2074. {
  2075. if (msg->params.len < 1)
  2076. RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
  2077. if (msg->params.len > 1 && !irc_is_this_me (c->ctx, msg->params.vector[0]))
  2078. RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[0]);
  2079. struct strv masks = strv_make ();
  2080. const char *masks_str = msg->params.vector[msg->params.len > 1];
  2081. cstr_split (masks_str, ",", true, &masks);
  2082. for (size_t i = 0; i < masks.len; i++)
  2083. {
  2084. const char *mask = masks.vector[i];
  2085. struct client *target;
  2086. if (!strpbrk (mask, "*?"))
  2087. {
  2088. if (!(target = str_map_find (&c->ctx->users, mask)))
  2089. irc_send_reply (c, IRC_ERR_NOSUCHNICK, mask);
  2090. else
  2091. irc_send_whois_reply (c, target);
  2092. }
  2093. else
  2094. {
  2095. struct str_map_iter iter = str_map_iter_make (&c->ctx->users);
  2096. bool found = false;
  2097. while ((target = str_map_iter_next (&iter)))
  2098. if (!irc_fnmatch (mask, target->nickname))
  2099. {
  2100. irc_send_whois_reply (c, target);
  2101. found = true;
  2102. }
  2103. if (!found)
  2104. irc_send_reply (c, IRC_ERR_NOSUCHNICK, mask);
  2105. }
  2106. }
  2107. strv_free (&masks);
  2108. }
  2109. static void
  2110. irc_handle_whowas (const struct irc_message *msg, struct client *c)
  2111. {
  2112. if (msg->params.len < 1)
  2113. RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
  2114. if (msg->params.len > 2 && !irc_is_this_me (c->ctx, msg->params.vector[2]))
  2115. RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[2]);
  2116. // The "count" parameter is ignored, we only store one entry for a nick
  2117. struct strv nicks = strv_make ();
  2118. cstr_split (msg->params.vector[0], ",", true, &nicks);
  2119. for (size_t i = 0; i < nicks.len; i++)
  2120. {
  2121. const char *nick = nicks.vector[i];
  2122. struct whowas_info *info = str_map_find (&c->ctx->whowas, nick);
  2123. if (!info)
  2124. irc_send_reply (c, IRC_ERR_WASNOSUCHNICK, nick);
  2125. else
  2126. {
  2127. irc_send_reply (c, IRC_RPL_WHOWASUSER, nick,
  2128. info->username, info->hostname, info->realname);
  2129. irc_send_reply (c, IRC_RPL_WHOISSERVER, nick, c->ctx->server_name,
  2130. str_map_find (&c->ctx->config, "server_info"));
  2131. }
  2132. irc_send_reply (c, IRC_RPL_ENDOFWHOWAS, nick);
  2133. }
  2134. strv_free (&nicks);
  2135. }
  2136. static void
  2137. irc_send_rpl_topic (struct client *c, struct channel *chan)
  2138. {
  2139. if (!*chan->topic)
  2140. irc_send_reply (c, IRC_RPL_NOTOPIC, chan->name);
  2141. else
  2142. {
  2143. irc_send_reply (c, IRC_RPL_TOPIC, chan->name, chan->topic);
  2144. irc_send_reply (c, IRC_RPL_TOPICWHOTIME,
  2145. chan->name, chan->topic_who, (long long) chan->topic_time);
  2146. }
  2147. }
  2148. static void
  2149. irc_handle_topic (const struct irc_message *msg, struct client *c)
  2150. {
  2151. if (msg->params.len < 1)
  2152. RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
  2153. const char *target = msg->params.vector[0];
  2154. struct channel *chan = str_map_find (&c->ctx->channels, target);
  2155. if (!chan)
  2156. RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHCHANNEL, target);
  2157. if (msg->params.len < 2)
  2158. {
  2159. irc_send_rpl_topic (c, chan);
  2160. return;
  2161. }
  2162. struct channel_user *user = channel_get_user (chan, c);
  2163. if (!user)
  2164. RETURN_WITH_REPLY (c, IRC_ERR_NOTONCHANNEL, target);
  2165. if ((chan->modes & IRC_CHAN_MODE_PROTECTED_TOPIC)
  2166. && !(user->modes & IRC_CHAN_MODE_OPERATOR))
  2167. RETURN_WITH_REPLY (c, IRC_ERR_CHANOPRIVSNEEDED, target);
  2168. cstr_set (&chan->topic, xstrdup (msg->params.vector[1]));
  2169. cstr_set (&chan->topic_who, xstrdup_printf
  2170. ("%s!%s@%s", c->nickname, c->username, c->hostname));
  2171. chan->topic_time = time (NULL);
  2172. char *message = xstrdup_printf (":%s!%s@%s TOPIC %s :%s",
  2173. c->nickname, c->username, c->hostname, target, chan->topic);
  2174. irc_channel_multicast (chan, message, NULL);
  2175. free (message);
  2176. }
  2177. static void
  2178. irc_try_part (struct client *c, const char *channel_name, const char *reason)
  2179. {
  2180. if (!reason)
  2181. reason = c->nickname;
  2182. struct channel *chan;
  2183. if (!(chan = str_map_find (&c->ctx->channels, channel_name)))
  2184. RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHCHANNEL, channel_name);
  2185. struct channel_user *user;
  2186. if (!(user = channel_get_user (chan, c)))
  2187. RETURN_WITH_REPLY (c, IRC_ERR_NOTONCHANNEL, channel_name);
  2188. char *message = xstrdup_printf (":%s!%s@%s PART %s :%s",
  2189. c->nickname, c->username, c->hostname, channel_name, reason);
  2190. if (!(chan->modes & IRC_CHAN_MODE_QUIET))
  2191. irc_channel_multicast (chan, message, NULL);
  2192. else
  2193. client_send (c, "%s", message);
  2194. free (message);
  2195. channel_remove_user (chan, user);
  2196. irc_channel_destroy_if_empty (c->ctx, chan);
  2197. }
  2198. static void
  2199. irc_part_all_channels (struct client *c)
  2200. {
  2201. // We have to be careful here, the channel might get destroyed
  2202. struct str_map_unset_iter iter =
  2203. str_map_unset_iter_make (&c->ctx->channels);
  2204. struct channel *chan;
  2205. while ((chan = str_map_unset_iter_next (&iter)))
  2206. if (channel_get_user (chan, c))
  2207. irc_try_part (c, chan->name, NULL);
  2208. str_map_unset_iter_free (&iter);
  2209. }
  2210. static void
  2211. irc_handle_part (const struct irc_message *msg, struct client *c)
  2212. {
  2213. if (msg->params.len < 1)
  2214. RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
  2215. const char *reason = msg->params.len > 1 ? msg->params.vector[1] : NULL;
  2216. struct strv channels = strv_make ();
  2217. cstr_split (msg->params.vector[0], ",", true, &channels);
  2218. for (size_t i = 0; i < channels.len; i++)
  2219. irc_try_part (c, channels.vector[i], reason);
  2220. strv_free (&channels);
  2221. }
  2222. static void
  2223. irc_try_kick (struct client *c, const char *channel_name, const char *nick,
  2224. const char *reason)
  2225. {
  2226. struct channel *chan;
  2227. if (!(chan = str_map_find (&c->ctx->channels, channel_name)))
  2228. RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHCHANNEL, channel_name);
  2229. struct channel_user *user;
  2230. if (!(user = channel_get_user (chan, c)))
  2231. RETURN_WITH_REPLY (c, IRC_ERR_NOTONCHANNEL, channel_name);
  2232. if (!(user->modes & IRC_CHAN_MODE_OPERATOR))
  2233. RETURN_WITH_REPLY (c, IRC_ERR_CHANOPRIVSNEEDED, channel_name);
  2234. struct client *client;
  2235. if (!(client = str_map_find (&c->ctx->users, nick))
  2236. || !(user = channel_get_user (chan, client)))
  2237. RETURN_WITH_REPLY (c, IRC_ERR_USERNOTINCHANNEL, nick, channel_name);
  2238. char *message = xstrdup_printf (":%s!%s@%s KICK %s %s :%s",
  2239. c->nickname, c->username, c->hostname, channel_name, nick, reason);
  2240. if (!(chan->modes & IRC_CHAN_MODE_QUIET))
  2241. irc_channel_multicast (chan, message, NULL);
  2242. else
  2243. client_send (c, "%s", message);
  2244. free (message);
  2245. channel_remove_user (chan, user);
  2246. irc_channel_destroy_if_empty (c->ctx, chan);
  2247. }
  2248. static void
  2249. irc_handle_kick (const struct irc_message *msg, struct client *c)
  2250. {
  2251. if (msg->params.len < 2)
  2252. RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
  2253. const char *reason = c->nickname;
  2254. if (msg->params.len > 2)
  2255. reason = msg->params.vector[2];
  2256. struct strv channels = strv_make ();
  2257. cstr_split (msg->params.vector[0], ",", true, &channels);
  2258. struct strv users = strv_make ();
  2259. cstr_split (msg->params.vector[1], ",", true, &users);
  2260. if (channels.len == 1)
  2261. for (size_t i = 0; i < users.len; i++)
  2262. irc_try_kick (c, channels.vector[0], users.vector[i], reason);
  2263. else
  2264. for (size_t i = 0; i < channels.len && i < users.len; i++)
  2265. irc_try_kick (c, channels.vector[i], users.vector[i], reason);
  2266. strv_free (&channels);
  2267. strv_free (&users);
  2268. }
  2269. static void
  2270. irc_send_invite_notifications
  2271. (struct channel *chan, struct client *c, struct client *target)
  2272. {
  2273. for (struct channel_user *iter = chan->users; iter; iter = iter->next)
  2274. if (iter->c != target && iter->c->caps_enabled & IRC_CAP_INVITE_NOTIFY)
  2275. client_send (iter->c, ":%s!%s@%s INVITE %s %s",
  2276. c->nickname, c->username, c->hostname,
  2277. target->nickname, chan->name);
  2278. }
  2279. static void
  2280. irc_handle_invite (const struct irc_message *msg, struct client *c)
  2281. {
  2282. if (msg->params.len < 2)
  2283. RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
  2284. const char *target = msg->params.vector[0];
  2285. const char *channel_name = msg->params.vector[1];
  2286. struct client *client = str_map_find (&c->ctx->users, target);
  2287. if (!client)
  2288. RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHNICK, target);
  2289. struct channel *chan = str_map_find (&c->ctx->channels, channel_name);
  2290. if (chan)
  2291. {
  2292. struct channel_user *inviting_user;
  2293. if (!(inviting_user = channel_get_user (chan, c)))
  2294. RETURN_WITH_REPLY (c, IRC_ERR_NOTONCHANNEL, channel_name);
  2295. if (channel_get_user (chan, client))
  2296. RETURN_WITH_REPLY (c, IRC_ERR_USERONCHANNEL, target, channel_name);
  2297. if ((inviting_user->modes & IRC_CHAN_MODE_OPERATOR))
  2298. str_map_set (&client->invites, channel_name, (void *) 1);
  2299. else if ((chan->modes & IRC_CHAN_MODE_INVITE_ONLY))
  2300. RETURN_WITH_REPLY (c, IRC_ERR_CHANOPRIVSNEEDED, channel_name);
  2301. // It's not specified when and how we should send out invite-notify
  2302. if (chan->modes & IRC_CHAN_MODE_INVITE_ONLY)
  2303. irc_send_invite_notifications (chan, c, client);
  2304. }
  2305. client_send (client, ":%s!%s@%s INVITE %s %s",
  2306. c->nickname, c->username, c->hostname, client->nickname, channel_name);
  2307. if (client->away_message)
  2308. irc_send_reply (c, IRC_RPL_AWAY,
  2309. client->nickname, client->away_message);
  2310. irc_send_reply (c, IRC_RPL_INVITING, client->nickname, channel_name);
  2311. }
  2312. static void
  2313. irc_try_join (struct client *c, const char *channel_name, const char *key)
  2314. {
  2315. struct channel *chan = str_map_find (&c->ctx->channels, channel_name);
  2316. unsigned user_mode = 0;
  2317. if (!chan)
  2318. {
  2319. if (irc_validate_channel_name (channel_name) != VALIDATION_OK)
  2320. RETURN_WITH_REPLY (c, IRC_ERR_BADCHANMASK, channel_name);
  2321. chan = irc_channel_create (c->ctx, channel_name);
  2322. user_mode = IRC_CHAN_MODE_OPERATOR;
  2323. }
  2324. else if (channel_get_user (chan, c))
  2325. return;
  2326. bool invited_by_chanop = !!str_map_find (&c->invites, channel_name);
  2327. if ((chan->modes & IRC_CHAN_MODE_INVITE_ONLY)
  2328. && !client_in_mask_list (c, &chan->invite_list)
  2329. && !invited_by_chanop)
  2330. RETURN_WITH_REPLY (c, IRC_ERR_INVITEONLYCHAN, channel_name);
  2331. if (chan->key && (!key || strcmp (key, chan->key)))
  2332. RETURN_WITH_REPLY (c, IRC_ERR_BADCHANNELKEY, channel_name);
  2333. if (chan->user_limit != -1
  2334. && channel_user_count (chan) >= (size_t) chan->user_limit)
  2335. RETURN_WITH_REPLY (c, IRC_ERR_CHANNELISFULL, channel_name);
  2336. if (client_in_mask_list (c, &chan->ban_list)
  2337. && !client_in_mask_list (c, &chan->exception_list)
  2338. && !invited_by_chanop)
  2339. RETURN_WITH_REPLY (c, IRC_ERR_BANNEDFROMCHAN, channel_name);
  2340. // Destroy any invitation as there's no other way to get rid of it
  2341. str_map_set (&c->invites, channel_name, NULL);
  2342. channel_add_user (chan, c)->modes = user_mode;
  2343. char *message = xstrdup_printf (":%s!%s@%s JOIN %s",
  2344. c->nickname, c->username, c->hostname, channel_name);
  2345. if (!(chan->modes & IRC_CHAN_MODE_QUIET))
  2346. irc_channel_multicast (chan, message, NULL);
  2347. else
  2348. client_send (c, "%s", message);
  2349. free (message);
  2350. irc_send_rpl_topic (c, chan);
  2351. irc_send_rpl_namreply (c, chan, NULL);
  2352. irc_send_reply (c, IRC_RPL_ENDOFNAMES, chan->name);
  2353. }
  2354. static void
  2355. irc_handle_join (const struct irc_message *msg, struct client *c)
  2356. {
  2357. if (msg->params.len < 1)
  2358. RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
  2359. if (!strcmp (msg->params.vector[0], "0"))
  2360. {
  2361. irc_part_all_channels (c);
  2362. return;
  2363. }
  2364. struct strv channels = strv_make ();
  2365. cstr_split (msg->params.vector[0], ",", true, &channels);
  2366. struct strv keys = strv_make ();
  2367. if (msg->params.len > 1)
  2368. cstr_split (msg->params.vector[1], ",", true, &keys);
  2369. for (size_t i = 0; i < channels.len; i++)
  2370. irc_try_join (c, channels.vector[i],
  2371. i < keys.len ? keys.vector[i] : NULL);
  2372. strv_free (&channels);
  2373. strv_free (&keys);
  2374. }
  2375. static void
  2376. irc_handle_summon (const struct irc_message *msg, struct client *c)
  2377. {
  2378. (void) msg;
  2379. irc_send_reply (c, IRC_ERR_SUMMONDISABLED);
  2380. }
  2381. static void
  2382. irc_handle_users (const struct irc_message *msg, struct client *c)
  2383. {
  2384. (void) msg;
  2385. irc_send_reply (c, IRC_ERR_USERSDISABLED);
  2386. }
  2387. static void
  2388. irc_handle_away (const struct irc_message *msg, struct client *c)
  2389. {
  2390. if (msg->params.len < 1)
  2391. {
  2392. cstr_set (&c->away_message, NULL);
  2393. irc_send_reply (c, IRC_RPL_UNAWAY);
  2394. }
  2395. else
  2396. {
  2397. cstr_set (&c->away_message, xstrdup (msg->params.vector[0]));
  2398. irc_send_reply (c, IRC_RPL_NOWAWAY);
  2399. }
  2400. }
  2401. static void
  2402. irc_handle_ison (const struct irc_message *msg, struct client *c)
  2403. {
  2404. if (msg->params.len < 1)
  2405. RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
  2406. struct str result = str_make ();
  2407. const char *nick;
  2408. if (str_map_find (&c->ctx->users, (nick = msg->params.vector[0])))
  2409. str_append (&result, nick);
  2410. for (size_t i = 1; i < msg->params.len; i++)
  2411. if (str_map_find (&c->ctx->users, (nick = msg->params.vector[i])))
  2412. str_append_printf (&result, " %s", nick);
  2413. irc_send_reply (c, IRC_RPL_ISON, result.str);
  2414. str_free (&result);
  2415. }
  2416. static void
  2417. irc_handle_admin (const struct irc_message *msg, struct client *c)
  2418. {
  2419. if (msg->params.len > 0 && !irc_is_this_me (c->ctx, msg->params.vector[0]))
  2420. RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[0]);
  2421. irc_send_reply (c, IRC_ERR_NOADMININFO, c->ctx->server_name);
  2422. }
  2423. static void
  2424. irc_handle_stats_links (struct client *c, const struct irc_message *msg)
  2425. {
  2426. // There is only an "l" query in RFC 2812 but we cannot link,
  2427. // so instead we provide the "L" query giving information for all users
  2428. const char *filter = NULL;
  2429. if (msg->params.len > 1)
  2430. filter = msg->params.vector[1];
  2431. for (struct client *iter = c->ctx->clients; iter; iter = iter->next)
  2432. {
  2433. if (filter && irc_strcmp (iter->nickname, filter))
  2434. continue;
  2435. irc_send_reply (c, IRC_RPL_STATSLINKINFO,
  2436. iter->address, // linkname
  2437. iter->write_buffer.len, // sendq
  2438. iter->n_sent_messages, iter->sent_bytes / 1024,
  2439. iter->n_received_messages, iter->received_bytes / 1024,
  2440. (long long) (time (NULL) - iter->opened));
  2441. }
  2442. }
  2443. static void
  2444. irc_handle_stats_commands (struct client *c)
  2445. {
  2446. struct str_map_iter iter = str_map_iter_make (&c->ctx->handlers);
  2447. struct irc_command *handler;
  2448. while ((handler = str_map_iter_next (&iter)))
  2449. {
  2450. if (!handler->n_received)
  2451. continue;
  2452. irc_send_reply (c, IRC_RPL_STATSCOMMANDS, handler->name,
  2453. handler->n_received, handler->bytes_received, (size_t) 0);
  2454. }
  2455. }
  2456. static void
  2457. irc_handle_stats_uptime (struct client *c)
  2458. {
  2459. time_t uptime = time (NULL) - c->ctx->started;
  2460. int days = uptime / 60 / 60 / 24;
  2461. int hours = (uptime % (60 * 60 * 24)) / 60 / 60;
  2462. int mins = (uptime % (60 * 60)) / 60;
  2463. int secs = uptime % 60;
  2464. irc_send_reply (c, IRC_RPL_STATSUPTIME, days, hours, mins, secs);
  2465. }
  2466. static void
  2467. irc_handle_stats (const struct irc_message *msg, struct client *c)
  2468. {
  2469. char query = 0;
  2470. if (msg->params.len > 0)
  2471. query = *msg->params.vector[0];
  2472. if (msg->params.len > 1 && !irc_is_this_me (c->ctx, msg->params.vector[1]))
  2473. RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[1]);
  2474. if (!(c->mode & IRC_USER_MODE_OPERATOR))
  2475. RETURN_WITH_REPLY (c, IRC_ERR_NOPRIVILEGES);
  2476. switch (query)
  2477. {
  2478. case 'L': irc_handle_stats_links (c, msg); break;
  2479. case 'm': irc_handle_stats_commands (c); break;
  2480. case 'u': irc_handle_stats_uptime (c); break;
  2481. }
  2482. irc_send_reply (c, IRC_RPL_ENDOFSTATS, query ? query : '*');
  2483. }
  2484. static void
  2485. irc_handle_links (const struct irc_message *msg, struct client *c)
  2486. {
  2487. if (msg->params.len > 1 && !irc_is_this_me (c->ctx, msg->params.vector[0]))
  2488. RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHSERVER, msg->params.vector[0]);
  2489. const char *mask = "*";
  2490. if (msg->params.len > 0)
  2491. mask = msg->params.vector[msg->params.len > 1];
  2492. if (!irc_fnmatch (mask, c->ctx->server_name))
  2493. irc_send_reply (c, IRC_RPL_LINKS, mask,
  2494. c->ctx->server_name, 0 /* hop count */,
  2495. str_map_find (&c->ctx->config, "server_info"));
  2496. irc_send_reply (c, IRC_RPL_ENDOFLINKS, mask);
  2497. }
  2498. static void
  2499. irc_handle_kill (const struct irc_message *msg, struct client *c)
  2500. {
  2501. if (msg->params.len < 2)
  2502. RETURN_WITH_REPLY (c, IRC_ERR_NEEDMOREPARAMS, msg->command);
  2503. if (!(c->mode & IRC_USER_MODE_OPERATOR))
  2504. RETURN_WITH_REPLY (c, IRC_ERR_NOPRIVILEGES);
  2505. struct client *target;
  2506. if (!(target = str_map_find (&c->ctx->users, msg->params.vector[0])))
  2507. RETURN_WITH_REPLY (c, IRC_ERR_NOSUCHNICK, msg->params.vector[0]);
  2508. client_send (target, ":%s!%s@%s KILL %s :%s",
  2509. c->nickname, c->username, c->hostname,
  2510. target->nickname, msg->params.vector[1]);
  2511. char *reason = xstrdup_printf ("Killed by %s: %s",
  2512. c->nickname, msg->params.vector[1]);
  2513. client_close_link (target, reason);
  2514. free (reason);
  2515. }
  2516. static void
  2517. irc_handle_die (const struct irc_message *msg, struct client *c)
  2518. {
  2519. (void) msg;
  2520. if (!(c->mode & IRC_USER_MODE_OPERATOR))
  2521. RETURN_WITH_REPLY (c, IRC_ERR_NOPRIVILEGES);
  2522. if (!c->ctx->quitting)
  2523. irc_initiate_quit (c->ctx);
  2524. }
  2525. // -----------------------------------------------------------------------------
  2526. static void
  2527. irc_register_handlers (struct server_context *ctx)
  2528. {
  2529. // TODO: add an index for IRC_ERR_NOSUCHSERVER validation?
  2530. // TODO: add a minimal parameter count?
  2531. // TODO: add a field for oper-only commands?
  2532. static struct irc_command message_handlers[] =
  2533. {
  2534. { "CAP", false, irc_handle_cap, 0, 0 },
  2535. { "PASS", false, irc_handle_pass, 0, 0 },
  2536. { "NICK", false, irc_handle_nick, 0, 0 },
  2537. { "USER", false, irc_handle_user, 0, 0 },
  2538. { "USERHOST", true, irc_handle_userhost, 0, 0 },
  2539. { "LUSERS", true, irc_handle_lusers, 0, 0 },
  2540. { "MOTD", true, irc_handle_motd, 0, 0 },
  2541. { "PING", true, irc_handle_ping, 0, 0 },
  2542. { "PONG", false, irc_handle_pong, 0, 0 },
  2543. { "QUIT", false, irc_handle_quit, 0, 0 },
  2544. { "TIME", true, irc_handle_time, 0, 0 },
  2545. { "VERSION", true, irc_handle_version, 0, 0 },
  2546. { "USERS", true, irc_handle_users, 0, 0 },
  2547. { "SUMMON", true, irc_handle_summon, 0, 0 },
  2548. { "AWAY", true, irc_handle_away, 0, 0 },
  2549. { "ADMIN", true, irc_handle_admin, 0, 0 },
  2550. { "STATS", true, irc_handle_stats, 0, 0 },
  2551. { "LINKS", true, irc_handle_links, 0, 0 },
  2552. { "MODE", true, irc_handle_mode, 0, 0 },
  2553. { "PRIVMSG", true, irc_handle_privmsg, 0, 0 },
  2554. { "NOTICE", true, irc_handle_notice, 0, 0 },
  2555. { "JOIN", true, irc_handle_join, 0, 0 },
  2556. { "PART", true, irc_handle_part, 0, 0 },
  2557. { "KICK", true, irc_handle_kick, 0, 0 },
  2558. { "INVITE", true, irc_handle_invite, 0, 0 },
  2559. { "TOPIC", true, irc_handle_topic, 0, 0 },
  2560. { "LIST", true, irc_handle_list, 0, 0 },
  2561. { "NAMES", true, irc_handle_names, 0, 0 },
  2562. { "WHO", true, irc_handle_who, 0, 0 },
  2563. { "WHOIS", true, irc_handle_whois, 0, 0 },
  2564. { "WHOWAS", true, irc_handle_whowas, 0, 0 },
  2565. { "ISON", true, irc_handle_ison, 0, 0 },
  2566. { "KILL", true, irc_handle_kill, 0, 0 },
  2567. { "DIE", true, irc_handle_die, 0, 0 },
  2568. };
  2569. for (size_t i = 0; i < N_ELEMENTS (message_handlers); i++)
  2570. {
  2571. const struct irc_command *cmd = &message_handlers[i];
  2572. str_map_set (&ctx->handlers, cmd->name, (void *) cmd);
  2573. }
  2574. }
  2575. static void
  2576. irc_process_message (const struct irc_message *msg,
  2577. const char *raw, void *user_data)
  2578. {
  2579. struct client *c = user_data;
  2580. if (c->closing_link)
  2581. return;
  2582. c->n_received_messages++;
  2583. c->received_bytes += strlen (raw) + 2;
  2584. if (!flood_detector_check (&c->antiflood))
  2585. {
  2586. client_close_link (c, "Excess flood");
  2587. return;
  2588. }
  2589. struct irc_command *cmd = str_map_find (&c->ctx->handlers, msg->command);
  2590. if (!cmd)
  2591. irc_send_reply (c, IRC_ERR_UNKNOWNCOMMAND, msg->command);
  2592. else
  2593. {
  2594. cmd->n_received++;
  2595. cmd->bytes_received += strlen (raw) + 2;
  2596. if (cmd->requires_registration && !c->registered)
  2597. irc_send_reply (c, IRC_ERR_NOTREGISTERED);
  2598. else
  2599. cmd->handler (msg, c);
  2600. }
  2601. }
  2602. // --- Network I/O -------------------------------------------------------------
  2603. static bool
  2604. irc_try_read (struct client *c)
  2605. {
  2606. struct str *buf = &c->read_buffer;
  2607. ssize_t n_read;
  2608. while (true)
  2609. {
  2610. str_reserve (buf, 512);
  2611. n_read = recv (c->socket_fd, buf->str + buf->len,
  2612. buf->alloc - buf->len - 1 /* null byte */, 0);
  2613. if (n_read > 0)
  2614. {
  2615. buf->str[buf->len += n_read] = '\0';
  2616. // TODO: discard characters above the 512 character limit
  2617. irc_process_buffer (buf, irc_process_message, c);
  2618. continue;
  2619. }
  2620. if (n_read == 0)
  2621. {
  2622. client_kill (c, NULL);
  2623. return false;
  2624. }
  2625. if (errno == EAGAIN)
  2626. return true;
  2627. if (errno == EINTR)
  2628. continue;
  2629. print_debug ("%s: %s: %s", __func__, "recv", strerror (errno));
  2630. client_kill (c, strerror (errno));
  2631. return false;
  2632. }
  2633. }
  2634. static bool
  2635. irc_try_read_tls (struct client *c)
  2636. {
  2637. if (c->ssl_tx_want_rx)
  2638. return true;
  2639. struct str *buf = &c->read_buffer;
  2640. c->ssl_rx_want_tx = false;
  2641. while (true)
  2642. {
  2643. str_reserve (buf, 512);
  2644. ERR_clear_error ();
  2645. int n_read = SSL_read (c->ssl, buf->str + buf->len,
  2646. buf->alloc - buf->len - 1 /* null byte */);
  2647. const char *error_info = NULL;
  2648. switch (xssl_get_error (c->ssl, n_read, &error_info))
  2649. {
  2650. case SSL_ERROR_NONE:
  2651. buf->str[buf->len += n_read] = '\0';
  2652. // TODO: discard characters above the 512 character limit
  2653. irc_process_buffer (buf, irc_process_message, c);
  2654. continue;
  2655. case SSL_ERROR_ZERO_RETURN:
  2656. client_kill (c, NULL);
  2657. return false;
  2658. case SSL_ERROR_WANT_READ:
  2659. return true;
  2660. case SSL_ERROR_WANT_WRITE:
  2661. c->ssl_rx_want_tx = true;
  2662. return true;
  2663. case XSSL_ERROR_TRY_AGAIN:
  2664. continue;
  2665. default:
  2666. print_debug ("%s: %s: %s", __func__, "SSL_read", error_info);
  2667. client_kill (c, error_info);
  2668. return false;
  2669. }
  2670. }
  2671. }
  2672. static bool
  2673. irc_try_write (struct client *c)
  2674. {
  2675. struct str *buf = &c->write_buffer;
  2676. ssize_t n_written;
  2677. while (buf->len)
  2678. {
  2679. n_written = send (c->socket_fd, buf->str, buf->len, 0);
  2680. if (n_written >= 0)
  2681. {
  2682. str_remove_slice (buf, 0, n_written);
  2683. continue;
  2684. }
  2685. if (errno == EAGAIN)
  2686. return true;
  2687. if (errno == EINTR)
  2688. continue;
  2689. print_debug ("%s: %s: %s", __func__, "send", strerror (errno));
  2690. client_kill (c, strerror (errno));
  2691. return false;
  2692. }
  2693. return true;
  2694. }
  2695. static bool
  2696. irc_try_write_tls (struct client *c)
  2697. {
  2698. if (c->ssl_rx_want_tx)
  2699. return true;
  2700. struct str *buf = &c->write_buffer;
  2701. c->ssl_tx_want_rx = false;
  2702. while (buf->len)
  2703. {
  2704. ERR_clear_error ();
  2705. int n_written = SSL_write (c->ssl, buf->str, buf->len);
  2706. const char *error_info = NULL;
  2707. switch (xssl_get_error (c->ssl, n_written, &error_info))
  2708. {
  2709. case SSL_ERROR_NONE:
  2710. str_remove_slice (buf, 0, n_written);
  2711. continue;
  2712. case SSL_ERROR_ZERO_RETURN:
  2713. client_kill (c, NULL);
  2714. return false;
  2715. case SSL_ERROR_WANT_WRITE:
  2716. return true;
  2717. case SSL_ERROR_WANT_READ:
  2718. c->ssl_tx_want_rx = true;
  2719. return true;
  2720. case XSSL_ERROR_TRY_AGAIN:
  2721. continue;
  2722. default:
  2723. print_debug ("%s: %s: %s", __func__, "SSL_write", error_info);
  2724. client_kill (c, error_info);
  2725. return false;
  2726. }
  2727. }
  2728. return true;
  2729. }
  2730. // -----------------------------------------------------------------------------
  2731. static bool
  2732. irc_autodetect_tls (struct client *c)
  2733. {
  2734. // Trivial SSL/TLS autodetection. The first block of data returned by
  2735. // recv() must be at least three bytes long for this to work reliably,
  2736. // but that should not pose a problem in practice.
  2737. //
  2738. // SSL2: 1xxx xxxx | xxxx xxxx | <1>
  2739. // (message length) (client hello)
  2740. // SSL3/TLS: <22> | <3> | xxxx xxxx
  2741. // (handshake)| (protocol version)
  2742. //
  2743. // Such byte sequences should never occur at the beginning of regular IRC
  2744. // communication, which usually begins with USER/NICK/PASS/SERVICE.
  2745. char buf[3];
  2746. start:
  2747. switch (recv (c->socket_fd, buf, sizeof buf, MSG_PEEK))
  2748. {
  2749. case 3:
  2750. if ((buf[0] & 0x80) && buf[2] == 1)
  2751. return true;
  2752. // Fall-through
  2753. case 2:
  2754. if (buf[0] == 22 && buf[1] == 3)
  2755. return true;
  2756. break;
  2757. case 1:
  2758. if (buf[0] == 22)
  2759. return true;
  2760. break;
  2761. case 0:
  2762. break;
  2763. default:
  2764. if (errno == EINTR)
  2765. goto start;
  2766. }
  2767. return false;
  2768. }
  2769. static bool
  2770. client_initialize_tls (struct client *c)
  2771. {
  2772. const char *error_info = NULL;
  2773. if (!c->ctx->ssl_ctx)
  2774. {
  2775. error_info = "TLS support disabled";
  2776. goto error_ssl_1;
  2777. }
  2778. ERR_clear_error ();
  2779. c->ssl = SSL_new (c->ctx->ssl_ctx);
  2780. if (!c->ssl)
  2781. goto error_ssl_2;
  2782. if (!SSL_set_fd (c->ssl, c->socket_fd))
  2783. goto error_ssl_3;
  2784. SSL_set_accept_state (c->ssl);
  2785. return true;
  2786. error_ssl_3:
  2787. SSL_free (c->ssl);
  2788. c->ssl = NULL;
  2789. error_ssl_2:
  2790. error_info = ERR_reason_error_string (ERR_get_error ());
  2791. error_ssl_1:
  2792. print_debug ("could not initialize TLS for %s: %s", c->address, error_info);
  2793. return false;
  2794. }
  2795. // -----------------------------------------------------------------------------
  2796. static void
  2797. on_client_ready (const struct pollfd *pfd, void *user_data)
  2798. {
  2799. struct client *c = user_data;
  2800. if (!c->initialized)
  2801. {
  2802. hard_assert (pfd->events == POLLIN);
  2803. if (irc_autodetect_tls (c) && !client_initialize_tls (c))
  2804. {
  2805. client_kill (c, NULL);
  2806. return;
  2807. }
  2808. c->initialized = true;
  2809. client_set_ping_timer (c);
  2810. }
  2811. if (c->ssl)
  2812. {
  2813. // Reads may want to write, writes may want to read, poll() may
  2814. // return unexpected things in `revents'... let's try both
  2815. if (!irc_try_read_tls (c) || !irc_try_write_tls (c))
  2816. return;
  2817. }
  2818. else if (!irc_try_read (c) || !irc_try_write (c))
  2819. return;
  2820. client_update_poller (c, pfd);
  2821. // The purpose of the `closing_link' state is to transfer the `ERROR'
  2822. if (c->closing_link && !c->half_closed && !c->write_buffer.len)
  2823. {
  2824. // To make sure the client has received our ERROR message, we must
  2825. // first half-close the connection, otherwise it could happen that they
  2826. // receive a RST from our TCP stack first when we receive further data
  2827. // We only send the "close notify" alert if libssl can write to the
  2828. // socket at this moment. All the other data has been already written,
  2829. // though, and the client will receive a TCP half-close as usual, so
  2830. // it's not that important if the alert actually gets through.
  2831. if (c->ssl)
  2832. (void) SSL_shutdown (c->ssl);
  2833. // Either the shutdown succeeds, in which case we set a flag so that
  2834. // we don't retry this action and wait until we get an EOF, or it fails
  2835. // and we just kill the client straight away
  2836. if (!shutdown (c->socket_fd, SHUT_WR))
  2837. c->half_closed = true;
  2838. else
  2839. client_kill (c, NULL);
  2840. }
  2841. }
  2842. static void
  2843. client_update_poller (struct client *c, const struct pollfd *pfd)
  2844. {
  2845. // We must not poll for writing when the connection hasn't been initialized
  2846. int new_events = POLLIN;
  2847. if (c->ssl)
  2848. {
  2849. if (c->write_buffer.len || c->ssl_rx_want_tx)
  2850. new_events |= POLLOUT;
  2851. // While we're waiting for an opposite event, we ignore the original
  2852. if (c->ssl_rx_want_tx) new_events &= ~POLLIN;
  2853. if (c->ssl_tx_want_rx) new_events &= ~POLLOUT;
  2854. }
  2855. else if (c->initialized && c->write_buffer.len)
  2856. new_events |= POLLOUT;
  2857. hard_assert (new_events != 0);
  2858. if (!pfd || pfd->events != new_events)
  2859. poller_fd_set (&c->socket_event, new_events);
  2860. }
  2861. static void
  2862. client_finish_connection (struct client *c)
  2863. {
  2864. c->gni = NULL;
  2865. c->address = format_host_port_pair (c->hostname, c->port);
  2866. print_debug ("accepted connection from %s", c->address);
  2867. client_update_poller (c, NULL);
  2868. client_set_kill_timer (c);
  2869. }
  2870. static void
  2871. on_client_gni_resolved (int result, char *host, char *port, void *user_data)
  2872. {
  2873. struct client *c = user_data;
  2874. if (result)
  2875. print_debug ("%s: %s", "getnameinfo", gai_strerror (result));
  2876. else
  2877. {
  2878. cstr_set (&c->hostname, xstrdup (host));
  2879. (void) port;
  2880. }
  2881. poller_timer_reset (&c->gni_timer);
  2882. client_finish_connection (c);
  2883. }
  2884. static void
  2885. on_client_gni_timer (struct client *c)
  2886. {
  2887. async_cancel (&c->gni->async);
  2888. client_finish_connection (c);
  2889. }
  2890. static bool
  2891. irc_try_fetch_client (struct server_context *ctx, int listen_fd)
  2892. {
  2893. // XXX: `struct sockaddr_storage' is not the most portable thing
  2894. struct sockaddr_storage peer;
  2895. socklen_t peer_len = sizeof peer;
  2896. int fd = accept (listen_fd, (struct sockaddr *) &peer, &peer_len);
  2897. if (fd == -1)
  2898. {
  2899. if (errno == EAGAIN || errno == EWOULDBLOCK)
  2900. return false;
  2901. if (errno == EINTR)
  2902. return true;
  2903. if (errno == EBADF
  2904. || errno == EINVAL
  2905. || errno == ENOTSOCK
  2906. || errno == EOPNOTSUPP)
  2907. print_fatal ("%s: %s", "accept", strerror (errno));
  2908. // OS kernels may return a wide range of unforeseeable errors.
  2909. // Assuming that they're either transient or caused by
  2910. // a connection that we've just extracted from the queue.
  2911. print_warning ("%s: %s", "accept", strerror (errno));
  2912. return true;
  2913. }
  2914. hard_assert (peer_len <= sizeof peer);
  2915. set_blocking (fd, false);
  2916. // A little bit questionable once the traffic gets high enough (IMO),
  2917. // but it reduces silly latencies that we don't need because we already
  2918. // do buffer our output
  2919. int yes = 1;
  2920. soft_assert (setsockopt (fd, IPPROTO_TCP, TCP_NODELAY,
  2921. &yes, sizeof yes) != -1);
  2922. if (ctx->max_connections != 0 && ctx->n_clients >= ctx->max_connections)
  2923. {
  2924. print_debug ("connection limit reached, refusing connection");
  2925. close (fd);
  2926. return true;
  2927. }
  2928. char host[NI_MAXHOST] = "unknown", port[NI_MAXSERV] = "unknown";
  2929. int err = getnameinfo ((struct sockaddr *) &peer, peer_len,
  2930. host, sizeof host, port, sizeof port, NI_NUMERICHOST | NI_NUMERICSERV);
  2931. if (err)
  2932. print_debug ("%s: %s", "getnameinfo", gai_strerror (err));
  2933. struct client *c = client_new ();
  2934. c->ctx = ctx;
  2935. c->opened = time (NULL);
  2936. c->socket_fd = fd;
  2937. c->hostname = xstrdup (host);
  2938. c->port = xstrdup (port);
  2939. c->last_active = time (NULL);
  2940. LIST_PREPEND (ctx->clients, c);
  2941. ctx->n_clients++;
  2942. c->socket_event = poller_fd_make (&c->ctx->poller, c->socket_fd);
  2943. c->socket_event.dispatcher = (poller_fd_fn) on_client_ready;
  2944. c->socket_event.user_data = c;
  2945. c->kill_timer = poller_timer_make (&c->ctx->poller);
  2946. c->kill_timer.dispatcher = (poller_timer_fn) on_client_kill_timer;
  2947. c->kill_timer.user_data = c;
  2948. c->timeout_timer = poller_timer_make (&c->ctx->poller);
  2949. c->timeout_timer.dispatcher = (poller_timer_fn) on_client_timeout_timer;
  2950. c->timeout_timer.user_data = c;
  2951. c->ping_timer = poller_timer_make (&c->ctx->poller);
  2952. c->ping_timer.dispatcher = (poller_timer_fn) on_client_ping_timer;
  2953. c->ping_timer.user_data = c;
  2954. // Resolve the client's hostname first; this is a blocking operation that
  2955. // depends on the network, so run it asynchronously with some timeout
  2956. c->gni = async_getnameinfo (&ctx->poller.common.async,
  2957. (const struct sockaddr *) &peer, peer_len, NI_NUMERICSERV);
  2958. c->gni->dispatcher = on_client_gni_resolved;
  2959. c->gni->user_data = c;
  2960. c->gni_timer = poller_timer_make (&c->ctx->poller);
  2961. c->gni_timer.dispatcher = (poller_timer_fn) on_client_gni_timer;
  2962. c->gni_timer.user_data = c;
  2963. poller_timer_set (&c->gni_timer, 5000);
  2964. return true;
  2965. }
  2966. static void
  2967. on_irc_client_available (const struct pollfd *pfd, void *user_data)
  2968. {
  2969. struct server_context *ctx = user_data;
  2970. while (irc_try_fetch_client (ctx, pfd->fd))
  2971. ;
  2972. }
  2973. // --- Application setup -------------------------------------------------------
  2974. static int
  2975. irc_ssl_verify_callback (int verify_ok, X509_STORE_CTX *ctx)
  2976. {
  2977. (void) verify_ok;
  2978. (void) ctx;
  2979. // RFC 5246: "If the client has sent a certificate with signing ability,
  2980. // a digitally-signed CertificateVerify message is sent to explicitly
  2981. // verify possession of the private key in the certificate."
  2982. //
  2983. // The handshake will fail if the client doesn't have a matching private
  2984. // key, see OpenSSL's tls_process_cert_verify(), and the CertificateVerify
  2985. // message cannot be skipped (except for a case where it doesn't matter).
  2986. // Thus we're fine checking just the cryptographic hash of the certificate.
  2987. // We only want to provide additional privileges based on the client's
  2988. // certificate, so let's not terminate the connection because of a failure
  2989. // (especially since self-signed certificates are likely to be used).
  2990. return 1;
  2991. }
  2992. static void
  2993. irc_ssl_info_callback (const SSL *ssl, int where, int ret)
  2994. {
  2995. // For debugging only; provides us with the most important information
  2996. struct str s = str_make ();
  2997. if (where & SSL_CB_LOOP)
  2998. str_append_printf (&s, "loop (%s) ",
  2999. SSL_state_string_long (ssl));
  3000. if (where & SSL_CB_EXIT)
  3001. str_append_printf (&s, "exit (%d in %s) ", ret,
  3002. SSL_state_string_long (ssl));
  3003. if (where & SSL_CB_READ) str_append (&s, "read ");
  3004. if (where & SSL_CB_WRITE) str_append (&s, "write ");
  3005. if (where & SSL_CB_ALERT)
  3006. str_append_printf (&s, "alert (%s: %s) ",
  3007. SSL_alert_type_string_long (ret),
  3008. SSL_alert_desc_string_long (ret));
  3009. if (where & SSL_CB_HANDSHAKE_START) str_append (&s, "handshake start ");
  3010. if (where & SSL_CB_HANDSHAKE_DONE) str_append (&s, "handshake done ");
  3011. print_debug ("ssl <%p> %s", ssl, s.str);
  3012. str_free (&s);
  3013. }
  3014. static bool
  3015. irc_initialize_ssl_ctx (struct server_context *ctx,
  3016. const char *cert_path, const char *key_path, struct error **e)
  3017. {
  3018. ERR_clear_error ();
  3019. ctx->ssl_ctx = SSL_CTX_new (SSLv23_server_method ());
  3020. if (!ctx->ssl_ctx)
  3021. {
  3022. error_set (e, "%s: %s", "could not initialize TLS",
  3023. ERR_reason_error_string (ERR_get_error ()));
  3024. return false;
  3025. }
  3026. SSL_CTX_set_verify (ctx->ssl_ctx,
  3027. SSL_VERIFY_PEER | SSL_VERIFY_CLIENT_ONCE, irc_ssl_verify_callback);
  3028. if (g_debug_mode)
  3029. SSL_CTX_set_info_callback (ctx->ssl_ctx, irc_ssl_info_callback);
  3030. const unsigned char session_id_context[SSL_MAX_SSL_SESSION_ID_LENGTH]
  3031. = PROGRAM_NAME;
  3032. (void) SSL_CTX_set_session_id_context (ctx->ssl_ctx,
  3033. session_id_context, sizeof session_id_context);
  3034. // IRC is not particularly reconnect-heavy, prefer forward secrecy
  3035. SSL_CTX_set_session_cache_mode (ctx->ssl_ctx, SSL_SESS_CACHE_OFF);
  3036. // Gah, spare me your awkward semantics, I just want to push data!
  3037. SSL_CTX_set_mode (ctx->ssl_ctx,
  3038. SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_ENABLE_PARTIAL_WRITE);
  3039. // Disable deprecated protocols (see RFC 7568)
  3040. SSL_CTX_set_options (ctx->ssl_ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3);
  3041. // XXX: perhaps we should read the files ourselves for better messages
  3042. const char *ciphers = str_map_find (&ctx->config, "tls_ciphers");
  3043. if (!SSL_CTX_set_cipher_list (ctx->ssl_ctx, ciphers))
  3044. error_set (e, "failed to select any cipher from the cipher list");
  3045. else if (!SSL_CTX_use_certificate_chain_file (ctx->ssl_ctx, cert_path))
  3046. error_set (e, "%s: %s", "setting the TLS certificate failed",
  3047. ERR_reason_error_string (ERR_get_error ()));
  3048. else if (!SSL_CTX_use_PrivateKey_file
  3049. (ctx->ssl_ctx, key_path, SSL_FILETYPE_PEM))
  3050. error_set (e, "%s: %s", "setting the TLS private key failed",
  3051. ERR_reason_error_string (ERR_get_error ()));
  3052. else
  3053. // TODO: SSL_CTX_check_private_key()? It has probably already been
  3054. // checked by SSL_CTX_use_PrivateKey_file() above.
  3055. return true;
  3056. SSL_CTX_free (ctx->ssl_ctx);
  3057. ctx->ssl_ctx = NULL;
  3058. return false;
  3059. }
  3060. static bool
  3061. irc_initialize_tls (struct server_context *ctx, struct error **e)
  3062. {
  3063. const char *tls_cert = str_map_find (&ctx->config, "tls_cert");
  3064. const char *tls_key = str_map_find (&ctx->config, "tls_key");
  3065. // Only try to enable SSL support if the user configures it; it is not
  3066. // a failure if no one has requested it.
  3067. if (!tls_cert && !tls_key)
  3068. return true;
  3069. if (!tls_cert)
  3070. error_set (e, "no TLS certificate set");
  3071. else if (!tls_key)
  3072. error_set (e, "no TLS private key set");
  3073. if (!tls_cert || !tls_key)
  3074. return false;
  3075. bool result = false;
  3076. char *cert_path = resolve_filename
  3077. (tls_cert, resolve_relative_config_filename);
  3078. char *key_path = resolve_filename
  3079. (tls_key, resolve_relative_config_filename);
  3080. if (!cert_path)
  3081. error_set (e, "%s: %s", "cannot open file", tls_cert);
  3082. else if (!key_path)
  3083. error_set (e, "%s: %s", "cannot open file", tls_key);
  3084. else
  3085. result = irc_initialize_ssl_ctx (ctx, cert_path, key_path, e);
  3086. free (cert_path);
  3087. free (key_path);
  3088. return result;
  3089. }
  3090. static bool
  3091. irc_initialize_catalog (struct server_context *ctx, struct error **e)
  3092. {
  3093. hard_assert (ctx->catalog == (nl_catd) -1);
  3094. const char *catalog = str_map_find (&ctx->config, "catalog");
  3095. if (!catalog)
  3096. return true;
  3097. char *path = resolve_filename (catalog, resolve_relative_config_filename);
  3098. if (!path)
  3099. {
  3100. error_set (e, "%s: %s", "cannot open file", catalog);
  3101. return false;
  3102. }
  3103. ctx->catalog = catopen (path, NL_CAT_LOCALE);
  3104. free (path);
  3105. if (ctx->catalog == (nl_catd) -1)
  3106. {
  3107. error_set (e, "%s: %s",
  3108. "failed reading the message catalog file", strerror (errno));
  3109. return false;
  3110. }
  3111. return true;
  3112. }
  3113. static bool
  3114. irc_initialize_motd (struct server_context *ctx, struct error **e)
  3115. {
  3116. hard_assert (ctx->motd.len == 0);
  3117. const char *motd = str_map_find (&ctx->config, "motd");
  3118. if (!motd)
  3119. return true;
  3120. char *path = resolve_filename (motd, resolve_relative_config_filename);
  3121. if (!path)
  3122. {
  3123. error_set (e, "%s: %s", "cannot open file", motd);
  3124. return false;
  3125. }
  3126. FILE *fp = fopen (path, "r");
  3127. free (path);
  3128. if (!fp)
  3129. {
  3130. error_set (e, "%s: %s",
  3131. "failed reading the MOTD file", strerror (errno));
  3132. return false;
  3133. }
  3134. struct str line = str_make ();
  3135. while (read_line (fp, &line))
  3136. strv_append_owned (&ctx->motd, str_steal (&line));
  3137. str_free (&line);
  3138. fclose (fp);
  3139. return true;
  3140. }
  3141. /// This function handles values that require validation before their first use,
  3142. /// or some kind of a transformation (such as conversion to an integer) needs
  3143. /// to be done before they can be used directly.
  3144. static bool
  3145. irc_parse_config (struct server_context *ctx, struct error **e)
  3146. {
  3147. unsigned long ul;
  3148. #define PARSE_UNSIGNED(name, min, max) \
  3149. const char *name = str_map_find (&ctx->config, #name); \
  3150. hard_assert (name != NULL); \
  3151. if (!xstrtoul (&ul, name, 10) || ul > max || ul < min) \
  3152. { \
  3153. error_set (e, "invalid configuration value for `%s': %s", \
  3154. #name, "the number is invalid or out of range"); \
  3155. return false; \
  3156. } \
  3157. ctx->name = ul
  3158. PARSE_UNSIGNED (ping_interval, 1, UINT_MAX);
  3159. PARSE_UNSIGNED (max_connections, 0, UINT_MAX);
  3160. bool result = true;
  3161. struct strv fingerprints = strv_make ();
  3162. const char *operators = str_map_find (&ctx->config, "operators");
  3163. if (operators)
  3164. cstr_split (operators, ",", true, &fingerprints);
  3165. for (size_t i = 0; i < fingerprints.len; i++)
  3166. {
  3167. const char *key = fingerprints.vector[i];
  3168. if (!irc_is_valid_fingerprint (key))
  3169. {
  3170. error_set (e, "invalid configuration value for `%s': %s",
  3171. "operators", "invalid fingerprint value");
  3172. result = false;
  3173. break;
  3174. }
  3175. str_map_set (&ctx->operators, key, (void *) 1);
  3176. }
  3177. strv_free (&fingerprints);
  3178. return result;
  3179. }
  3180. static bool
  3181. irc_initialize_server_name (struct server_context *ctx, struct error **e)
  3182. {
  3183. enum validation_result res;
  3184. const char *server_name = str_map_find (&ctx->config, "server_name");
  3185. if (server_name)
  3186. {
  3187. res = irc_validate_hostname (server_name);
  3188. if (res != VALIDATION_OK)
  3189. {
  3190. error_set (e, "invalid configuration value for `%s': %s",
  3191. "server_name", irc_validate_to_str (res));
  3192. return false;
  3193. }
  3194. ctx->server_name = xstrdup (server_name);
  3195. }
  3196. else
  3197. {
  3198. long host_name_max = sysconf (_SC_HOST_NAME_MAX);
  3199. if (host_name_max <= 0)
  3200. host_name_max = _POSIX_HOST_NAME_MAX;
  3201. char hostname[host_name_max + 1];
  3202. if (gethostname (hostname, sizeof hostname))
  3203. {
  3204. error_set (e, "%s: %s",
  3205. "getting the hostname failed", strerror (errno));
  3206. return false;
  3207. }
  3208. res = irc_validate_hostname (hostname);
  3209. if (res != VALIDATION_OK)
  3210. {
  3211. error_set (e,
  3212. "`%s' is not set and the hostname (`%s') cannot be used: %s",
  3213. "server_name", hostname, irc_validate_to_str (res));
  3214. return false;
  3215. }
  3216. ctx->server_name = xstrdup (hostname);
  3217. }
  3218. return true;
  3219. }
  3220. static bool
  3221. irc_lock_pid_file (struct server_context *ctx, struct error **e)
  3222. {
  3223. const char *path = str_map_find (&ctx->config, "pid_file");
  3224. if (!path)
  3225. return true;
  3226. char *resolved = resolve_filename (path, resolve_relative_runtime_filename);
  3227. bool result = lock_pid_file (resolved, e) != -1;
  3228. free (resolved);
  3229. return result;
  3230. }
  3231. static int
  3232. irc_listen (struct addrinfo *gai_iter)
  3233. {
  3234. int fd = socket (gai_iter->ai_family,
  3235. gai_iter->ai_socktype, gai_iter->ai_protocol);
  3236. if (fd == -1)
  3237. return -1;
  3238. set_cloexec (fd);
  3239. int yes = 1;
  3240. soft_assert (setsockopt (fd, SOL_SOCKET, SO_KEEPALIVE,
  3241. &yes, sizeof yes) != -1);
  3242. soft_assert (setsockopt (fd, SOL_SOCKET, SO_REUSEADDR,
  3243. &yes, sizeof yes) != -1);
  3244. char host[NI_MAXHOST], port[NI_MAXSERV];
  3245. host[0] = port[0] = '\0';
  3246. int err = getnameinfo (gai_iter->ai_addr, gai_iter->ai_addrlen,
  3247. host, sizeof host, port, sizeof port,
  3248. NI_NUMERICHOST | NI_NUMERICSERV);
  3249. if (err)
  3250. print_debug ("%s: %s", "getnameinfo", gai_strerror (err));
  3251. char *address = format_host_port_pair (host, port);
  3252. if (bind (fd, gai_iter->ai_addr, gai_iter->ai_addrlen))
  3253. print_error ("bind to %s failed: %s", address, strerror (errno));
  3254. else if (listen (fd, 16 /* arbitrary number */))
  3255. print_error ("listen on %s failed: %s", address, strerror (errno));
  3256. else
  3257. {
  3258. print_status ("listening on %s", address);
  3259. free (address);
  3260. return fd;
  3261. }
  3262. free (address);
  3263. xclose (fd);
  3264. return -1;
  3265. }
  3266. static void
  3267. irc_listen_resolve (struct server_context *ctx,
  3268. const char *host, const char *port, struct addrinfo *gai_hints)
  3269. {
  3270. struct addrinfo *gai_result, *gai_iter;
  3271. int err = getaddrinfo (host, port, gai_hints, &gai_result);
  3272. if (err)
  3273. {
  3274. char *address = format_host_port_pair (host, port);
  3275. print_error ("bind to %s failed: %s: %s",
  3276. address, "getaddrinfo", gai_strerror (err));
  3277. free (address);
  3278. return;
  3279. }
  3280. int fd;
  3281. for (gai_iter = gai_result; gai_iter; gai_iter = gai_iter->ai_next)
  3282. {
  3283. if ((fd = irc_listen (gai_iter)) == -1)
  3284. continue;
  3285. set_blocking (fd, false);
  3286. struct poller_fd *event = &ctx->listen_events[ctx->n_listen_fds];
  3287. *event = poller_fd_make (&ctx->poller, fd);
  3288. event->dispatcher = (poller_fd_fn) on_irc_client_available;
  3289. event->user_data = ctx;
  3290. ctx->listen_fds[ctx->n_listen_fds++] = fd;
  3291. poller_fd_set (event, POLLIN);
  3292. break;
  3293. }
  3294. freeaddrinfo (gai_result);
  3295. }
  3296. static bool
  3297. irc_setup_listen_fds (struct server_context *ctx, struct error **e)
  3298. {
  3299. const char *bind_host = str_map_find (&ctx->config, "bind_host");
  3300. const char *bind_port = str_map_find (&ctx->config, "bind_port");
  3301. hard_assert (bind_port != NULL); // We have a default value for this
  3302. struct addrinfo gai_hints;
  3303. memset (&gai_hints, 0, sizeof gai_hints);
  3304. gai_hints.ai_socktype = SOCK_STREAM;
  3305. gai_hints.ai_flags = AI_PASSIVE;
  3306. struct strv ports = strv_make ();
  3307. cstr_split (bind_port, ",", true, &ports);
  3308. ctx->listen_fds = xcalloc (ports.len, sizeof *ctx->listen_fds);
  3309. ctx->listen_events = xcalloc (ports.len, sizeof *ctx->listen_events);
  3310. for (size_t i = 0; i < ports.len; i++)
  3311. irc_listen_resolve (ctx, bind_host, ports.vector[i], &gai_hints);
  3312. strv_free (&ports);
  3313. if (!ctx->n_listen_fds)
  3314. {
  3315. error_set (e, "%s: %s",
  3316. "network setup failed", "no ports to listen on");
  3317. return false;
  3318. }
  3319. return true;
  3320. }
  3321. // --- Main --------------------------------------------------------------------
  3322. static void
  3323. on_signal_pipe_readable (const struct pollfd *fd, struct server_context *ctx)
  3324. {
  3325. char dummy;
  3326. (void) read (fd->fd, &dummy, 1);
  3327. if (g_termination_requested && !ctx->quitting)
  3328. irc_initiate_quit (ctx);
  3329. }
  3330. static void
  3331. daemonize (struct server_context *ctx)
  3332. {
  3333. print_status ("daemonizing...");
  3334. if (chdir ("/"))
  3335. exit_fatal ("%s: %s", "chdir", strerror (errno));
  3336. // Because of systemd, we need to exit the parent process _after_ writing
  3337. // a PID file, otherwise our grandchild would receive a SIGTERM
  3338. int sync_pipe[2];
  3339. if (pipe (sync_pipe))
  3340. exit_fatal ("%s: %s", "pipe", strerror (errno));
  3341. pid_t pid;
  3342. if ((pid = fork ()) < 0)
  3343. exit_fatal ("%s: %s", "fork", strerror (errno));
  3344. else if (pid)
  3345. {
  3346. // Wait until all write ends of the pipe are closed, which can mean
  3347. // either success or failure, we don't need to care
  3348. xclose (sync_pipe[PIPE_WRITE]);
  3349. char dummy;
  3350. if (read (sync_pipe[PIPE_READ], &dummy, 1) < 0)
  3351. exit_fatal ("%s: %s", "read", strerror (errno));
  3352. exit (EXIT_SUCCESS);
  3353. }
  3354. setsid ();
  3355. signal (SIGHUP, SIG_IGN);
  3356. if ((pid = fork ()) < 0)
  3357. exit_fatal ("%s: %s", "fork", strerror (errno));
  3358. else if (pid)
  3359. exit (EXIT_SUCCESS);
  3360. openlog (PROGRAM_NAME, LOG_NDELAY | LOG_NOWAIT | LOG_PID, 0);
  3361. g_log_message_real = log_message_syslog;
  3362. // Write the PID file (if so configured) and get rid of the pipe, so that
  3363. // the read() in our grandparent finally returns zero (no write ends)
  3364. struct error *e = NULL;
  3365. if (!irc_lock_pid_file (ctx, &e))
  3366. exit_fatal ("%s", e->message);
  3367. xclose (sync_pipe[PIPE_READ]);
  3368. xclose (sync_pipe[PIPE_WRITE]);
  3369. // XXX: we may close our own descriptors this way, crippling ourselves;
  3370. // there is no real guarantee that we will start with all three
  3371. // descriptors open. In theory we could try to enumerate the descriptors
  3372. // at the start of main().
  3373. for (int i = 0; i < 3; i++)
  3374. xclose (i);
  3375. int tty = open ("/dev/null", O_RDWR);
  3376. if (tty != 0 || dup (0) != 1 || dup (0) != 2)
  3377. exit_fatal ("failed to reopen FD's: %s", strerror (errno));
  3378. poller_post_fork (&ctx->poller);
  3379. }
  3380. int
  3381. main (int argc, char *argv[])
  3382. {
  3383. // Need to call this first as all string maps depend on it
  3384. siphash_wrapper_randomize ();
  3385. static const struct opt opts[] =
  3386. {
  3387. { 'd', "debug", NULL, 0, "run in debug mode (do not daemonize)" },
  3388. { 'h', "help", NULL, 0, "display this help and exit" },
  3389. { 'V', "version", NULL, 0, "output version information and exit" },
  3390. { 'w', "write-default-cfg", "FILENAME",
  3391. OPT_OPTIONAL_ARG | OPT_LONG_ONLY,
  3392. "write a default configuration file and exit" },
  3393. { 0, NULL, NULL, 0, NULL }
  3394. };
  3395. struct opt_handler oh =
  3396. opt_handler_make (argc, argv, opts, NULL, "Experimental IRC daemon.");
  3397. int c;
  3398. while ((c = opt_handler_get (&oh)) != -1)
  3399. switch (c)
  3400. {
  3401. case 'd':
  3402. g_debug_mode = true;
  3403. break;
  3404. case 'h':
  3405. opt_handler_usage (&oh, stdout);
  3406. exit (EXIT_SUCCESS);
  3407. case 'V':
  3408. printf (PROGRAM_NAME " " PROGRAM_VERSION "\n");
  3409. exit (EXIT_SUCCESS);
  3410. case 'w':
  3411. call_simple_config_write_default (optarg, g_config_table);
  3412. exit (EXIT_SUCCESS);
  3413. default:
  3414. print_error ("wrong options");
  3415. opt_handler_usage (&oh, stderr);
  3416. exit (EXIT_FAILURE);
  3417. }
  3418. opt_handler_free (&oh);
  3419. print_status (PROGRAM_NAME " " PROGRAM_VERSION " starting");
  3420. setup_signal_handlers ();
  3421. init_openssl ();
  3422. struct server_context ctx;
  3423. server_context_init (&ctx);
  3424. ctx.started = time (NULL);
  3425. irc_register_handlers (&ctx);
  3426. irc_register_cap_handlers (&ctx);
  3427. struct error *e = NULL;
  3428. if (!simple_config_update_from_file (&ctx.config, &e))
  3429. {
  3430. print_error ("error loading configuration: %s", e->message);
  3431. error_free (e);
  3432. exit (EXIT_FAILURE);
  3433. }
  3434. ctx.signal_event = poller_fd_make (&ctx.poller, g_signal_pipe[0]);
  3435. ctx.signal_event.dispatcher = (poller_fd_fn) on_signal_pipe_readable;
  3436. ctx.signal_event.user_data = &ctx;
  3437. poller_fd_set (&ctx.signal_event, POLLIN);
  3438. if (!irc_initialize_tls (&ctx, &e)
  3439. || !irc_initialize_server_name (&ctx, &e)
  3440. || !irc_initialize_motd (&ctx, &e)
  3441. || !irc_initialize_catalog (&ctx, &e)
  3442. || !irc_parse_config (&ctx, &e)
  3443. || !irc_setup_listen_fds (&ctx, &e))
  3444. exit_fatal ("%s", e->message);
  3445. if (!g_debug_mode)
  3446. daemonize (&ctx);
  3447. else if (!irc_lock_pid_file (&ctx, &e))
  3448. exit_fatal ("%s", e->message);
  3449. #if OpenBSD >= 201605
  3450. // This won't be as simple once we decide to implement REHASH
  3451. if (pledge ("stdio inet dns", NULL))
  3452. exit_fatal ("%s: %s", "pledge", strerror (errno));
  3453. #endif
  3454. ctx.polling = true;
  3455. while (ctx.polling)
  3456. poller_run (&ctx.poller);
  3457. server_context_free (&ctx);
  3458. return EXIT_SUCCESS;
  3459. }