smtp.c 111 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346
  1. /**
  2. * @file
  3. * @brief SMTP client library.
  4. * @author James Humphrey (mail@somnisoft.com)
  5. * @version 1.00
  6. *
  7. * This SMTP client library allows the user to send emails to an SMTP server.
  8. * The user can include custom headers and MIME attachments.
  9. *
  10. * This software has been placed into the public domain using CC0.
  11. */
  12. /**
  13. * @mainpage smtp-client
  14. *
  15. * This section contains documentation generated directly from the source
  16. * code.
  17. *
  18. * To view the repository details, visit the main smtp-client page at
  19. * <a href='https://www.somnisoft.com/smtp-client'>
  20. * www.somnisoft.com/smtp-client
  21. * </a>.
  22. */
  23. #include "cfg.h"
  24. #ifdef USE_SMTP
  25. #include <sys/types.h>
  26. #include <stddef.h>
  27. #include <stdio.h>
  28. #define SMTP_OPENSSL
  29. #ifndef SIZE_MAX
  30. /**
  31. * Maximum value of size_t type.
  32. */
  33. # define SIZE_MAX ((size_t)(-1))
  34. #endif /* SIZE_MAX */
  35. /**
  36. * Status codes indicating success or failure from calling any of the
  37. * SMTP library functions.
  38. *
  39. * This code gets returned by all functions in this header.
  40. */
  41. enum smtp_status_code{
  42. /**
  43. * Successful operation completed.
  44. */
  45. SMTP_STATUS_OK = 0,
  46. /**
  47. * Memory allocation failed.
  48. */
  49. SMTP_STATUS_NOMEM = 1,
  50. /**
  51. * Failed to connect to the mail server.
  52. */
  53. SMTP_STATUS_CONNECT = 2,
  54. /**
  55. * Failed to handshake or negotiate a TLS connection with the server.
  56. */
  57. SMTP_STATUS_HANDSHAKE = 3,
  58. /**
  59. * Failed to authenticate with the given credentials.
  60. */
  61. SMTP_STATUS_AUTH = 4,
  62. /**
  63. * Failed to send bytes to the server.
  64. */
  65. SMTP_STATUS_SEND = 5,
  66. /**
  67. * Failed to receive bytes from the server.
  68. */
  69. SMTP_STATUS_RECV = 6,
  70. /**
  71. * Failed to properly close a connection.
  72. */
  73. SMTP_STATUS_CLOSE = 7,
  74. /**
  75. * SMTP server sent back an unexpected status code.
  76. */
  77. SMTP_STATUS_SERVER_RESPONSE = 8,
  78. /**
  79. * Invalid parameter.
  80. */
  81. SMTP_STATUS_PARAM = 9,
  82. /**
  83. * Failed to open or read a local file.
  84. */
  85. SMTP_STATUS_FILE = 10,
  86. /**
  87. * Failed to get the local date and time.
  88. */
  89. SMTP_STATUS_DATE = 11,
  90. /**
  91. * Indicates the last status code in the enumeration, useful for
  92. * bounds checking.
  93. *
  94. * Not a valid status code.
  95. */
  96. SMTP_STATUS__LAST
  97. };
  98. /**
  99. * Address source and destination types.
  100. */
  101. enum smtp_address_type{
  102. /**
  103. * From address.
  104. */
  105. SMTP_ADDRESS_FROM = 0,
  106. /**
  107. * To address.
  108. */
  109. SMTP_ADDRESS_TO = 1,
  110. /**
  111. * Copy address.
  112. */
  113. SMTP_ADDRESS_CC = 2,
  114. /**
  115. * Blind copy address.
  116. *
  117. * Recipients should not see any of the BCC addresses when they receive
  118. * their email. However, some SMTP server implementations may copy this
  119. * information into the mail header, so do not assume that this will
  120. * always get hidden. If the BCC addresses must not get shown to the
  121. * receivers, then send one separate email to each BCC party and add
  122. * the TO and CC addresses manually as a header property using
  123. * @ref smtp_header_add instead of as an address using
  124. * @ref smtp_address_add.
  125. */
  126. SMTP_ADDRESS_BCC = 3
  127. };
  128. /**
  129. * Connect to the SMTP server using either an unencrypted socket or
  130. * TLS encryption.
  131. */
  132. enum smtp_connection_security{
  133. #ifdef SMTP_OPENSSL
  134. /**
  135. * First connect without encryption, then negotiate an encrypted connection
  136. * by issuing a STARTTLS command.
  137. *
  138. * Typically used when connecting to a mail server on port 25 or 587.
  139. */
  140. SMTP_SECURITY_STARTTLS = 0,
  141. /**
  142. * Use TLS when initially connecting to server.
  143. *
  144. * Typically used when connecting to a mail server on port 465.
  145. */
  146. SMTP_SECURITY_TLS = 1,
  147. #endif /* SMTP_OPENSSL */
  148. /**
  149. * Do not use TLS encryption.
  150. *
  151. * Not recommended unless connecting to the SMTP server locally.
  152. */
  153. SMTP_SECURITY_NONE = 2
  154. };
  155. /**
  156. * List of supported methods for authenticating a mail user account on
  157. * the server.
  158. */
  159. enum smtp_authentication_method{
  160. #ifdef SMTP_OPENSSL
  161. /**
  162. * Use HMAC-MD5.
  163. */
  164. SMTP_AUTH_CRAM_MD5 = 0,
  165. #endif /* SMTP_OPENSSL */
  166. /**
  167. * No authentication required.
  168. *
  169. * Some servers support this option if connecting locally.
  170. */
  171. SMTP_AUTH_NONE = 1,
  172. /**
  173. * Authenticate using base64 user and password.
  174. */
  175. SMTP_AUTH_PLAIN = 2,
  176. /**
  177. * Another base64 authentication method, similar to SMTP_AUTH_PLAIN.
  178. */
  179. SMTP_AUTH_LOGIN = 3
  180. };
  181. /**
  182. * Special flags defining certain behaviors for the SMTP client context.
  183. */
  184. enum smtp_flag{
  185. /**
  186. * Print client and server communication on stderr.
  187. */
  188. SMTP_DEBUG = 1 << 0,
  189. /**
  190. * Do not verify TLS certificate.
  191. *
  192. * By default, the TLS handshake function will check if a certificate
  193. * has expired or if using a self-signed certificate. Either of those
  194. * conditions will cause the connection to fail. This option allows the
  195. * connection to proceed even if those checks fail.
  196. */
  197. SMTP_NO_CERT_VERIFY = 1 << 1
  198. };
  199. /**
  200. * SMTP codes returned by the server and parsed by the client.
  201. */
  202. enum smtp_result_code{
  203. /**
  204. * Client error code which does not get set by the server.
  205. */
  206. SMTP_INTERNAL_ERROR = -1,
  207. /**
  208. * Returned when ready to begin processing next step.
  209. */
  210. SMTP_READY = 220,
  211. /**
  212. * Returned in response to QUIT.
  213. */
  214. SMTP_CLOSE = 221,
  215. /**
  216. * Returned if client successfully authenticates.
  217. */
  218. SMTP_AUTH_SUCCESS = 235,
  219. /**
  220. * Returned when some commands successfully complete.
  221. */
  222. SMTP_DONE = 250,
  223. /**
  224. * Returned for some multi-line authentication mechanisms where this code
  225. * indicates the next stage in the authentication step.
  226. */
  227. SMTP_AUTH_CONTINUE = 334,
  228. /**
  229. * Returned in response to DATA command.
  230. */
  231. SMTP_BEGIN_MAIL = 354
  232. };
  233. /**
  234. * Used for parsing out the responses from the SMTP server.
  235. *
  236. * For example, if the server sends back '250-STARTTLS', then code would
  237. * get set to 250, more would get set to 1, and text would get set to STARTTLS.
  238. */
  239. struct smtp_command{
  240. /**
  241. * Result code converted to an integer.
  242. */
  243. enum smtp_result_code code;
  244. /**
  245. * Indicates if more server commands follow.
  246. *
  247. * This will get set to 1 if the fourth character in the response line
  248. * contains a '-', otherwise this will get set to 0.
  249. */
  250. int more;
  251. /**
  252. * The text shown after the status code.
  253. */
  254. const char *text;
  255. };
  256. /**
  257. * Return codes for the getdelim interface which allows the caller to check
  258. * if more delimited lines can get processed.
  259. */
  260. enum str_getdelim_retcode{
  261. /**
  262. * An error occurred during the getdelim processing.
  263. */
  264. STRING_GETDELIMFD_ERROR = -1,
  265. /**
  266. * Found a new line and can process more lines in the next call.
  267. */
  268. STRING_GETDELIMFD_NEXT = 0,
  269. /**
  270. * Found a new line and unable to read any more lines at this time.
  271. */
  272. STRING_GETDELIMFD_DONE = 1
  273. };
  274. /**
  275. * Data structure for read buffer and line parsing.
  276. *
  277. * This assists with getting and parsing the server response lines.
  278. */
  279. struct str_getdelimfd{
  280. /**
  281. * Read buffer which may include bytes past the delimiter.
  282. */
  283. char *_buf;
  284. /**
  285. * Number of allocated bytes in the read buffer.
  286. */
  287. size_t _bufsz;
  288. /**
  289. * Number of actual stored bytes in the read buffer.
  290. */
  291. size_t _buf_len;
  292. /**
  293. * Current line containing the text up to the delimiter.
  294. */
  295. char *line;
  296. /**
  297. * Number of stored bytes in the line buffer.
  298. */
  299. size_t line_len;
  300. /**
  301. * Function pointer to a custom read function for the
  302. * @ref smtp_str_getdelimfd interface.
  303. *
  304. * This function prototype has similar semantics to the read function.
  305. * The @p gdfd parameter allows the custom function to pull the user_data
  306. * info from the @ref str_getdelimfd struct which can contain file pointer,
  307. * socket connection, etc.
  308. */
  309. long (*getdelimfd_read)(struct str_getdelimfd *const gdfd,
  310. void *buf,
  311. size_t count);
  312. /**
  313. * User data which gets sent to the read handler function.
  314. */
  315. void *user_data;
  316. /**
  317. * Character delimiter used for determining line separation.
  318. */
  319. int delim;
  320. /**
  321. * Padding structure to align.
  322. */
  323. char pad[4];
  324. };
  325. struct smtp;
  326. enum smtp_status_code
  327. smtp_open(const char *const server,
  328. const char *const port,
  329. enum smtp_connection_security connection_security,
  330. enum smtp_flag flags,
  331. const char *const cafile,
  332. struct smtp **smtp);
  333. enum smtp_status_code
  334. smtp_auth(struct smtp *const smtp,
  335. enum smtp_authentication_method auth_method,
  336. const char *const user,
  337. const char *const pass);
  338. enum smtp_status_code
  339. smtp_mail(struct smtp *const smtp,
  340. const char *const body);
  341. enum smtp_status_code
  342. smtp_close(struct smtp *smtp);
  343. enum smtp_status_code
  344. smtp_status_code_get(const struct smtp *const smtp);
  345. enum smtp_status_code
  346. smtp_status_code_clear(struct smtp *const smtp);
  347. enum smtp_status_code
  348. smtp_status_code_set(struct smtp *const smtp,
  349. enum smtp_status_code new_status_code);
  350. const char *
  351. smtp_status_code_errstr(enum smtp_status_code status_code);
  352. enum smtp_status_code
  353. smtp_header_add(struct smtp *const smtp,
  354. const char *const key,
  355. const char *const value);
  356. void
  357. smtp_header_clear_all(struct smtp *const smtp);
  358. enum smtp_status_code
  359. smtp_address_add(struct smtp *const smtp,
  360. enum smtp_address_type type,
  361. const char *const email,
  362. const char *const name);
  363. void
  364. smtp_address_clear_all(struct smtp *const smtp);
  365. enum smtp_status_code
  366. smtp_attachment_add_path(struct smtp *const smtp,
  367. const char *const name,
  368. const char *const path);
  369. enum smtp_status_code
  370. smtp_attachment_add_fp(struct smtp *const smtp,
  371. const char *const name,
  372. FILE *fp);
  373. enum smtp_status_code
  374. smtp_attachment_add_mem(struct smtp *const smtp,
  375. const char *const name,
  376. const void *const data,
  377. size_t datasz);
  378. void smtp_attachment_clear_all(struct smtp *const smtp);
  379. //////////////////////////////////////////////////////////////////////
  380. #if defined(_WIN32) || defined(WIN32)
  381. # define SMTP_IS_WINDOWS
  382. #endif /* SMTP_IS_WINDOWS */
  383. #ifdef SMTP_IS_WINDOWS
  384. # include <winsock2.h>
  385. # include <ws2tcpip.h>
  386. #else /* POSIX */
  387. # include <netinet/in.h>
  388. # include <sys/select.h>
  389. # include <sys/socket.h>
  390. # include <netdb.h>
  391. # include <unistd.h>
  392. #endif /* SMTP_IS_WINDOWS */
  393. #include <errno.h>
  394. #include <limits.h>
  395. #include <signal.h>
  396. #include <stdarg.h>
  397. #include <string.h>
  398. #include <stdlib.h>
  399. #include <time.h>
  400. #ifdef SMTP_OPENSSL
  401. # include <openssl/bio.h>
  402. # include <openssl/err.h>
  403. # include <openssl/ssl.h>
  404. # include <openssl/x509.h>
  405. # include <openssl/x509v3.h>
  406. #endif /* SMTP_OPENSSL */
  407. /**
  408. * Get access to the @ref smtp_result_code and @ref smtp_command definitions.
  409. */
  410. #define SMTP_INTERNAL_DEFINE
  411. #include "smtp.h"
  412. /*
  413. * The SMTP_TEST converts some library routines into special test seams which
  414. * allows the test program to control whether they fail. For example, we can
  415. * control when malloc() fails under certain conditions with an out of
  416. * memory condition.
  417. */
  418. #ifdef SMTP_TEST
  419. /**
  420. * Declare extern linkage on some functions so we can redefine their behavior
  421. * in the external test suite.
  422. */
  423. # define SMTP_LINKAGE extern
  424. # include "../test/seams.h"
  425. #else /* !(SMTP_TEST) */
  426. /**
  427. * When not testing, all functions should have static linkage except for those
  428. * in the header.
  429. */
  430. # define SMTP_LINKAGE static
  431. #endif /* SMTP_TEST */
  432. /**
  433. * Increment the read buffer size by this amount if the delimiter
  434. * has not been found.
  435. */
  436. #define SMTP_GETDELIM_READ_SZ 1000
  437. /**
  438. * Stores source and destination email addresses.
  439. */
  440. struct smtp_address{
  441. /**
  442. * Email address without any special formatting.
  443. *
  444. * For example: mail@example.com
  445. */
  446. char *email;
  447. /**
  448. * Description of the email address.
  449. */
  450. char *name;
  451. /**
  452. * Specify from, to, cc, bcc.
  453. */
  454. enum smtp_address_type type;
  455. /**
  456. * Padding structure to align.
  457. */
  458. char pad[4];
  459. };
  460. /**
  461. * Attachment data which gets placed in the MIME email section.
  462. */
  463. struct smtp_attachment{
  464. /**
  465. * File name of the attachment.
  466. */
  467. char *name;
  468. /**
  469. * Base64-encoded file data.
  470. */
  471. char *b64_data;
  472. };
  473. /**
  474. * List of email headers to send before the mail body.
  475. */
  476. struct smtp_header{
  477. /**
  478. * Header name which will get sorted alphabetically in the header list.
  479. */
  480. char *key;
  481. /**
  482. * Content of the corresponding header key.
  483. */
  484. char *value;
  485. };
  486. /**
  487. * Main data structure that holds the SMTP client context.
  488. */
  489. struct smtp{
  490. /**
  491. * Bitwise list of flags controlling the behavior of this SMTP client.
  492. */
  493. enum smtp_flag flags;
  494. /**
  495. * Standard network socket connection.
  496. */
  497. int sock;
  498. /**
  499. * Read buffer and line parsing structure.
  500. */
  501. struct str_getdelimfd gdfd;
  502. /**
  503. * List of headers to print before the mail body.
  504. */
  505. struct smtp_header *header_list;
  506. /**
  507. * Number of headers in header_list.
  508. */
  509. size_t num_headers;
  510. /**
  511. * List of from, to, cc, and bcc email addresses.
  512. */
  513. struct smtp_address *address_list;
  514. /**
  515. * Number of addresses in address_list.
  516. */
  517. size_t num_address;
  518. /**
  519. * List of attachments to send.
  520. */
  521. struct smtp_attachment *attachment_list;
  522. /**
  523. * Number of attachments in attachment_list.
  524. */
  525. size_t num_attachment;
  526. /**
  527. * Timeout in seconds to wait before returning with an error.
  528. *
  529. * This applies to both writing to and reading from a network socket.
  530. */
  531. long timeout_sec;
  532. /**
  533. * Status code indicating success/failure.
  534. *
  535. * This code gets returned by most of the header functions.
  536. */
  537. enum smtp_status_code status_code;
  538. /**
  539. * Indicates if this context has an active TLS connection.
  540. * - Set to 0 if TLS connection inactive.
  541. * - Set to 1 if TLS connection currently active.
  542. */
  543. int tls_on;
  544. /**
  545. * Path to certificate file if using self-signed or untrusted certificate
  546. * not in the default key store.
  547. */
  548. const char *cafile;
  549. #ifdef SMTP_OPENSSL
  550. /**
  551. * OpenSSL TLS object.
  552. */
  553. SSL *tls;
  554. /**
  555. * OpenSSL TLS context.
  556. */
  557. SSL_CTX *tls_ctx;
  558. /**
  559. * OpenSSL TLS I/O abstraction.
  560. */
  561. BIO *tls_bio;
  562. #endif /* SMTP_OPENSSL */
  563. };
  564. /**
  565. * Check if adding a size_t value will cause a wrap.
  566. *
  567. * @param[in] a Add this value with @p b.
  568. * @param[in] b Add this value with @p a.
  569. * @param[out] result Save the addition to this buffer. Does not
  570. * perform the addition if set to NULL.
  571. * @retval 1 Value wrapped.
  572. * @retval 0 Value did not wrap.
  573. */
  574. SMTP_LINKAGE int
  575. smtp_si_add_size_t(const size_t a,
  576. const size_t b,
  577. size_t *const result){
  578. int wraps;
  579. #ifdef SMTP_TEST
  580. if(smtp_test_seam_dec_err_ctr(&g_smtp_test_err_si_add_size_t_ctr)){
  581. return 1;
  582. }
  583. #endif /* SMTP_TEST */
  584. if(SIZE_MAX - a < b){
  585. wraps = 1;
  586. }
  587. else{
  588. wraps = 0;
  589. }
  590. if(result){
  591. *result = a + b;
  592. }
  593. return wraps;
  594. }
  595. /**
  596. * Check if subtracting a size_t value will cause wrap.
  597. *
  598. * @param[in] a Subtract this value by @p b.
  599. * @param[in] b Subtract this value from @p a.
  600. * @param[out] result Save the subtraction to this buffer. Does not
  601. * perform the subtraction if set to NULL.
  602. * @retval 1 Value wrapped.
  603. * @retval 0 Value did not wrap.
  604. */
  605. SMTP_LINKAGE int
  606. smtp_si_sub_size_t(const size_t a,
  607. const size_t b,
  608. size_t *const result){
  609. int wraps;
  610. #ifdef SMTP_TEST
  611. if(smtp_test_seam_dec_err_ctr(&g_smtp_test_err_si_sub_size_t_ctr)){
  612. return 1;
  613. }
  614. #endif /* SMTP_TEST */
  615. if(a < b){
  616. wraps = 1;
  617. }
  618. else{
  619. wraps = 0;
  620. }
  621. if(result){
  622. *result = a - b;
  623. }
  624. return wraps;
  625. }
  626. /**
  627. * Check if multiplying a size_t value will cause a wrap.
  628. *
  629. * @param[in] a Multiply this value with @p b.
  630. * @param[in] b Multiply this value with @p a.
  631. * @param[out] result Save the multiplication to this buffer. Does not
  632. * perform the multiplication if set to NULL.
  633. * @retval 1 Value wrapped.
  634. * @retval 0 Value did not wrap.
  635. */
  636. SMTP_LINKAGE int
  637. smtp_si_mul_size_t(const size_t a,
  638. const size_t b,
  639. size_t *const result){
  640. int wraps;
  641. #ifdef SMTP_TEST
  642. if(smtp_test_seam_dec_err_ctr(&g_smtp_test_err_si_mul_size_t_ctr)){
  643. return 1;
  644. }
  645. #endif /* SMTP_TEST */
  646. if(b != 0 && a > SIZE_MAX / b){
  647. wraps = 1;
  648. }
  649. else{
  650. wraps = 0;
  651. }
  652. if(result){
  653. *result = a * b;
  654. }
  655. return wraps;
  656. }
  657. /**
  658. * Wait until more data has been made available on the socket read end.
  659. *
  660. * @param[in] smtp SMTP client context.
  661. * @retval SMTP_STATUS_OK If data available to read on the socket.
  662. * @retval SMTP_STATUS_RECV If the connection times out before any data
  663. * appears on the socket.
  664. */
  665. static enum smtp_status_code
  666. smtp_str_getdelimfd_read_timeout(struct smtp *const smtp){
  667. fd_set readfds;
  668. struct timeval timeout;
  669. int sel_rc;
  670. FD_ZERO(&readfds);
  671. FD_SET(smtp->sock, &readfds);
  672. timeout.tv_sec = smtp->timeout_sec;
  673. timeout.tv_usec = 0;
  674. sel_rc = select(smtp->sock + 1, &readfds, NULL, NULL, &timeout);
  675. if(sel_rc < 1){
  676. return smtp_status_code_set(smtp, SMTP_STATUS_RECV);
  677. }
  678. return SMTP_STATUS_OK;
  679. }
  680. /**
  681. * This function gets called by the @ref smtp_str_getdelimfd interface when it
  682. * needs to read in more data.
  683. *
  684. * It reads using either the plain socket connection if encryption not
  685. * enabled, or it reads using OpenSSL if it has an active TLS connection.
  686. *
  687. * @param[in] gdfd See @ref str_getdelimfd.
  688. * @param[out] buf Pointer to buffer for storing bytes read.
  689. * @param[in] count Maximum number of bytes to try reading.
  690. * @retval >=0 Number of bytes read.
  691. * @retval -1 Failed to read from the socket.
  692. */
  693. static long
  694. smtp_str_getdelimfd_read(struct str_getdelimfd *const gdfd,
  695. void *buf,
  696. size_t count){
  697. struct smtp *smtp;
  698. long bytes_read;
  699. smtp = gdfd->user_data;
  700. if(smtp_str_getdelimfd_read_timeout(smtp) != SMTP_STATUS_OK){
  701. return -1;
  702. }
  703. bytes_read = 0;
  704. if(smtp->tls_on){
  705. #ifdef SMTP_OPENSSL
  706. do{
  707. /*
  708. * Count will never have a value greater than SMTP_GETDELIM_READ_SZ,
  709. * so we can safely convert this to an int.
  710. */
  711. bytes_read = SSL_read(smtp->tls, buf, (int)count);
  712. } while(bytes_read <= 0 && BIO_should_retry(smtp->tls_bio));
  713. #endif /* SMTP_OPENSSL */
  714. }
  715. else{
  716. bytes_read = recv(smtp->sock, buf, count, 0);
  717. }
  718. return bytes_read;
  719. }
  720. /**
  721. * Find and return the location of the delimiter character in the
  722. * search buffer.
  723. *
  724. * This function gets used by the main socket parsing function which
  725. * continually reads from the socket and expands the buffer until it
  726. * encounters the expected delimiter. This function provides the logic
  727. * to check for the delimiter character in order to simplify the code
  728. * in the main parse function.
  729. *
  730. * @param[in] buf Search buffer used to find the delimiter.
  731. * @param[in] buf_len Number of bytes to search for in buf.
  732. * @param[in] delim The delimiter to search for in buf.
  733. * @param[out] delim_pos If delimiter found in buf, return the delimiter
  734. * position in this parameter.
  735. * @retval 1 If the delimiter character found.
  736. * @retval 0 If the delimiter character not found.
  737. */
  738. static int
  739. smtp_str_getdelimfd_search_delim(const char *const buf,
  740. size_t buf_len,
  741. int delim,
  742. size_t *const delim_pos){
  743. size_t i;
  744. *delim_pos = 0;
  745. for(i = 0; i < buf_len; i++){
  746. if(buf[i] == delim){
  747. *delim_pos = i;
  748. return 1;
  749. }
  750. }
  751. return 0;
  752. }
  753. /**
  754. * Set the internal line buffer to the number of bytes specified.
  755. *
  756. * @param[in] gdfd See @ref str_getdelimfd.
  757. * @param[in] copy_len Number of bytes to copy to the internal line buffer.
  758. * @retval 0 Successfully allocated and copied data over to the new
  759. * line buffer.
  760. * @retval -1 Failed to allocate memory for the new line buffer.
  761. */
  762. SMTP_LINKAGE int
  763. smtp_str_getdelimfd_set_line_and_buf(struct str_getdelimfd *const gdfd,
  764. size_t copy_len){
  765. size_t copy_len_inc;
  766. size_t nbytes_to_shift;
  767. size_t new_buf_len;
  768. if(gdfd->line){
  769. free(gdfd->line);
  770. gdfd->line = NULL;
  771. }
  772. if(smtp_si_add_size_t(copy_len, 1, &copy_len_inc) ||
  773. smtp_si_add_size_t((size_t)gdfd->_buf, copy_len_inc, NULL) ||
  774. smtp_si_sub_size_t(gdfd->_buf_len, copy_len, &nbytes_to_shift) ||
  775. (gdfd->line = calloc(1, copy_len_inc)) == NULL){
  776. return -1;
  777. }
  778. memcpy(gdfd->line, gdfd->_buf, copy_len);
  779. gdfd->line_len = copy_len;
  780. memmove(gdfd->_buf, gdfd->_buf + copy_len_inc, nbytes_to_shift);
  781. if(smtp_si_sub_size_t(nbytes_to_shift, 1, &new_buf_len) == 0){
  782. gdfd->_buf_len = new_buf_len;
  783. }
  784. return 0;
  785. }
  786. /**
  787. * Free memory in the @ref str_getdelimfd data structure.
  788. *
  789. * @param[in] gdfd Frees memory stored in this socket parsing structure.
  790. */
  791. SMTP_LINKAGE void
  792. smtp_str_getdelimfd_free(struct str_getdelimfd *const gdfd){
  793. free(gdfd->_buf);
  794. free(gdfd->line);
  795. gdfd->_buf = NULL;
  796. gdfd->_bufsz = 0;
  797. gdfd->_buf_len = 0;
  798. gdfd->line = NULL;
  799. gdfd->line_len = 0;
  800. }
  801. /**
  802. * Free the @ref str_getdelimfd and return the @ref STRING_GETDELIMFD_ERROR
  803. * error code.
  804. *
  805. * @param[in] gdfd See @ref str_getdelimfd.
  806. * @return See @ref str_getdelim_retcode.
  807. */
  808. static enum str_getdelim_retcode
  809. smtp_str_getdelimfd_throw_error(struct str_getdelimfd *const gdfd){
  810. smtp_str_getdelimfd_free(gdfd);
  811. return STRING_GETDELIMFD_ERROR;
  812. }
  813. /**
  814. * Read and parse a delimited string using a custom socket read function.
  815. *
  816. * This interface handles all of the logic for expanding the buffer,
  817. * parsing the delimiter in the buffer, and returning each "line"
  818. * to the caller for handling.
  819. *
  820. * @param[in] gdfd See @ref str_getdelimfd.
  821. * @return See @ref str_getdelim_retcode.
  822. */
  823. SMTP_LINKAGE enum str_getdelim_retcode
  824. smtp_str_getdelimfd(struct str_getdelimfd *const gdfd){
  825. size_t delim_pos;
  826. long bytes_read;
  827. void *read_buf_ptr;
  828. char *buf_new;
  829. size_t buf_sz_remaining;
  830. size_t buf_sz_new;
  831. if(gdfd->getdelimfd_read == NULL){
  832. return STRING_GETDELIMFD_ERROR;
  833. }
  834. bytes_read = -1;
  835. while(1){
  836. if(smtp_str_getdelimfd_search_delim(gdfd->_buf,
  837. gdfd->_buf_len,
  838. gdfd->delim,
  839. &delim_pos)){
  840. if(smtp_str_getdelimfd_set_line_and_buf(gdfd, delim_pos) < 0){
  841. return smtp_str_getdelimfd_throw_error(gdfd);
  842. }
  843. return STRING_GETDELIMFD_NEXT;
  844. }else if(bytes_read == 0){
  845. if(smtp_str_getdelimfd_set_line_and_buf(gdfd, gdfd->_buf_len) < 0){
  846. return smtp_str_getdelimfd_throw_error(gdfd);
  847. }
  848. return STRING_GETDELIMFD_DONE;
  849. }
  850. if(smtp_si_sub_size_t(gdfd->_bufsz, gdfd->_buf_len, &buf_sz_remaining)){
  851. return smtp_str_getdelimfd_throw_error(gdfd);
  852. }
  853. if(buf_sz_remaining < SMTP_GETDELIM_READ_SZ){
  854. if(smtp_si_add_size_t(buf_sz_remaining,
  855. SMTP_GETDELIM_READ_SZ,
  856. &buf_sz_new)){
  857. return smtp_str_getdelimfd_throw_error(gdfd);
  858. }
  859. buf_new = realloc(gdfd->_buf, buf_sz_new);
  860. if(buf_new == NULL){
  861. return smtp_str_getdelimfd_throw_error(gdfd);
  862. }
  863. gdfd->_buf = buf_new;
  864. gdfd->_bufsz = buf_sz_new;
  865. }
  866. if(smtp_si_add_size_t((size_t)gdfd->_buf, gdfd->_buf_len, NULL)){
  867. return smtp_str_getdelimfd_throw_error(gdfd);
  868. }
  869. read_buf_ptr = gdfd->_buf + gdfd->_buf_len;
  870. bytes_read = (*gdfd->getdelimfd_read)(gdfd,
  871. read_buf_ptr,
  872. SMTP_GETDELIM_READ_SZ);
  873. if(bytes_read < 0 ||
  874. smtp_si_add_size_t(gdfd->_buf_len,
  875. (size_t)bytes_read,
  876. &gdfd->_buf_len)){
  877. return smtp_str_getdelimfd_throw_error(gdfd);
  878. }
  879. }
  880. }
  881. /**
  882. * Copy a string and get the pointer to the end of the copied buffer.
  883. *
  884. * This function behaves similar to POSIX stpcpy(), useful for
  885. * concatenating multiple strings onto a buffer. It always adds a
  886. * null-terminated byte at the end of the string.
  887. *
  888. * @param[in] s1 Destination buffer.
  889. * @param[in] s2 Null-terminated source string to copy to @p s1.
  890. * @return Pointer to location in @p s1 after the last copied byte.
  891. */
  892. SMTP_LINKAGE char *
  893. smtp_stpcpy(char *s1,
  894. const char *s2){
  895. size_t i;
  896. i = 0;
  897. do{
  898. s1[i] = s2[i];
  899. } while(s2[i++] != '\0');
  900. return &s1[i-1];
  901. }
  902. /**
  903. * Reallocate memory with unsigned wrapping checks.
  904. *
  905. * @param[in] ptr Existing allocation buffer, or NULL when allocating a
  906. * new buffer.
  907. * @param[in] nmemb Number of elements to allocate.
  908. * @param[in] size Size of each element in @p nmemb.
  909. * @retval void* Pointer to a reallocated buffer containing
  910. * @p nmemb * @p size bytes.
  911. * @retval NULL Failed to reallocate memory.
  912. */
  913. SMTP_LINKAGE void *
  914. smtp_reallocarray(void *ptr,
  915. size_t nmemb,
  916. size_t size){
  917. void *alloc;
  918. size_t size_mul;
  919. if(smtp_si_mul_size_t(nmemb, size, &size_mul)){
  920. alloc = NULL;
  921. errno = ENOMEM;
  922. }
  923. else{
  924. alloc = realloc(ptr, size_mul);
  925. }
  926. return alloc;
  927. }
  928. /**
  929. * Copy a string into a new dynamically allocated buffer.
  930. *
  931. * Returns a dynamically allocated string, with the same contents as the
  932. * input string. The caller must free the returned string when finished.
  933. *
  934. * @param[in] s String to duplicate.
  935. * @retval char* Pointer to a new dynamically allocated string duplicated
  936. * from @p s.
  937. * @retval NULL Failed to allocate memory for the new duplicate string.
  938. */
  939. SMTP_LINKAGE char *
  940. smtp_strdup(const char *s){
  941. char *dup;
  942. size_t dup_len;
  943. size_t slen;
  944. slen = strlen(s);
  945. if(smtp_si_add_size_t(slen, 1, &dup_len)){
  946. dup = NULL;
  947. errno = ENOMEM;
  948. }
  949. else if((dup = malloc(dup_len)) != NULL){
  950. memcpy(dup, s, dup_len);
  951. }
  952. return dup;
  953. }
  954. /**
  955. * Search for all substrings in a string and replace each instance with a
  956. * replacement string.
  957. *
  958. * @param[in] search Substring to search for in @p s.
  959. * @param[in] replace Replace each instance of the search string with this.
  960. * @param[in] s Null-terminated string to search and replace.
  961. * @retval char* A dynamically allocated string with the replaced instances
  962. * as described above. The caller must free the allocated
  963. * memory when finished.
  964. * @retval NULL Memory allocation failure.
  965. */
  966. SMTP_LINKAGE char *
  967. smtp_str_replace(const char *const search,
  968. const char *const replace,
  969. const char *const s){
  970. size_t search_len;
  971. size_t replace_len;
  972. size_t replace_len_inc;
  973. size_t slen;
  974. size_t slen_inc;
  975. size_t s_idx;
  976. size_t snew_len;
  977. size_t snew_len_inc;
  978. size_t snew_sz;
  979. size_t snew_sz_dup;
  980. size_t snew_sz_plus_slen;
  981. size_t snew_replace_len_inc;
  982. char *snew;
  983. char *stmp;
  984. search_len = strlen(search);
  985. replace_len = strlen(replace);
  986. slen = strlen(s);
  987. s_idx = 0;
  988. snew = NULL;
  989. snew_len = 0;
  990. snew_sz = 0;
  991. if(smtp_si_add_size_t(replace_len, 1, &replace_len_inc) ||
  992. smtp_si_add_size_t(slen, 1, &slen_inc)){
  993. return NULL;
  994. }
  995. if(s[0] == '\0'){
  996. return smtp_strdup("");
  997. }
  998. else if(search_len < 1){
  999. return smtp_strdup(s);
  1000. }
  1001. while(s[s_idx]){
  1002. if(smtp_si_add_size_t(snew_len, 1, &snew_len_inc) ||
  1003. smtp_si_add_size_t(snew_sz, snew_sz, &snew_sz_dup) ||
  1004. smtp_si_add_size_t(snew_sz, slen, &snew_sz_plus_slen)){
  1005. free(snew);
  1006. return NULL;
  1007. }
  1008. if(strncmp(&s[s_idx], search, search_len) == 0){
  1009. if(smtp_si_add_size_t(snew_len, replace_len_inc, &snew_replace_len_inc)){
  1010. free(snew);
  1011. return NULL;
  1012. }
  1013. if(snew_replace_len_inc >= snew_sz){
  1014. /* snew_sz += snew_sz + slen + replace_len + 1 */
  1015. if(smtp_si_add_size_t(snew_sz_dup, slen_inc, &snew_sz) ||
  1016. smtp_si_add_size_t(snew_sz, replace_len, &snew_sz) ||
  1017. (stmp = realloc(snew, snew_sz)) == NULL){
  1018. free(snew);
  1019. return NULL;
  1020. }
  1021. snew = stmp;
  1022. }
  1023. memcpy(&snew[snew_len], replace, replace_len);
  1024. snew_len += replace_len;
  1025. s_idx += search_len;
  1026. }
  1027. else{
  1028. if(snew_len_inc >= snew_sz){
  1029. /* snew_sz += snew_sz + slen + snew_len + 1 */
  1030. if(smtp_si_add_size_t(snew_sz_dup, slen, &snew_sz) ||
  1031. smtp_si_add_size_t(snew_sz, snew_len_inc, &snew_sz) ||
  1032. (stmp = realloc(snew, snew_sz)) == NULL){
  1033. free(snew);
  1034. return NULL;
  1035. }
  1036. snew = stmp;
  1037. }
  1038. snew[snew_len] = s[s_idx];
  1039. s_idx += 1;
  1040. snew_len = snew_len_inc;
  1041. }
  1042. }
  1043. snew[snew_len] = '\0';
  1044. return snew;
  1045. }
  1046. /**
  1047. * Lookup table used to encode data into base64.
  1048. *
  1049. * Base64 encoding takes six bits of data and encodes those bits using this
  1050. * table. Since 2^6 = 64, this array has 64 entries which maps directly from
  1051. * the 6 bit value into the corresponding array value.
  1052. */
  1053. static char g_base64_encode_table[] = {
  1054. 'A','B','C','D','E','F','G','H','I','J',
  1055. 'K','L','M','N','O','P','Q','R','S','T',
  1056. 'U','V','W','X','Y','Z',
  1057. 'a','b','c','d','e','f','g','h','i','j',
  1058. 'k','l','m','n','o','p','q','r','s','t',
  1059. 'u','v','w','x','y','z',
  1060. '0','1','2','3','4','5','6','7','8','9',
  1061. '+','/'
  1062. };
  1063. /**
  1064. * Encode a single block of binary data into base64.
  1065. *
  1066. * @param[in] buf Buffer with data to encode.
  1067. * @param[in] buf_block_sz Number of bytes in buf to encode (min 1, max 3).
  1068. * @param[out] b64 Pointer to buffer with at least 4 bytes for
  1069. * storing the base64 encoded result.
  1070. */
  1071. static void
  1072. smtp_base64_encode_block(const char *const buf,
  1073. size_t buf_block_sz,
  1074. char *const b64){
  1075. unsigned char inb[3] = {0};
  1076. unsigned char in_idx[4] = {0};
  1077. char outb[5] = {'=', '=', '=', '=', '\0'};
  1078. size_t i;
  1079. memcpy(inb, buf, buf_block_sz);
  1080. in_idx[0] = ((inb[0] >> 2)) & 0x3F;
  1081. in_idx[1] = ((inb[0] << 4) | ((inb[1] >> 4) & 0xF)) & 0x3F;
  1082. in_idx[2] = ((inb[1] << 2) | ((inb[2] >> 6) & 0x3)) & 0x3F;
  1083. in_idx[3] = ((inb[2] )) & 0x3F;
  1084. for(i = 0; i < 4; i++){
  1085. if(i < buf_block_sz + 1){
  1086. outb[i] = g_base64_encode_table[in_idx[i]];
  1087. }
  1088. b64[i] = outb[i];
  1089. }
  1090. }
  1091. /**
  1092. * Encode binary data into a base64 string.
  1093. *
  1094. * @param[in] buf Binary data to encode in base64.
  1095. * @param[in] buflen Number of bytes in the @p buf parameter, or -1 if
  1096. * null-terminated.
  1097. * @retval char* Dynamically allocated base64 encoded string. The caller
  1098. * must free this string when finished.
  1099. * @retval NULL Memory allocation failure.
  1100. */
  1101. SMTP_LINKAGE char *
  1102. smtp_base64_encode(const char *const buf,
  1103. size_t buflen){
  1104. char *b64;
  1105. size_t b64_sz;
  1106. size_t buf_i;
  1107. size_t b64_i;
  1108. size_t remaining_block_sz;
  1109. size_t buf_block_sz;
  1110. if(buflen == SIZE_MAX){
  1111. buflen = strlen(buf);
  1112. }
  1113. /*
  1114. * base64 size expands by 33%
  1115. * +1 to round integer division up
  1116. * +2 for '=' padding
  1117. * +1 null terminator
  1118. */
  1119. if(smtp_si_mul_size_t(buflen, 4, NULL)){
  1120. return NULL;
  1121. }
  1122. b64_sz = (4 * buflen / 3) + 1 + 2 + 1;
  1123. if((b64 = calloc(1, b64_sz)) == NULL){
  1124. return NULL;
  1125. }
  1126. if(buflen == 0){
  1127. return b64;
  1128. }
  1129. buf_i = 0;
  1130. b64_i = 0;
  1131. remaining_block_sz = buflen;
  1132. while(remaining_block_sz > 0){
  1133. if(remaining_block_sz >= 3){
  1134. buf_block_sz = 3;
  1135. }
  1136. else{
  1137. buf_block_sz = remaining_block_sz;
  1138. }
  1139. smtp_base64_encode_block(&buf[buf_i], buf_block_sz, &b64[b64_i]);
  1140. /*
  1141. * Do not need to check for wrapping because these values restricted to
  1142. * range of b64_sz, which has already been checked for wrapping above.
  1143. */
  1144. buf_i += 3;
  1145. b64_i += 4;
  1146. remaining_block_sz -= buf_block_sz;
  1147. }
  1148. return b64;
  1149. }
  1150. #ifdef SMTP_OPENSSL
  1151. /**
  1152. * Lookup table used to decode base64 data.
  1153. *
  1154. * For base64 encoding, every six bits have been encoded using only the ASCII
  1155. * characters from @ref g_base64_encode_table. This table has entries which
  1156. * allow the reversal of that process. It has 128 entries which map over to
  1157. * the index value from the encoding table. If an indexing result ends up
  1158. * with -1 during the decoding process, then that indicates an invalid base64
  1159. * character in the encoded data.
  1160. */
  1161. static signed char
  1162. g_base64_decode_table[] = {
  1163. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  1164. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  1165. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  1166. -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
  1167. -1, -1, -1,
  1168. 62, /* + */
  1169. -1, -1, -1,
  1170. 63, /* / */
  1171. 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, /* 0 - 9 */
  1172. -1, -1, -1, -1, -1, -1, -1,
  1173. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, /* A - J */
  1174. 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, /* K - T */
  1175. 20, 21, 22, 23, 24, 25, /* U - Z */
  1176. -1, -1, -1, -1, -1, -1,
  1177. 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, /* a - j */
  1178. 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, /* k - t */
  1179. 46, 47, 48, 49, 50, 51, /* u - z */
  1180. -1, -1, -1, -1, -1
  1181. };
  1182. /**
  1183. * Decodes a base64 block of up to four bytes at a time.
  1184. *
  1185. * @param[in] buf Buffer containing bytes to decode.
  1186. * @param[out] decode Buffer for storing base64 decoded bytes.
  1187. * @retval >0 Length of the decoded block.
  1188. * @retval 0 If the block contains invalid base64 data.
  1189. */
  1190. static size_t
  1191. smtp_base64_decode_block(const unsigned char *const buf,
  1192. unsigned char *const decode){
  1193. size_t decode_block_len;
  1194. size_t i;
  1195. signed char decode_table[4];
  1196. unsigned char outb[3];
  1197. decode_block_len = 0;
  1198. for(i = 0; i < 4; i++){
  1199. if(buf[i] == '='){
  1200. decode_table[i] = 0;
  1201. continue;
  1202. }
  1203. decode_table[i] = g_base64_decode_table[buf[i]];
  1204. if(decode_table[i] < 0){
  1205. return 0;
  1206. }
  1207. }
  1208. outb[0] = ((decode_table[0] << 2) & 0xFC) | ((decode_table[1] >> 4) & 0x03);
  1209. outb[1] = ((decode_table[1] << 4) & 0xF0) | ((decode_table[2] >> 2) & 0x0F);
  1210. outb[2] = ((decode_table[2] << 6) & 0xC0) | ((decode_table[3] ) & 0x3F);
  1211. decode[0] = outb[0];
  1212. decode_block_len += 1;
  1213. if(buf[2] == '='){
  1214. decode[1] = '\0';
  1215. }
  1216. else{
  1217. decode[1] = outb[1];
  1218. decode_block_len += 1;
  1219. }
  1220. if(buf[3] == '='){
  1221. decode[2] = '\0';
  1222. }
  1223. else{
  1224. decode[2] = outb[2];
  1225. decode_block_len += 1;
  1226. }
  1227. return decode_block_len;
  1228. }
  1229. /**
  1230. * Decode a base64 string.
  1231. *
  1232. * The decode parameter will get dynamically allocated by this function
  1233. * if it successfully completes. Therefore, the caller must free the decode
  1234. * parameter after use.
  1235. *
  1236. * @param[in] buf Null-terminated base64 string.
  1237. * @param[out] decode Pointer to buffer which will get dynamically allocated
  1238. * and will contain the decoded binary data. This parameter
  1239. * will get set to NULL if the memory allocation fails.
  1240. * @retval >=0 Length of the data stored in the decode parameter.
  1241. * @retval -1 Memory allocation failure or invalid base64 byte sequences.
  1242. */
  1243. SMTP_LINKAGE size_t
  1244. smtp_base64_decode(const char *const buf,
  1245. unsigned char **decode){
  1246. size_t buf_len;
  1247. size_t buf_len_inc;
  1248. size_t buf_i;
  1249. unsigned char *b64_decode;
  1250. size_t decode_len;
  1251. size_t decode_block_len;
  1252. *decode = NULL;
  1253. buf_len = strlen(buf);
  1254. if(buf_len % 4 != 0){
  1255. return SIZE_MAX;
  1256. }
  1257. if(smtp_si_add_size_t(buf_len, 1, &buf_len_inc) ||
  1258. (b64_decode = calloc(1, buf_len_inc)) == NULL){
  1259. return SIZE_MAX;
  1260. }
  1261. decode_len = 0;
  1262. for(buf_i = 0; buf_i < buf_len; buf_i += 4){
  1263. decode_block_len = smtp_base64_decode_block(
  1264. (const unsigned char*)&buf[buf_i],
  1265. &b64_decode[decode_len]);
  1266. if(decode_block_len == 0){
  1267. free(b64_decode);
  1268. return SIZE_MAX;
  1269. }
  1270. decode_len += decode_block_len;
  1271. }
  1272. *decode = b64_decode;
  1273. return decode_len;
  1274. }
  1275. /**
  1276. * Convert binary data to lowercase hexadecimal representation.
  1277. *
  1278. * @param[in] s Buffer containing binary data to convert.
  1279. * @param[in] slen Number of bytes in @p s.
  1280. * @retval char* Dynamically allocated string consisting of a hexadecimal
  1281. * representation of binary data in @p s. The caller must free
  1282. * this memory when finished.
  1283. * @retval NULL Memory allocation or encoding error.
  1284. */
  1285. SMTP_LINKAGE char *
  1286. smtp_bin2hex(const unsigned char *const s,
  1287. size_t slen){
  1288. char *snew;
  1289. size_t alloc_sz;
  1290. size_t i;
  1291. size_t j;
  1292. unsigned hex;
  1293. int rc;
  1294. /* alloc_sz = slen * 2 + 1 */
  1295. if(smtp_si_mul_size_t(slen, 2, &alloc_sz) ||
  1296. smtp_si_add_size_t(alloc_sz, 1, &alloc_sz)){
  1297. return NULL;
  1298. }
  1299. if((snew = malloc(alloc_sz)) == NULL){
  1300. return NULL;
  1301. }
  1302. j = 0;
  1303. for(i = 0; i < slen; i++){
  1304. hex = s[i];
  1305. rc = sprintf(&snew[j], "%02x", hex);
  1306. if(rc < 0 || (size_t)rc >= 3){
  1307. free(snew);
  1308. return NULL;
  1309. }
  1310. j += 2;
  1311. }
  1312. snew[j] = '\0';
  1313. return snew;
  1314. }
  1315. #endif /* SMTP_OPENSSL */
  1316. /**
  1317. * Get the length in bytes of a UTF-8 character.
  1318. *
  1319. * This consists of a very simple check and assumes the user provides a valid
  1320. * UTF-8 byte sequence. It gets the length from the first byte in the sequence
  1321. * and does not validate any other bytes in the character sequence or any other
  1322. * bits in the first byte of the character sequence.
  1323. *
  1324. * @param[in] c The first byte in a valid UTF-8 character sequence.
  1325. * @retval >0 Number of bytes for the current UTF-8 character sequence.
  1326. * @retval -1 Invalid byte sequence.
  1327. */
  1328. SMTP_LINKAGE size_t
  1329. smtp_utf8_charlen(char c){
  1330. unsigned char uc;
  1331. uc = (unsigned char)c;
  1332. if((uc & 0x80) == 0){ /* 0XXXXXXX */
  1333. return 1;
  1334. }
  1335. else if((uc & 0xE0) == 0xC0){ /* 110XXXXX */
  1336. return 2;
  1337. }
  1338. else if((uc & 0xF0) == 0xE0){ /* 1110XXXX */
  1339. return 3;
  1340. }
  1341. else if((uc & 0xF8) == 0xF0){ /* 11110XXX */
  1342. return 4;
  1343. }
  1344. else{ /* invalid */
  1345. return 0;
  1346. }
  1347. }
  1348. /**
  1349. * Check if a string contains non-ASCII UTF-8 characters.
  1350. *
  1351. * Uses the simple algorithm from @ref smtp_utf8_charlen to check for
  1352. * non-ASCII UTF-8 characters.
  1353. *
  1354. * @param[in] s UTF-8 string.
  1355. * @retval 1 String contains non-ASCII UTF-8 characters.
  1356. * @retval 0 String contains only ASCII characters.
  1357. */
  1358. SMTP_LINKAGE int
  1359. smtp_str_has_nonascii_utf8(const char *const s){
  1360. size_t i;
  1361. size_t charlen;
  1362. for(i = 0; s[i]; i++){
  1363. charlen = smtp_utf8_charlen(s[i]);
  1364. if(charlen != 1){
  1365. return 1;
  1366. }
  1367. }
  1368. return 0;
  1369. }
  1370. /**
  1371. * Get the number of bytes in a UTF-8 string, or a shorter count if
  1372. * the string exceeds a maximum specified length.
  1373. *
  1374. * See @p maxlen for more information on multi-byte parsing.
  1375. *
  1376. * @param[in] s Null-terminated UTF-8 string.
  1377. * @param[in] maxlen Do not check more than @p maxlen bytes of string @p s
  1378. * except if in the middle of a multi-byte character.
  1379. * @retval strlen(s) If length of s has less bytes than maxlen or the same
  1380. * number of bytes as maxlen. See @p maxlen for more details.
  1381. * @retval maxlen If length of s has more bytes than maxlen.
  1382. * @retval -1 If @p s contains an invalid UTF-8 byte sequence.
  1383. */
  1384. SMTP_LINKAGE size_t
  1385. smtp_strnlen_utf8(const char *s,
  1386. size_t maxlen){
  1387. size_t i;
  1388. size_t utf8_i;
  1389. size_t utf8_len;
  1390. for(i = 0; *s && i < maxlen; i += utf8_len){
  1391. utf8_len = smtp_utf8_charlen(*s);
  1392. if(utf8_len == 0){
  1393. return SIZE_MAX;
  1394. }
  1395. for(utf8_i = 0; utf8_i < utf8_len; utf8_i++){
  1396. if(!*s){
  1397. return SIZE_MAX;
  1398. }
  1399. s += 1;
  1400. }
  1401. }
  1402. return i;
  1403. }
  1404. /**
  1405. * Get the offset of the next whitespace block to process folding.
  1406. *
  1407. * If a string does not have whitespace before @p maxlen, then the index
  1408. * will get returned past @p maxlen. Also returns the index of NULL character
  1409. * if that fits within the next block. The caller must check for the NULL
  1410. * index to indicate the last block. It will skip past any leading whitespace
  1411. * even if that means going over maxlen.
  1412. *
  1413. * Examples:
  1414. * @ref smtp_fold_whitespace_get_offset ("Subject: Test WS", 1/2/8/9/10/13) -> 8
  1415. * @ref smtp_fold_whitespace_get_offset ("Subject: Test WS", 14/15) -> 13
  1416. * @ref smtp_fold_whitespace_get_offset ("Subject: Test WS", 17/18) -> 16
  1417. *
  1418. * @param[in] s String to get offset from.
  1419. * @param[in] maxlen Number of bytes for each line in the string (soft limit).
  1420. * @return Index in @p s.
  1421. */
  1422. SMTP_LINKAGE size_t
  1423. smtp_fold_whitespace_get_offset(const char *const s,
  1424. unsigned int maxlen){
  1425. size_t i;
  1426. size_t offset_i;
  1427. i = 0;
  1428. offset_i = 0;
  1429. while(s[i] == ' ' || s[i] == '\t'){
  1430. i += 1;
  1431. }
  1432. while(s[i]){
  1433. if(s[i] == ' ' || s[i] == '\t'){
  1434. do{
  1435. i += 1;
  1436. } while(s[i] == ' ' || s[i] == '\t');
  1437. i -= 1;
  1438. if(i < maxlen || !offset_i){
  1439. offset_i = i;
  1440. }
  1441. else{
  1442. break;
  1443. }
  1444. }
  1445. i += 1;
  1446. }
  1447. if(!offset_i || i < maxlen){
  1448. offset_i = i;
  1449. }
  1450. return offset_i;
  1451. }
  1452. /**
  1453. * Email header lines should have no more than 78 characters and must
  1454. * not be more than 998 characters.
  1455. */
  1456. #define SMTP_LINE_MAX 78
  1457. /**
  1458. * Fold a line at whitespace characters.
  1459. *
  1460. * This function tries to keep the total number of characters per line under
  1461. * @p maxlen, but does not guarantee this. For really long text with no
  1462. * whitespace, the line will still extend beyond @p maxlen and possibly
  1463. * beyond the RFC limit as defined in @ref SMTP_LINE_MAX. This is by design
  1464. * and intended to keep the algorithm simpler to implement. Users sending
  1465. * long headers with no space characters should not assume that will work,
  1466. * but modern email systems may correctly process those headers anyways.
  1467. *
  1468. * Lines get folded by adding a [CR][LF] and then two space characters on the
  1469. * beginning of the next line. For example, this Subject line:
  1470. *
  1471. * Subject: Email[WS][WS]Header
  1472. *
  1473. * Would get folded like this (assuming a small @p maxlen):
  1474. *
  1475. * Subject: Email[WS][CR][LF]
  1476. * [WS][WS]Header
  1477. *
  1478. * @param[in] s String to fold.
  1479. * @param[in] maxlen Number of bytes for each line in the string (soft limit).
  1480. * The minimum value of this parameter is 3 and it will get
  1481. * forced to 3 if the provided value is less.
  1482. * @retval char* Pointer to an allocated string with the contents split into
  1483. * separate lines. The caller must free this memory when done.
  1484. * @retval NULL Memory allocation failed.
  1485. */
  1486. SMTP_LINKAGE char *
  1487. smtp_fold_whitespace(const char *const s,
  1488. unsigned int maxlen){
  1489. const char *const SMTP_LINE_FOLD_STR = "\r\n ";
  1490. size_t end_slen;
  1491. size_t s_i;
  1492. size_t buf_i;
  1493. size_t bufsz;
  1494. size_t ws_offset;
  1495. char *buf;
  1496. char *buf_new;
  1497. if(maxlen < 3){
  1498. maxlen = 3;
  1499. }
  1500. end_slen = strlen(SMTP_LINE_FOLD_STR);
  1501. s_i = 0;
  1502. buf_i = 0;
  1503. bufsz = 0;
  1504. buf = NULL;
  1505. while(1){
  1506. ws_offset = smtp_fold_whitespace_get_offset(&s[s_i], maxlen - 2);
  1507. /* bufsz += ws_offset + end_slen + 1 */
  1508. if(smtp_si_add_size_t(bufsz, ws_offset, &bufsz) ||
  1509. smtp_si_add_size_t(bufsz, end_slen, &bufsz) ||
  1510. smtp_si_add_size_t(bufsz, 1, &bufsz) ||
  1511. (buf_new = realloc(buf, bufsz)) == NULL){
  1512. free(buf);
  1513. return NULL;
  1514. }
  1515. buf = buf_new;
  1516. memcpy(&buf[buf_i], &s[s_i], ws_offset);
  1517. buf[buf_i + ws_offset] = '\0';
  1518. if(s[s_i + ws_offset] == '\0'){
  1519. break;
  1520. }
  1521. buf_i += ws_offset;
  1522. strcat(&buf[buf_i], SMTP_LINE_FOLD_STR);
  1523. buf_i += end_slen;
  1524. /* WS */
  1525. s_i += ws_offset + 1;
  1526. }
  1527. return buf;
  1528. }
  1529. /**
  1530. * Splits a string into smaller chunks separated by a terminating string.
  1531. *
  1532. * @param[in] s The string to chunk.
  1533. * @param[in] chunklen Number of bytes for each chunk in the string.
  1534. * @param[in] end Terminating string placed at the end of each chunk.
  1535. * @retval char* Pointer to an allocated string with the contents split into
  1536. * separate chunks. The caller must free this memory when done.
  1537. * @retval NULL Memory allocation failure.
  1538. */
  1539. SMTP_LINKAGE char *
  1540. smtp_chunk_split(const char *const s,
  1541. size_t chunklen,
  1542. const char *const end){
  1543. char *snew;
  1544. size_t bodylen;
  1545. size_t bodylen_inc;
  1546. size_t endlen;
  1547. size_t endlen_inc;
  1548. size_t snewlen;
  1549. size_t chunk_i;
  1550. size_t snew_i;
  1551. size_t body_i;
  1552. size_t body_copy_len;
  1553. if(chunklen < 1){
  1554. errno = EINVAL;
  1555. return NULL;
  1556. }
  1557. bodylen = strlen(s);
  1558. endlen = strlen(end);
  1559. if(bodylen < 1){
  1560. return smtp_strdup(end);
  1561. }
  1562. /*
  1563. * \0
  1564. * snewlen = bodylen + (endlen + 1) * (bodylen / chunklen + 1) + 1
  1565. */
  1566. if(smtp_si_add_size_t(endlen, 1, &endlen_inc) ||
  1567. smtp_si_add_size_t(bodylen, 1, &bodylen_inc) ||
  1568. smtp_si_mul_size_t(endlen_inc, bodylen / chunklen + 1, &snewlen) ||
  1569. smtp_si_add_size_t(snewlen, bodylen_inc, &snewlen) ||
  1570. (snew = calloc(1, snewlen)) == NULL){
  1571. return NULL;
  1572. }
  1573. body_i = 0;
  1574. snew_i = 0;
  1575. for(chunk_i = 0; chunk_i < bodylen / chunklen + 1; chunk_i++){
  1576. body_copy_len = smtp_strnlen_utf8(&s[body_i], chunklen);
  1577. if(body_copy_len == SIZE_MAX){
  1578. free(snew);
  1579. return NULL;
  1580. }
  1581. memcpy(&snew[snew_i], &s[body_i], body_copy_len);
  1582. snew_i += body_copy_len;
  1583. if(s[body_i] == '\0'){
  1584. snew_i += 1;
  1585. }
  1586. body_i += body_copy_len;
  1587. if(endlen > 0){
  1588. memcpy(&snew[snew_i], end, endlen);
  1589. }
  1590. snew_i += endlen;
  1591. }
  1592. return snew;
  1593. }
  1594. /**
  1595. * Read the entire contents of a file stream and store the data into a
  1596. * dynamically allocated buffer.
  1597. *
  1598. * @param[in] stream File stream already opened by the caller.
  1599. * @param[out] bytes_read Number of bytes stored in the return buffer.
  1600. * @retval char* A dynamically allocated buffer which contains the entire
  1601. * contents of @p stream. The caller must free this memory
  1602. * when done.
  1603. * @retval NULL Memory allocation or file read error.
  1604. */
  1605. SMTP_LINKAGE char *
  1606. smtp_ffile_get_contents(FILE *stream,
  1607. size_t *bytes_read){
  1608. char *read_buf;
  1609. size_t bufsz;
  1610. size_t bufsz_inc;
  1611. char *new_buf;
  1612. size_t bytes_read_loop;
  1613. const size_t BUFSZ_INCREMENT = 512;
  1614. read_buf = NULL;
  1615. bufsz = 0;
  1616. if(bytes_read){
  1617. *bytes_read = 0;
  1618. }
  1619. do{
  1620. if(smtp_si_add_size_t(bufsz, BUFSZ_INCREMENT, &bufsz_inc) ||
  1621. (new_buf = realloc(read_buf, bufsz_inc)) == NULL){
  1622. free(read_buf);
  1623. return NULL;
  1624. }
  1625. read_buf = new_buf;
  1626. bufsz = bufsz_inc;
  1627. bytes_read_loop = fread(&read_buf[bufsz - BUFSZ_INCREMENT],
  1628. sizeof(char),
  1629. BUFSZ_INCREMENT,
  1630. stream);
  1631. if(bytes_read){
  1632. *bytes_read += bytes_read_loop;
  1633. }
  1634. if(ferror(stream)){
  1635. free(read_buf);
  1636. return NULL;
  1637. }
  1638. } while(!feof(stream));
  1639. return read_buf;
  1640. }
  1641. /**
  1642. * Read the entire contents of a file from a given path, and store the data
  1643. * into a dynamically allocated buffer.
  1644. *
  1645. * @param[in] filename Path of file to open and read from.
  1646. * @param[out] bytes_read Number of bytes stored in the return buffer.
  1647. * @retval char* A dynamically allocated buffer which has the contents of
  1648. * the file at @p filename. The caller must free this memory when
  1649. * done.
  1650. * @retval NULL Memory allocation or file read error.
  1651. */
  1652. SMTP_LINKAGE char *
  1653. smtp_file_get_contents(const char *const filename,
  1654. size_t *bytes_read){
  1655. FILE *fp;
  1656. char *read_buf;
  1657. if((fp = fopen(filename, "rb")) == NULL){
  1658. return NULL;
  1659. }
  1660. read_buf = smtp_ffile_get_contents(fp, bytes_read);
  1661. if(fclose(fp) == EOF){
  1662. free(read_buf);
  1663. read_buf = NULL;
  1664. }
  1665. return read_buf;
  1666. }
  1667. /**
  1668. * Parse a server response line into the @ref smtp_command data structure.
  1669. *
  1670. * @param[in] line Server response string.
  1671. * @param[out] cmd Structure containing the server response data broken up
  1672. * into its separate components.
  1673. * @return See @ref smtp_result_code.
  1674. */
  1675. SMTP_LINKAGE int
  1676. smtp_parse_cmd_line(char *const line,
  1677. struct smtp_command *const cmd){
  1678. char *ep;
  1679. char code_str[4];
  1680. size_t line_len;
  1681. unsigned long int ulcode;
  1682. line_len = strlen(line);
  1683. if(line_len < 5){
  1684. cmd->code = SMTP_INTERNAL_ERROR;
  1685. cmd->more = 0;
  1686. cmd->text = line;
  1687. return cmd->code;
  1688. }
  1689. cmd->text = &line[4];
  1690. memcpy(code_str, line, 3);
  1691. code_str[3] = '\0';
  1692. ulcode = strtoul(code_str, &ep, 10);
  1693. if(*ep != '\0' || ulcode > SMTP_BEGIN_MAIL){
  1694. cmd->code = SMTP_INTERNAL_ERROR;
  1695. }
  1696. else{
  1697. cmd->code = (enum smtp_result_code)ulcode;
  1698. }
  1699. if(line[3] == '-'){
  1700. cmd->more = 1;
  1701. }
  1702. else{
  1703. cmd->more = 0;
  1704. }
  1705. return cmd->code;
  1706. }
  1707. /**
  1708. * Prints communication between the client and server to stderr only if
  1709. * the debug flag has been set.
  1710. *
  1711. * @param[in] smtp SMTP client context.
  1712. * @param[in] prefix Print this prefix before the main debug line text.
  1713. * @param[in] str Debug text to print out.
  1714. */
  1715. static void
  1716. smtp_puts_dbg(struct smtp *const smtp,
  1717. const char *const prefix,
  1718. const char *const str){
  1719. char *sdup;
  1720. size_t i;
  1721. if(smtp->flags & SMTP_DEBUG){
  1722. if((sdup = smtp_strdup(str)) == NULL){
  1723. return;
  1724. }
  1725. /* Remove carriage return and newline when printing to stderr. */
  1726. for(i = 0; sdup[i]; i++){
  1727. if(sdup[i] == '\r' || sdup[i] == '\n'){
  1728. sdup[i] = ' ';
  1729. }
  1730. }
  1731. if(fprintf(stderr, "[smtp %s]: %s\n", prefix, sdup) < 0){
  1732. /* Do not care if this fails. */
  1733. }
  1734. free(sdup);
  1735. }
  1736. }
  1737. /**
  1738. * Read a server response line.
  1739. *
  1740. * @param[in] smtp SMTP client context.
  1741. * @return See @ref str_getdelim_retcode.
  1742. */
  1743. static enum str_getdelim_retcode
  1744. smtp_getline(struct smtp *const smtp){
  1745. enum str_getdelim_retcode rc;
  1746. errno = 0;
  1747. rc = smtp_str_getdelimfd(&smtp->gdfd);
  1748. if(errno == ENOMEM){
  1749. smtp_status_code_set(smtp, SMTP_STATUS_NOMEM);
  1750. return rc;
  1751. }
  1752. else if(rc == STRING_GETDELIMFD_ERROR){
  1753. smtp_status_code_set(smtp, SMTP_STATUS_RECV);
  1754. return STRING_GETDELIMFD_ERROR;
  1755. }
  1756. if(smtp->gdfd.line_len > 0){
  1757. /* Remove the carriage-return character ('\r'). */
  1758. smtp->gdfd.line[smtp->gdfd.line_len - 1] = '\0';
  1759. smtp_puts_dbg(smtp, "Server", smtp->gdfd.line);
  1760. }
  1761. return rc;
  1762. }
  1763. /**
  1764. * Loop through all of the server response lines until the last line, and
  1765. * then return the status code from the last response line.
  1766. *
  1767. * @param[in] smtp SMTP client context.
  1768. * @return See @ref smtp_result_code.
  1769. */
  1770. static int
  1771. smtp_read_and_parse_code(struct smtp *const smtp){
  1772. struct smtp_command cmd;
  1773. enum str_getdelim_retcode rc;
  1774. do{
  1775. rc = smtp_getline(smtp);
  1776. if(rc == STRING_GETDELIMFD_ERROR){
  1777. return SMTP_INTERNAL_ERROR;
  1778. }
  1779. smtp_parse_cmd_line(smtp->gdfd.line, &cmd);
  1780. }while (rc != STRING_GETDELIMFD_DONE && cmd.more);
  1781. return cmd.code;
  1782. }
  1783. /**
  1784. * Send data to the SMTP server.
  1785. *
  1786. * Writes a buffer of length len into either the unencrypted TCP socket or
  1787. * the TLS encrypted socket, depending on the current underlying mode of
  1788. * the socket.
  1789. *
  1790. * @param[in] smtp SMTP client context.
  1791. * @param[in] buf Data to send to the SMTP server.
  1792. * @param[in] len Number of bytes in buf.
  1793. * @return See @ref smtp_status_code.
  1794. */
  1795. SMTP_LINKAGE enum smtp_status_code
  1796. smtp_write(struct smtp *const smtp,
  1797. const char *const buf,
  1798. size_t len){
  1799. size_t bytes_to_send;
  1800. long bytes_sent;
  1801. const char *buf_offset;
  1802. int ssl_bytes_to_send;
  1803. smtp_puts_dbg(smtp, "Client", buf);
  1804. bytes_to_send = len;
  1805. buf_offset = buf;
  1806. while(bytes_to_send){
  1807. if(bytes_to_send > INT_MAX){
  1808. return smtp_status_code_set(smtp, SMTP_STATUS_SEND);
  1809. }
  1810. if(smtp->tls_on){
  1811. #ifdef SMTP_OPENSSL
  1812. /* bytes_to_send <= INT_MAX */
  1813. ssl_bytes_to_send = (int)bytes_to_send;
  1814. bytes_sent = SSL_write(smtp->tls, buf_offset, ssl_bytes_to_send);
  1815. if(bytes_sent <= 0){
  1816. return smtp_status_code_set(smtp, SMTP_STATUS_SEND);
  1817. }
  1818. #else /* !(SMTP_OPENSSL) */
  1819. /* unreachable */
  1820. bytes_sent = 0;
  1821. (void)ssl_bytes_to_send;
  1822. #endif /* SMTP_OPENSSL */
  1823. }
  1824. else{
  1825. bytes_sent = send(smtp->sock, buf_offset, bytes_to_send, 0);
  1826. if(bytes_sent < 0){
  1827. return smtp_status_code_set(smtp, SMTP_STATUS_SEND);
  1828. }
  1829. }
  1830. bytes_to_send -= (size_t)bytes_sent;
  1831. buf_offset += bytes_sent;
  1832. }
  1833. return smtp->status_code;
  1834. }
  1835. /**
  1836. * Send a null-terminated string to the SMTP server.
  1837. *
  1838. * @param[in] smtp SMTP client context.
  1839. * @param[in] s Null-terminated string to send to the SMTP server.
  1840. * @return See @ref smtp_status_code and @ref smtp_write.
  1841. */
  1842. static enum smtp_status_code
  1843. smtp_puts(struct smtp *const smtp,
  1844. const char *const s){
  1845. return smtp_write(smtp, s, strlen(s));
  1846. }
  1847. /**
  1848. * Same as @ref smtp_puts except this function also appends the line
  1849. * terminating carriage return and newline bytes at the end of the string.
  1850. *
  1851. * @param[in] smtp SMTP client context.
  1852. * @param[in] s Null-terminated string to send to the SMTP server.
  1853. * @return See @ref smtp_status_code and @ref smtp_puts.
  1854. */
  1855. static enum smtp_status_code
  1856. smtp_puts_terminate(struct smtp *const smtp,
  1857. const char *const s){
  1858. enum smtp_status_code rc;
  1859. char *line;
  1860. char *concat;
  1861. size_t slen;
  1862. size_t allocsz;
  1863. slen = strlen(s);
  1864. if(smtp_si_add_size_t(slen, 3, &allocsz) ||
  1865. (line = malloc(allocsz)) == NULL){
  1866. return smtp_status_code_set(smtp, SMTP_STATUS_NOMEM);
  1867. }
  1868. concat = smtp_stpcpy(line, s);
  1869. smtp_stpcpy(concat, "\r\n");
  1870. rc = smtp_puts(smtp, line);
  1871. free(line);
  1872. return rc;
  1873. }
  1874. /**
  1875. * Connect to the server using a standard TCP socket.
  1876. *
  1877. * This function handles the server name lookup to get an IP address
  1878. * for the server, and then to connect to that IP using a normal TCP
  1879. * connection.
  1880. *
  1881. * @param[in] smtp SMTP client context.
  1882. * @param[in] server Mail server name or IP address.
  1883. * @param[in] port Mail server port number.
  1884. * @retval 0 Successfully connected to server.
  1885. * @retval -1 Failed to connect to server.
  1886. */
  1887. static int
  1888. smtp_connect(struct smtp *const smtp,
  1889. const char *const server,
  1890. const char *const port){
  1891. struct addrinfo hints;
  1892. struct addrinfo *res0;
  1893. struct addrinfo *res;
  1894. /*
  1895. * Windows requires initializing the socket library before we call any
  1896. * socket functions.
  1897. */
  1898. #ifdef SMTP_IS_WINDOWS
  1899. /* Windows global network socket data structure. */
  1900. WSADATA wsa_data;
  1901. if(WSAStartup(MAKEWORD(2, 2), &wsa_data) != 0){
  1902. return -1;
  1903. }
  1904. #endif /* SMTP_IS_WINDOWS */
  1905. memset(&hints, 0, sizeof(hints));
  1906. hints.ai_family = AF_UNSPEC;
  1907. hints.ai_socktype = SOCK_STREAM;
  1908. hints.ai_flags = 0;
  1909. hints.ai_protocol = IPPROTO_TCP;
  1910. if(getaddrinfo(server, port, &hints, &res0) != 0){
  1911. return -1;
  1912. }
  1913. for(res = res0; res; res = res->ai_next){
  1914. smtp->sock = socket(res->ai_family, res->ai_socktype, res->ai_protocol);
  1915. if(smtp->sock < 0){
  1916. continue;
  1917. }
  1918. if(connect(smtp->sock, res->ai_addr, res->ai_addrlen) < 0){
  1919. #ifdef SMTP_IS_WINDOWS
  1920. closesocket(smtp->sock);
  1921. #else /* POSIX */
  1922. close(smtp->sock);
  1923. #endif /* SMTP_IS_WINDOWS */
  1924. smtp->sock = -1;
  1925. }
  1926. else{
  1927. break;
  1928. }
  1929. }
  1930. freeaddrinfo(res0);
  1931. if(smtp->sock < 0){
  1932. return -1;
  1933. }
  1934. return 0;
  1935. }
  1936. #ifdef SMTP_OPENSSL
  1937. /**
  1938. * Initialize the TLS library and establish a TLS handshake with the server
  1939. * over the existing socket connection.
  1940. *
  1941. * @param[in] smtp SMTP client context.
  1942. * @param[in] server Server name or IP address.
  1943. * @retval 0 Successfully established a TLS connection with the server.
  1944. * @retval -1 Failed to establish a TLS connection with the server.
  1945. */
  1946. static int
  1947. smtp_tls_init(struct smtp *const smtp,
  1948. const char *const server){
  1949. X509 *X509_cert_peer;
  1950. /* Do not need to check the return value since this always returns 1. */
  1951. SSL_library_init();
  1952. SSL_load_error_strings();
  1953. ERR_load_BIO_strings();
  1954. OpenSSL_add_all_algorithms();
  1955. if((smtp->tls_ctx = SSL_CTX_new(SSLv23_client_method())) == NULL){
  1956. return -1;
  1957. }
  1958. /* Disable SSLv2, SSLv3, and TLSv1.0. */
  1959. SSL_CTX_set_options(smtp->tls_ctx,
  1960. SSL_OP_NO_SSLv2 |
  1961. SSL_OP_NO_SSLv3 |
  1962. SSL_OP_NO_TLSv1);
  1963. SSL_CTX_set_mode(smtp->tls_ctx, SSL_MODE_AUTO_RETRY);
  1964. if((smtp->flags & SMTP_NO_CERT_VERIFY) == 0){
  1965. SSL_CTX_set_verify(smtp->tls_ctx, SSL_VERIFY_PEER, NULL);
  1966. }
  1967. /*
  1968. * Set the path to the user-provided CA file or use the default cert paths
  1969. * if not provided.
  1970. */
  1971. if(smtp->cafile){
  1972. if(SSL_CTX_load_verify_locations(smtp->tls_ctx, smtp->cafile, NULL) != 1){
  1973. SSL_CTX_free(smtp->tls_ctx);
  1974. return -1;
  1975. }
  1976. }
  1977. else{
  1978. X509_STORE_set_default_paths(SSL_CTX_get_cert_store(smtp->tls_ctx));
  1979. if(ERR_peek_error() != 0){
  1980. SSL_CTX_free(smtp->tls_ctx);
  1981. return -1;
  1982. }
  1983. }
  1984. if((smtp->tls = SSL_new(smtp->tls_ctx)) == NULL){
  1985. SSL_CTX_free(smtp->tls_ctx);
  1986. return -1;
  1987. }
  1988. if((smtp->tls_bio = BIO_new_socket(smtp->sock, 0)) == NULL){
  1989. SSL_CTX_free(smtp->tls_ctx);
  1990. SSL_free(smtp->tls);
  1991. return -1;
  1992. }
  1993. SSL_set_bio(smtp->tls, smtp->tls_bio, smtp->tls_bio);
  1994. SSL_set_connect_state(smtp->tls);
  1995. if(SSL_connect(smtp->tls) != 1){
  1996. SSL_CTX_free(smtp->tls_ctx);
  1997. SSL_free(smtp->tls);
  1998. return -1;
  1999. }
  2000. if(SSL_do_handshake(smtp->tls) != 1){
  2001. SSL_CTX_free(smtp->tls_ctx);
  2002. SSL_free(smtp->tls);
  2003. return -1;
  2004. }
  2005. /* Verify matching subject in certificate. */
  2006. if((smtp->flags & SMTP_NO_CERT_VERIFY) == 0){
  2007. if((X509_cert_peer = SSL_get_peer_certificate(smtp->tls)) == NULL){
  2008. SSL_CTX_free(smtp->tls_ctx);
  2009. SSL_free(smtp->tls);
  2010. return -1;
  2011. }
  2012. if(X509_check_host(X509_cert_peer, server, 0, 0, NULL) != 1){
  2013. SSL_CTX_free(smtp->tls_ctx);
  2014. SSL_free(smtp->tls);
  2015. return -1;
  2016. }
  2017. X509_free(X509_cert_peer);
  2018. }
  2019. smtp->tls_on = 1;
  2020. return 0;
  2021. }
  2022. #endif /* SMTP_OPENSSL */
  2023. /**
  2024. * Send the EHLO command and parse through the responses.
  2025. *
  2026. * Ignores all of the server extensions that get returned. If a server
  2027. * doesn't support an extension we need, then we should receive an error
  2028. * later on when we try to use that extension.
  2029. *
  2030. * @param[in] smtp SMTP client context.
  2031. * @return See @ref smtp_status_code.
  2032. */
  2033. static enum smtp_status_code
  2034. smtp_ehlo(struct smtp *const smtp){
  2035. if(smtp_puts(smtp, "EHLO smtp\r\n") == SMTP_STATUS_OK){
  2036. smtp_read_and_parse_code(smtp);
  2037. }
  2038. return smtp->status_code;
  2039. }
  2040. /**
  2041. * Authenticate using the PLAIN method.
  2042. *
  2043. * 1. Set the text to the following format: "\0<user>\0<password>",
  2044. * or as shown in the format string: "\0%s\0%s", email, password.
  2045. * 2. Base64 encode the text from (1).
  2046. * 3. Send the constructed auth text from (2) to the server:
  2047. * "AUTH PLAIN <b64><CR><NL>".
  2048. *
  2049. * @param[in] smtp SMTP client context.
  2050. * @param[in] user SMTP account user name.
  2051. * @param[in] pass SMTP account password.
  2052. * @retval 0 Successfully authenticated.
  2053. * @retval -1 Failed to authenticate.
  2054. */
  2055. static int
  2056. smtp_auth_plain(struct smtp *const smtp,
  2057. const char *const user,
  2058. const char *const pass){
  2059. size_t user_len;
  2060. size_t pass_len;
  2061. char *login_str;
  2062. size_t login_len;
  2063. char *login_b64;
  2064. size_t login_b64_len;
  2065. char *login_send;
  2066. char *concat;
  2067. /* (1) */
  2068. user_len = strlen(user);
  2069. pass_len = strlen(pass);
  2070. /* login_len = 1 + user_len + 1 + pass_len */
  2071. if(smtp_si_add_size_t(user_len, pass_len, &login_len) ||
  2072. smtp_si_add_size_t(login_len, 2, &login_len) ||
  2073. (login_str = malloc(login_len)) == NULL){
  2074. return -1;
  2075. }
  2076. login_str[0] = '\0';
  2077. memcpy(&login_str[1], user, user_len);
  2078. login_str[1 + user_len] = '\0';
  2079. memcpy(&login_str[1 + user_len + 1], pass, pass_len);
  2080. /* (2) */
  2081. login_b64 = smtp_base64_encode(login_str, login_len);
  2082. free(login_str);
  2083. if(login_b64 == NULL){
  2084. return -1;
  2085. }
  2086. /* (3) */
  2087. login_b64_len = strlen(login_b64);
  2088. if(smtp_si_add_size_t(login_b64_len, 14, &login_b64_len) ||
  2089. (login_send = malloc(login_b64_len)) == NULL){
  2090. free(login_b64);
  2091. return -1;
  2092. }
  2093. concat = smtp_stpcpy(login_send, "AUTH PLAIN ");
  2094. concat = smtp_stpcpy(concat, login_b64);
  2095. smtp_stpcpy(concat, "\r\n");
  2096. free(login_b64);
  2097. smtp_puts(smtp, login_send);
  2098. free(login_send);
  2099. if(smtp->status_code != SMTP_STATUS_OK){
  2100. return -1;
  2101. }
  2102. if(smtp_read_and_parse_code(smtp) != SMTP_AUTH_SUCCESS){
  2103. return -1;
  2104. }
  2105. return 0;
  2106. }
  2107. /**
  2108. * Authenticate using the LOGIN method.
  2109. *
  2110. * 1. Base64 encode the user name.
  2111. * 2. Send string from (1) as part of the login:
  2112. * "AUTH LOGIN <b64_username><CR><NL>".
  2113. * 3. Base64 encode the password and send that by itself on a separate
  2114. * line: "<b64_password><CR><NL>".
  2115. *
  2116. * @param[in] smtp SMTP client context.
  2117. * @param[in] user SMTP account user name.
  2118. * @param[in] pass SMTP account password.
  2119. * @retval 0 Successfully authenticated.
  2120. * @retval -1 Failed to authenticate.
  2121. */
  2122. static int
  2123. smtp_auth_login(struct smtp *const smtp,
  2124. const char *const user,
  2125. const char *const pass){
  2126. char *b64_user;
  2127. char *b64_pass;
  2128. size_t b64_user_len;
  2129. char *login_str;
  2130. char *concat;
  2131. /* (1) */
  2132. if((b64_user = smtp_base64_encode(user, SIZE_MAX)) == NULL){
  2133. return -1;
  2134. }
  2135. /* (2) */
  2136. b64_user_len = strlen(b64_user);
  2137. if(smtp_si_add_size_t(b64_user_len, 14, &b64_user_len) ||
  2138. (login_str = malloc(b64_user_len)) == NULL){
  2139. free(b64_user);
  2140. return -1;
  2141. }
  2142. concat = smtp_stpcpy(login_str, "AUTH LOGIN ");
  2143. concat = smtp_stpcpy(concat, b64_user);
  2144. smtp_stpcpy(concat, "\r\n");
  2145. free(b64_user);
  2146. smtp_puts(smtp, login_str);
  2147. free(login_str);
  2148. if(smtp->status_code != SMTP_STATUS_OK){
  2149. return -1;
  2150. }
  2151. if(smtp_read_and_parse_code(smtp) != SMTP_AUTH_CONTINUE){
  2152. return -1;
  2153. }
  2154. /* (3) */
  2155. if((b64_pass = smtp_base64_encode(pass, SIZE_MAX)) == NULL){
  2156. return -1;
  2157. }
  2158. smtp_puts_terminate(smtp, b64_pass);
  2159. free(b64_pass);
  2160. if(smtp->status_code != SMTP_STATUS_OK){
  2161. return -1;
  2162. }
  2163. if(smtp_read_and_parse_code(smtp) != SMTP_AUTH_SUCCESS){
  2164. return -1;
  2165. }
  2166. return 0;
  2167. }
  2168. #ifdef SMTP_OPENSSL
  2169. /**
  2170. * Authenticate using the CRAM-MD5 method.
  2171. *
  2172. * 1. Send "AUTH CRAM-MD5<CR><NL>" to the server.
  2173. * 2. Decode the base64 challenge response from the server.
  2174. * 3. Do an MD5 HMAC on (2) using the account password as the key.
  2175. * 4. Convert the binary data in (3) to lowercase hex characters.
  2176. * 5. Construct the string: "<user> <(4)>".
  2177. * 6. Encode (5) into base64 format.
  2178. * 7. Send the final string from (6) to the server and check the response.
  2179. *
  2180. * @param[in] smtp SMTP client context.
  2181. * @param[in] user SMTP account user name.
  2182. * @param[in] pass SMTP account password.
  2183. * @retval 0 Successfully authenticated.
  2184. * @retval -1 Failed to authenticate.
  2185. */
  2186. static int
  2187. smtp_auth_cram_md5(struct smtp *const smtp,
  2188. const char *const user,
  2189. const char *const pass){
  2190. struct smtp_command cmd;
  2191. unsigned char *challenge_decoded;
  2192. size_t challenge_decoded_len;
  2193. const char *key;
  2194. int key_len;
  2195. unsigned char hmac[EVP_MAX_MD_SIZE];
  2196. unsigned int hmac_len;
  2197. unsigned char *hmac_ret;
  2198. char *challenge_hex;
  2199. size_t user_len;
  2200. size_t challenge_hex_len;
  2201. char *auth_concat;
  2202. char *concat;
  2203. size_t auth_concat_len;
  2204. char *b64_auth;
  2205. /* (1) */
  2206. if(smtp_puts(smtp, "AUTH CRAM-MD5\r\n") != SMTP_STATUS_OK){
  2207. return -1;
  2208. }
  2209. if(smtp_getline(smtp) == STRING_GETDELIMFD_ERROR){
  2210. return -1;
  2211. }
  2212. if(smtp_parse_cmd_line(smtp->gdfd.line, &cmd) != SMTP_AUTH_CONTINUE){
  2213. return -1;
  2214. }
  2215. /* (2) */
  2216. challenge_decoded_len = smtp_base64_decode(cmd.text,
  2217. &challenge_decoded);
  2218. if(challenge_decoded_len == SIZE_MAX){
  2219. return -1;
  2220. }
  2221. /* (3) */
  2222. key = pass;
  2223. key_len = (int)strlen(pass);/*********************cast*/
  2224. hmac_ret = HMAC(EVP_md5(),
  2225. key,
  2226. key_len,
  2227. challenge_decoded,
  2228. challenge_decoded_len,
  2229. hmac,
  2230. &hmac_len);
  2231. free(challenge_decoded);
  2232. if(hmac_ret == NULL){
  2233. return -1;
  2234. }
  2235. /* (4) */
  2236. challenge_hex = smtp_bin2hex(hmac, hmac_len);
  2237. if(challenge_hex == NULL){
  2238. return -1;
  2239. }
  2240. /* (5) */
  2241. user_len = strlen(user);
  2242. challenge_hex_len = strlen(challenge_hex);
  2243. /* auth_concat_len = user_len + 1 + challenge_hex_len + 1 */
  2244. if(smtp_si_add_size_t(user_len, challenge_hex_len, &auth_concat_len) ||
  2245. smtp_si_add_size_t(auth_concat_len, 2, &auth_concat_len) ||
  2246. (auth_concat = malloc(auth_concat_len)) == NULL){
  2247. free(challenge_hex);
  2248. return -1;
  2249. }
  2250. concat = smtp_stpcpy(auth_concat, user);
  2251. concat = smtp_stpcpy(concat, " ");
  2252. smtp_stpcpy(concat, challenge_hex);
  2253. free(challenge_hex);
  2254. /* (6) */
  2255. b64_auth = smtp_base64_encode(auth_concat, auth_concat_len - 1);
  2256. free(auth_concat);
  2257. if(b64_auth == NULL){
  2258. return -1;
  2259. }
  2260. /* (7) */
  2261. smtp_puts_terminate(smtp, b64_auth);
  2262. free(b64_auth);
  2263. if(smtp->status_code != SMTP_STATUS_OK){
  2264. return -1;
  2265. }
  2266. if(smtp_read_and_parse_code(smtp) != SMTP_AUTH_SUCCESS){
  2267. return -1;
  2268. }
  2269. return 0;
  2270. }
  2271. #endif /* SMTP_OPENSSL */
  2272. /**
  2273. * Set the timeout for the next socket read operation.
  2274. *
  2275. * @param[in] smtp SMTP client context.
  2276. * @param[in] seconds Timeout in seconds.
  2277. */
  2278. static void
  2279. smtp_set_read_timeout(struct smtp *const smtp,
  2280. long seconds){
  2281. smtp->timeout_sec = seconds;
  2282. }
  2283. /**
  2284. * Perform a handshake with the SMTP server which includes optionally
  2285. * setting up TLS and sending the EHLO greeting.
  2286. *
  2287. * At this point, the client has already connected to the SMTP server
  2288. * through its socket connection. In this function, the client will:
  2289. * 1. Optionally convert the connection to TLS (SMTP_SECURITY_TLS).
  2290. * 2. Read the initial server greeting.
  2291. * 3. Send an EHLO to the server.
  2292. * 4. Optionally initiate STARTTLS and resend the EHLO
  2293. * (SMTP_SECURITY_STARTTLS).
  2294. *
  2295. * @param[in] smtp SMTP client context.
  2296. * @param[in] server Server name or IP address.
  2297. * @param[in] connection_security See @ref smtp_connection_security.
  2298. * @return See @ref smtp_status_code.
  2299. */
  2300. static enum smtp_status_code
  2301. smtp_initiate_handshake(struct smtp *const smtp,
  2302. const char *const server,
  2303. enum smtp_connection_security connection_security){
  2304. /* Eliminate unused warnings if not using SMTP_OPENSSL. */
  2305. (void)server;
  2306. (void)connection_security;
  2307. /* (1) */
  2308. #ifdef SMTP_OPENSSL
  2309. if(connection_security == SMTP_SECURITY_TLS){
  2310. if(smtp_tls_init(smtp, server) < 0){
  2311. return smtp_status_code_set(smtp, SMTP_STATUS_HANDSHAKE);
  2312. }
  2313. }
  2314. #endif /* SMTP_OPENSSL */
  2315. /* (2) */
  2316. /* Get initial 220 message - 5 minute timeout. */
  2317. smtp_set_read_timeout(smtp, 60 * 5);
  2318. if(smtp_getline(smtp) == STRING_GETDELIMFD_ERROR){
  2319. return smtp->status_code;
  2320. }
  2321. /* (3) */
  2322. if(smtp_ehlo(smtp) != SMTP_STATUS_OK){
  2323. return smtp->status_code;
  2324. }
  2325. /* (4) */
  2326. #ifdef SMTP_OPENSSL
  2327. if(connection_security == SMTP_SECURITY_STARTTLS){
  2328. if(smtp_puts(smtp, "STARTTLS\r\n") != SMTP_STATUS_OK){
  2329. return smtp->status_code;
  2330. }
  2331. if(smtp_read_and_parse_code(smtp) != SMTP_READY){
  2332. return smtp_status_code_set(smtp, SMTP_STATUS_HANDSHAKE);
  2333. }
  2334. if(smtp_tls_init(smtp, server) < 0){
  2335. return smtp_status_code_set(smtp, SMTP_STATUS_HANDSHAKE);
  2336. }
  2337. if(smtp_ehlo(smtp) != SMTP_STATUS_OK){
  2338. return smtp->status_code;
  2339. }
  2340. }
  2341. #endif /* SMTP_OPENSSL */
  2342. return smtp->status_code;
  2343. }
  2344. /**
  2345. Maximum size of an RFC 2822 date string.
  2346. @verbatim
  2347. Thu, 21 May 1998 05:33:29 -0700
  2348. 12345678901234567890123456789012
  2349. 10 20 30 32 (bytes)
  2350. @endverbatim
  2351. Add more bytes to the 32 maximum size to silence compiler warning on the
  2352. computed UTF offset.
  2353. */
  2354. #define SMTP_DATE_MAX_SZ (32 + 15)
  2355. /**
  2356. * Convert the time into an RFC 2822 formatted string.
  2357. *
  2358. * Example date format:
  2359. * Thu, 21 May 1998 05:33:29 -0700
  2360. *
  2361. * @param[out] date Buffer that has at least SMTP_DATE_MAX_SZ bytes.
  2362. * @retval 0 Successfully copied the current date to the buffer.
  2363. * @retval -1 Failed to establish the current date or an output
  2364. * format error occurred.
  2365. */
  2366. SMTP_LINKAGE int
  2367. smtp_date_rfc_2822(char *const date){
  2368. time_t t;
  2369. time_t t_local;
  2370. time_t t_utc;
  2371. struct tm tm_local;
  2372. struct tm tm_utc;
  2373. long offset_utc;
  2374. double diff_local_utc;
  2375. int rc;
  2376. const char weekday_abbreviation[7][4] = {
  2377. "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
  2378. };
  2379. const char month_abbreviation[12][4] = {
  2380. "Jan", "Feb", "Mar", "Apr", "May", "Jun",
  2381. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
  2382. };
  2383. if((t = time(NULL)) == (time_t)(-1)){
  2384. return -1;
  2385. }
  2386. #ifdef SMTP_IS_WINDOWS
  2387. if(localtime_s(&tm_local, &t) ||
  2388. gmtime_s(&tm_utc, &t)){
  2389. return -1;
  2390. }
  2391. #else /* POSIX */
  2392. /* Not defined if system does not have localtime_r or gmtime_r. */
  2393. # ifdef SMTP_TIME_NO_REENTRANT
  2394. struct tm *tm;
  2395. /* localtime() not thread-safe. */
  2396. if((tm = localtime(&t)) == NULL){
  2397. return -1;
  2398. }
  2399. memcpy(&tm_local, tm, sizeof(tm_local));
  2400. /* gmtime() not thread-safe. */
  2401. if((tm = gmtime(&t)) == NULL){
  2402. return -1;
  2403. }
  2404. memcpy(&tm_utc, tm, sizeof(tm_utc));
  2405. # else /* Reentrant versions: localtime_r() and gmtime_r(). */
  2406. if(localtime_r(&t, &tm_local) == NULL ||
  2407. gmtime_r(&t, &tm_utc) == NULL){
  2408. return -1;
  2409. }
  2410. # endif /* SMTP_TIME_NO_REENTRANT */
  2411. #endif /* SMTP_IS_WINDOWS */
  2412. if((t_local = mktime(&tm_local)) == (time_t)(-1)){
  2413. return -1;
  2414. }
  2415. if((t_utc = mktime(&tm_utc)) == (time_t)(-1)){
  2416. return -1;
  2417. }
  2418. /*
  2419. * After computing the offset, it will contain a maximum of 4 digits.
  2420. * For example, PST time zone will have an offset of -800 which will get
  2421. * formatted as -0800 in the sprintf call below.
  2422. */
  2423. diff_local_utc = difftime(t_local, t_utc);
  2424. offset_utc = (long)diff_local_utc;
  2425. offset_utc = offset_utc / 60 / 60 * 100;
  2426. rc = sprintf(date,
  2427. "%s, %02d %s %d %02d:%02d:%02d %0+5ld",
  2428. weekday_abbreviation[tm_local.tm_wday],
  2429. tm_local.tm_mday,
  2430. month_abbreviation[tm_local.tm_mon],
  2431. tm_local.tm_year + 1900,
  2432. tm_local.tm_hour,
  2433. tm_local.tm_min,
  2434. tm_local.tm_sec, /* 0 - 60 (leap second) */
  2435. offset_utc);
  2436. if(rc + 1 != SMTP_DATE_MAX_SZ - 15){ /* See @ref SMTP_DATE_MAX_SZ for -5. */
  2437. return -1;
  2438. }
  2439. return 0;
  2440. }
  2441. /**
  2442. * Search function used by bsearch, allowing the caller to check for
  2443. * headers with existing keys.
  2444. *
  2445. * @param v1 String to search for in the list.
  2446. * @param v2 The @ref smtp_header to compare.
  2447. * @retval 0 If the keys match.
  2448. * @retval !0 If the keys do not match.
  2449. */
  2450. static int
  2451. smtp_header_cmp_key(const void *const v1,
  2452. const void *const v2){
  2453. const char *key;
  2454. const struct smtp_header *header2;
  2455. key = v1;
  2456. header2 = v2;
  2457. return strcmp(key, header2->key);
  2458. }
  2459. /**
  2460. * Determine if the header key has already been defined in this context.
  2461. *
  2462. * @param[in] smtp SMTP client context.
  2463. * @param[in] key Header key value to search for.
  2464. * @retval 1 If the header already exists in this context.
  2465. * @retval 0 If the header does not exist in this context.
  2466. */
  2467. static int
  2468. smtp_header_exists(const struct smtp *const smtp,
  2469. const char *const key){
  2470. if(bsearch(key,
  2471. smtp->header_list,
  2472. smtp->num_headers,
  2473. sizeof(*smtp->header_list),
  2474. smtp_header_cmp_key) == NULL){
  2475. return 0;
  2476. }
  2477. return 1;
  2478. }
  2479. /**
  2480. * Minimum length of buffer required to hold the MIME boundary test:
  2481. * mimeXXXXXXXXXX
  2482. * 123456789012345
  2483. * 1 10 15 bytes
  2484. */
  2485. #define SMTP_MIME_BOUNDARY_LEN 15
  2486. /**
  2487. * Generate the MIME boundary text field and store it in a user-supplied
  2488. * buffer.
  2489. *
  2490. * For example:
  2491. * mimeXXXXXXXXXX
  2492. * where each X gets set to a pseudo-random uppercase ASCII character.
  2493. *
  2494. * This uses a simple pseudo-random number generator since we only care
  2495. * about preventing accidental boundary collisions.
  2496. *
  2497. * @param[out] boundary Buffer that has at least SMTP_MIME_BOUNDARY_LEN bytes.
  2498. */
  2499. static void
  2500. smtp_gen_mime_boundary(char *const boundary){
  2501. size_t i;
  2502. unsigned int seed;
  2503. seed = (unsigned int)time(NULL);
  2504. srand(seed);
  2505. strcpy(boundary, "mime");
  2506. for(i = 4; i < SMTP_MIME_BOUNDARY_LEN - 1; i++){
  2507. /* Modulo bias okay since we only need to prevent accidental collision. */
  2508. boundary[i] = rand() % 26 + 'A';
  2509. }
  2510. boundary[SMTP_MIME_BOUNDARY_LEN - 1] = '\0';
  2511. }
  2512. /**
  2513. * Print the MIME header and the MIME section containing the email body.
  2514. *
  2515. * @param[in] smtp SMTP client context.
  2516. * @param[in] boundary MIME boundary text.
  2517. * @param[in] body_dd Email body with double dots added at the
  2518. * beginning of each line.
  2519. * @return See @ref smtp_status_code.
  2520. */
  2521. static enum smtp_status_code
  2522. smtp_print_mime_header_and_body(struct smtp *const smtp,
  2523. const char *const boundary,
  2524. const char *const body_dd){
  2525. /* Buffer size for the static MIME text used below. */
  2526. const size_t MIME_TEXT_BUFSZ = 1000;
  2527. size_t data_double_dot_len;
  2528. char *data_header_and_body;
  2529. char *concat;
  2530. data_double_dot_len = strlen(body_dd);
  2531. if(smtp_si_add_size_t(data_double_dot_len,
  2532. MIME_TEXT_BUFSZ,
  2533. &data_double_dot_len) ||
  2534. (data_header_and_body = malloc(data_double_dot_len)) == NULL){
  2535. return smtp_status_code_set(smtp, SMTP_STATUS_NOMEM);
  2536. }
  2537. concat = smtp_stpcpy(data_header_and_body,
  2538. "MIME-Version: 1.0\r\n"
  2539. "Content-Type: multipart/mixed; boundary=");
  2540. concat = smtp_stpcpy(concat,
  2541. boundary);
  2542. concat = smtp_stpcpy(concat,
  2543. "\r\n"
  2544. "\r\n"
  2545. "Multipart MIME message.\r\n"
  2546. "--");
  2547. concat = smtp_stpcpy(concat,
  2548. boundary);
  2549. concat = smtp_stpcpy(concat,
  2550. "\r\n"
  2551. "Content-Type: text/plain; charset=\"UTF-8\"\r\n"
  2552. "\r\n");
  2553. concat = smtp_stpcpy(concat,
  2554. body_dd);
  2555. smtp_stpcpy(concat,
  2556. "\r\n"
  2557. "\r\n");
  2558. smtp_puts(smtp, data_header_and_body);
  2559. free(data_header_and_body);
  2560. return smtp->status_code;
  2561. }
  2562. /**
  2563. * Print a MIME section containing an attachment.
  2564. *
  2565. * @param[in] smtp SMTP client context.
  2566. * @param[in] boundary MIME boundary text.
  2567. * @param[in] attachment See @ref smtp_attachment.
  2568. * @return See @ref smtp_status_code.
  2569. */
  2570. static enum smtp_status_code
  2571. smtp_print_mime_attachment(struct smtp *const smtp,
  2572. const char *const boundary,
  2573. const struct smtp_attachment *const attachment){
  2574. /* Buffer size for the static MIME text used below. */
  2575. const size_t MIME_TEXT_BUFSZ = 1000;
  2576. size_t name_len;
  2577. size_t b64_data_len;
  2578. size_t bufsz;
  2579. char *mime_attach_text;
  2580. char *concat;
  2581. name_len = strlen(attachment->name);
  2582. b64_data_len = strlen(attachment->b64_data);
  2583. /*
  2584. * bufsz = SMTP_MIME_BOUNDARY_LEN + name_len + b64_data_len + MIME_TEXT_BUFSZ
  2585. */
  2586. if(smtp_si_add_size_t(name_len, b64_data_len, &bufsz) ||
  2587. smtp_si_add_size_t(bufsz,
  2588. SMTP_MIME_BOUNDARY_LEN + MIME_TEXT_BUFSZ,
  2589. &bufsz) ||
  2590. (mime_attach_text = malloc(bufsz)) == NULL){
  2591. return smtp_status_code_set(smtp, SMTP_STATUS_NOMEM);
  2592. }
  2593. concat = smtp_stpcpy(mime_attach_text,
  2594. "--");
  2595. concat = smtp_stpcpy(concat,
  2596. boundary);
  2597. concat = smtp_stpcpy(concat,
  2598. "\r\n"
  2599. "Content-Type: application/octet-stream\r\n"
  2600. "Content-Disposition: attachment; filename=\"");
  2601. concat = smtp_stpcpy(concat,
  2602. attachment->name);
  2603. concat = smtp_stpcpy(concat,
  2604. "\"\r\n"
  2605. "Content-Transfer-Encoding: base64\r\n"
  2606. "\r\n");
  2607. concat = smtp_stpcpy(concat,
  2608. attachment->b64_data);
  2609. smtp_stpcpy(concat,
  2610. "\r\n"
  2611. "\r\n");
  2612. smtp_puts(smtp, mime_attach_text);
  2613. free(mime_attach_text);
  2614. return smtp->status_code;
  2615. }
  2616. /**
  2617. * Prints double hyphen on both sides of the MIME boundary which indicates
  2618. * the end of the MIME sections.
  2619. *
  2620. * @param[in] smtp SMTP client context.
  2621. * @param[in] boundary MIME boundary text.
  2622. * @return See @ref smtp_status_code and @ref smtp_puts.
  2623. */
  2624. static enum smtp_status_code
  2625. smtp_print_mime_end(struct smtp *const smtp,
  2626. const char *const boundary){
  2627. char *concat;
  2628. char mime_end[2 + SMTP_MIME_BOUNDARY_LEN + 4 + 1];
  2629. concat = smtp_stpcpy(mime_end, "--");
  2630. concat = smtp_stpcpy(concat, boundary);
  2631. smtp_stpcpy(concat, "--\r\n");
  2632. return smtp_puts(smtp, mime_end);
  2633. }
  2634. /**
  2635. * Send the main email body to the SMTP server.
  2636. *
  2637. * This includes the MIME sections for the email body and attachments.
  2638. *
  2639. * @param[in] smtp SMTP client context.
  2640. * @param[in] body_dd Email body with double dots added at the
  2641. * beginning of each line.
  2642. * @return See @ref smtp_status_code.
  2643. */
  2644. static enum smtp_status_code
  2645. smtp_print_mime_email(struct smtp *const smtp,
  2646. const char *const body_dd){
  2647. char boundary[SMTP_MIME_BOUNDARY_LEN];
  2648. size_t i;
  2649. struct smtp_attachment *attachment;
  2650. smtp_gen_mime_boundary(boundary);
  2651. if(smtp_print_mime_header_and_body(smtp, boundary, body_dd) != SMTP_STATUS_OK){
  2652. return smtp->status_code;
  2653. }
  2654. for(i = 0; i < smtp->num_attachment; i++){
  2655. attachment = &smtp->attachment_list[i];
  2656. if(smtp_print_mime_attachment(smtp,
  2657. boundary,
  2658. attachment) != SMTP_STATUS_OK){
  2659. return smtp->status_code;
  2660. }
  2661. }
  2662. return smtp_print_mime_end(smtp, boundary);
  2663. }
  2664. /**
  2665. * Print the email data provided by the user without MIME formatting.
  2666. *
  2667. * @param[in,out] smtp SMTP client context.
  2668. * @param[in] body_dd Email body with double dots added at the
  2669. * beginning of each line.
  2670. * @return See @ref smtp_status_code.
  2671. */
  2672. static enum smtp_status_code
  2673. smtp_print_nomime_email(struct smtp *const smtp,
  2674. const char *const body_dd){
  2675. return smtp_puts_terminate(smtp, body_dd);
  2676. }
  2677. /**
  2678. * Send the email body to the mail server.
  2679. *
  2680. * @param[in,out] smtp SMTP client context.
  2681. * @param[in] body Email body text.
  2682. * @return See @ref smtp_status_code.
  2683. */
  2684. static enum smtp_status_code
  2685. smtp_print_email(struct smtp *const smtp,
  2686. const char *const body){
  2687. char *body_double_dot;
  2688. /*
  2689. * Insert an extra dot for each line that begins with a dot. This will
  2690. * prevent data in the body parameter from prematurely ending the DATA
  2691. * segment.
  2692. */
  2693. if((body_double_dot = smtp_str_replace("\n.", "\n..", body)) == NULL){
  2694. return smtp_status_code_set(smtp, SMTP_STATUS_NOMEM);
  2695. }
  2696. if(smtp_header_exists(smtp, "Content-Type")){
  2697. smtp_print_nomime_email(smtp, body_double_dot);
  2698. }
  2699. else{
  2700. smtp_print_mime_email(smtp, body_double_dot);
  2701. }
  2702. free(body_double_dot);
  2703. return smtp->status_code;
  2704. }
  2705. /**
  2706. * Convert a header into an RFC 5322 formatted string and send it to the
  2707. * SMTP server.
  2708. *
  2709. * This will adding proper line wrapping and indentation for long
  2710. * header lines.
  2711. *
  2712. * @param[in] smtp SMTP client context.
  2713. * @param[in] header See @ref smtp_header.
  2714. * @return See @ref smtp_status_code.
  2715. */
  2716. static enum smtp_status_code
  2717. smtp_print_header(struct smtp *const smtp,
  2718. const struct smtp_header *const header){
  2719. size_t key_len;
  2720. size_t value_len;
  2721. size_t concat_len;
  2722. char *header_concat;
  2723. char *concat;
  2724. char *header_fmt;
  2725. if(header->value == NULL){
  2726. return smtp->status_code;
  2727. }
  2728. key_len = strlen(header->key);
  2729. value_len = strlen(header->value);
  2730. /* concat_len = key_len + 2 + value_len + 1 */
  2731. if(smtp_si_add_size_t(key_len, value_len, &concat_len) ||
  2732. smtp_si_add_size_t(concat_len, 3, &concat_len) ||
  2733. (header_concat = malloc(concat_len)) == NULL){
  2734. return smtp_status_code_set(smtp, SMTP_STATUS_NOMEM);
  2735. }
  2736. concat = smtp_stpcpy(header_concat, header->key);
  2737. concat = smtp_stpcpy(concat, ": ");
  2738. smtp_stpcpy(concat, header->value);
  2739. header_fmt = smtp_fold_whitespace(header_concat, SMTP_LINE_MAX);
  2740. free(header_concat);
  2741. if(header_fmt == NULL){
  2742. return smtp_status_code_set(smtp, SMTP_STATUS_NOMEM);
  2743. }
  2744. smtp_puts_terminate(smtp, header_fmt);
  2745. free(header_fmt);
  2746. return smtp->status_code;
  2747. }
  2748. /**
  2749. * Take a FROM, TO, and CC address and add it into the email header list.
  2750. *
  2751. * The following example shows what the final header might look like when
  2752. * the client sends an email to two CC addresses:
  2753. * Cc: mail1\@example.com, mail2\@example.com
  2754. *
  2755. * @param[in] smtp SMTP client context.
  2756. * @param[in] address_type See @ref smtp_address_type.
  2757. * @param[in] key Header key value, for example, To From Cc.
  2758. * @return See @ref smtp_status_code.
  2759. */
  2760. static enum smtp_status_code
  2761. smtp_append_address_to_header(struct smtp *const smtp,
  2762. enum smtp_address_type address_type,
  2763. const char *const key){
  2764. size_t i;
  2765. size_t num_address_in_header;
  2766. size_t header_value_sz;
  2767. size_t name_slen;
  2768. size_t email_slen;
  2769. size_t concat_len;
  2770. struct smtp_address *address;
  2771. char *header_value;
  2772. char *header_value_new;
  2773. char *concat;
  2774. num_address_in_header = 0;
  2775. header_value_sz = 0;
  2776. header_value = NULL;
  2777. concat_len = 0;
  2778. for(i = 0; i < smtp->num_address; i++){
  2779. address = &smtp->address_list[i];
  2780. if(address->type == address_type){
  2781. name_slen = 0;
  2782. if(address->name){
  2783. name_slen = strlen(address->name);
  2784. }
  2785. email_slen = strlen(address->email);
  2786. /*
  2787. * ', "' NAME '" <' EMAIL > \0
  2788. * header_value_sz += 3 + name_slen + 3 + email_slen + 1 + 1
  2789. */
  2790. if(smtp_si_add_size_t(header_value_sz, name_slen, &header_value_sz) ||
  2791. smtp_si_add_size_t(header_value_sz, email_slen, &header_value_sz) ||
  2792. smtp_si_add_size_t(header_value_sz, 3 + 3 + 1 + 1, &header_value_sz)||
  2793. (header_value_new = realloc(header_value,
  2794. header_value_sz)) == NULL){
  2795. free(header_value);
  2796. return smtp_status_code_set(smtp, SMTP_STATUS_NOMEM);
  2797. }
  2798. header_value = header_value_new;
  2799. concat = header_value + concat_len;
  2800. if(num_address_in_header > 0){
  2801. concat = smtp_stpcpy(concat, ", ");
  2802. }
  2803. if(name_slen){
  2804. concat = smtp_stpcpy(concat, "\"");
  2805. concat = smtp_stpcpy(concat, address->name);
  2806. concat = smtp_stpcpy(concat, "\" ");
  2807. }
  2808. concat = smtp_stpcpy(concat, "<");
  2809. concat = smtp_stpcpy(concat, address->email);
  2810. concat = smtp_stpcpy(concat, ">");
  2811. num_address_in_header += 1;
  2812. concat_len = (size_t)(concat - header_value);
  2813. }
  2814. }
  2815. if(header_value){
  2816. smtp_header_add(smtp, key, header_value);
  2817. free(header_value);
  2818. }
  2819. return smtp->status_code;
  2820. }
  2821. /**
  2822. * Send envelope MAIL FROM or RCPT TO header address.
  2823. *
  2824. * Examples:
  2825. * MAIL FROM:<mail\@example.com>
  2826. * RCPT TO:<mail\@example.com>
  2827. *
  2828. * @param[in] smtp SMTP client context.
  2829. * @param[in] header Either "MAIL FROM" or "RCPT TO".
  2830. * @param[in] address See @ref smtp_address -> email field.
  2831. * @return See @ref smtp_status_code.
  2832. */
  2833. static enum smtp_status_code
  2834. smtp_mail_envelope_header(struct smtp *const smtp,
  2835. const char *const header,
  2836. const struct smtp_address *const address){
  2837. const char *const SMTPUTF8 = " SMTPUTF8";
  2838. const size_t SMTPUTF8_LEN = strlen(SMTPUTF8);
  2839. size_t email_len;
  2840. size_t bufsz;
  2841. char *envelope_address;
  2842. char *concat;
  2843. const char *smtputf8_opt;
  2844. email_len = strlen(address->email);
  2845. /* bufsz = 14 + email_len + SMTPUTF8_LEN + 1 */
  2846. if(smtp_si_add_size_t(email_len, SMTPUTF8_LEN + 14 + 1, &bufsz) ||
  2847. (envelope_address = malloc(bufsz)) == NULL){
  2848. return smtp_status_code_set(smtp, SMTP_STATUS_NOMEM);
  2849. }
  2850. smtputf8_opt = "";
  2851. if(smtp_str_has_nonascii_utf8(address->email)){
  2852. smtputf8_opt = SMTPUTF8;
  2853. }
  2854. concat = smtp_stpcpy(envelope_address, header);
  2855. concat = smtp_stpcpy(concat, ":<");
  2856. concat = smtp_stpcpy(concat, address->email);
  2857. concat = smtp_stpcpy(concat, ">");
  2858. concat = smtp_stpcpy(concat, smtputf8_opt);
  2859. smtp_stpcpy(concat, "\r\n");
  2860. smtp_puts(smtp, envelope_address);
  2861. free(envelope_address);
  2862. if(smtp->status_code != SMTP_STATUS_OK){
  2863. return smtp->status_code;
  2864. }
  2865. smtp_read_and_parse_code(smtp);
  2866. return smtp->status_code;
  2867. }
  2868. /**
  2869. * Comparison function for qsort which sorts headers alphabetically based
  2870. * on the key.
  2871. *
  2872. * @param[in] v1 The first @ref smtp_header to compare.
  2873. * @param[in] v2 The second @ref smtp_header to compare.
  2874. * @retval 0 If the keys match.
  2875. * @retval !0 If the keys do not match.
  2876. */
  2877. static int
  2878. smtp_header_cmp(const void *v1,
  2879. const void *v2){
  2880. const struct smtp_header *header1;
  2881. const struct smtp_header *header2;
  2882. header1 = v1;
  2883. header2 = v2;
  2884. return strcmp(header1->key, header2->key);
  2885. }
  2886. /**
  2887. * Validate characters in the email header key.
  2888. *
  2889. * Must consist only of printable US-ASCII characters except colon.
  2890. *
  2891. * @param[in] key Header key to validate.
  2892. * @retval 0 Successful validation.
  2893. * @retval -1 Failed to validate.
  2894. */
  2895. SMTP_LINKAGE int
  2896. smtp_header_key_validate(const char *const key){
  2897. unsigned char uc;
  2898. size_t i;
  2899. size_t keylen;
  2900. keylen = strlen(key);
  2901. if(keylen < 1){
  2902. return -1;
  2903. }
  2904. for(i = 0; i < keylen; i++){
  2905. uc = (unsigned char)key[i];
  2906. if(uc <= ' ' || uc > 126 || uc == ':'){
  2907. return -1;
  2908. }
  2909. }
  2910. return 0;
  2911. }
  2912. /**
  2913. * Validate characters in the email header contents.
  2914. *
  2915. * Must consist only of printable character, space, or horizontal tab.
  2916. *
  2917. * @param[in] value Header value to validate.
  2918. * @retval 0 Successful validation.
  2919. * @retval -1 Failed to validate.
  2920. */
  2921. SMTP_LINKAGE int
  2922. smtp_header_value_validate(const char *const value){
  2923. size_t i;
  2924. unsigned char uc;
  2925. for(i = 0; value[i]; i++){
  2926. uc = (unsigned char)value[i];
  2927. if((uc < ' ' || uc > 126) &&
  2928. uc != '\t' &&
  2929. uc < 0x80){ /* Allow UTF-8 byte sequence. */
  2930. return -1;
  2931. }
  2932. }
  2933. return 0;
  2934. }
  2935. /**
  2936. * Validate characters in the email address.
  2937. *
  2938. * The email address must consist only of printable characters excluding
  2939. * the angle brackets (<) and (>).
  2940. *
  2941. * @param[in] email The email address of the party.
  2942. * @retval 0 Successful validation.
  2943. * @retval -1 Failed to validate.
  2944. */
  2945. SMTP_LINKAGE int
  2946. smtp_address_validate_email(const char *const email){
  2947. size_t i;
  2948. unsigned char uc;
  2949. for(i = 0; email[i]; i++){
  2950. uc = (unsigned char)email[i];
  2951. if(uc <= ' ' || uc == 127 ||
  2952. uc == '<' || uc == '>'){
  2953. return -1;
  2954. }
  2955. }
  2956. return 0;
  2957. }
  2958. /**
  2959. * Validate characters in the email name.
  2960. *
  2961. * Email user name must consist only of printable characters, excluding the
  2962. * double quote character.
  2963. *
  2964. * @param[in] name Email name to validate.
  2965. * @retval 0 Successful validation.
  2966. * @retval -1 Failed to validate.
  2967. */
  2968. SMTP_LINKAGE int
  2969. smtp_address_validate_name(const char *const name){
  2970. size_t i;
  2971. unsigned char uc;
  2972. for(i = 0; name[i]; i++){
  2973. uc = (unsigned char)name[i];
  2974. if(uc < ' ' || uc == 127 || uc == '\"'){
  2975. return -1;
  2976. }
  2977. }
  2978. return 0;
  2979. }
  2980. /**
  2981. * Validate characters in the attachment file name.
  2982. *
  2983. * Must consist only of printable characters or the space character ( ), and
  2984. * excluding the quote characters (') and (").
  2985. *
  2986. * @param[in] name Filename of the attachment shown to recipients.
  2987. * @retval 0 Successful validation.
  2988. * @retval -1 Failed to validate.
  2989. */
  2990. SMTP_LINKAGE int
  2991. smtp_attachment_validate_name(const char *const name){
  2992. size_t i;
  2993. unsigned char uc;
  2994. for(i = 0; name[i]; i++){
  2995. uc = (unsigned char)name[i];
  2996. if(uc < ' ' || uc == 127 ||
  2997. uc == '\'' || uc == '\"'){
  2998. return -1;
  2999. }
  3000. }
  3001. return 0;
  3002. }
  3003. /**
  3004. * Special flag value for the SMTP context used to determine if the initial
  3005. * memory allocation failed to create the context.
  3006. */
  3007. #define SMTP_FLAG_INVALID_MEMORY (enum smtp_flag)(0xFFFFFFFF)
  3008. /**
  3009. * This error structure used for the single error case where we cannot
  3010. * initially allocate memory. This makes it easier to propagate any
  3011. * error codes when calling the other header functions because the
  3012. * caller will always get a valid SMTP structure returned.
  3013. */
  3014. static struct smtp
  3015. g_smtp_error = {
  3016. SMTP_FLAG_INVALID_MEMORY, /* flags */
  3017. 0, /* sock */
  3018. { /* gdfd */
  3019. NULL, /* _buf */
  3020. 0, /* _bufsz */
  3021. 0, /* _buf_len */
  3022. NULL, /* line */
  3023. 0, /* line_len */
  3024. NULL, /* getdelimfd_read */
  3025. NULL, /* user_data */
  3026. 0, /* delim */
  3027. {0} /* pad */
  3028. }, /* gdfd */
  3029. NULL, /* header_list */
  3030. 0, /* num_headers */
  3031. NULL, /* address_list */
  3032. 0, /* num_address */
  3033. NULL, /* attachment_list */
  3034. 0, /* num_attachment */
  3035. 0, /* timeout_sec */
  3036. SMTP_STATUS_NOMEM, /* smtp_status_code status_code */
  3037. 0, /* tls_on */
  3038. NULL /* cafile */
  3039. #ifdef SMTP_OPENSSL
  3040. ,
  3041. NULL, /* tls */
  3042. NULL, /* tls_ctx */
  3043. NULL /* tls_bio */
  3044. #endif /* SMTP_OPENSSL */
  3045. };
  3046. enum smtp_status_code
  3047. smtp_open(const char *const server,
  3048. const char *const port,
  3049. enum smtp_connection_security connection_security,
  3050. enum smtp_flag flags,
  3051. const char *const cafile,
  3052. struct smtp **smtp){
  3053. struct smtp *snew;
  3054. if((snew = calloc(1, sizeof(**smtp))) == NULL){
  3055. *smtp = &g_smtp_error;
  3056. return smtp_status_code_get(*smtp);
  3057. }
  3058. *smtp = snew;
  3059. snew->flags = flags;
  3060. snew->sock = -1;
  3061. snew->gdfd.delim = '\n';
  3062. snew->gdfd.getdelimfd_read = smtp_str_getdelimfd_read;
  3063. snew->gdfd.user_data = snew;
  3064. snew->cafile = cafile;
  3065. #ifndef SMTP_IS_WINDOWS
  3066. signal(SIGPIPE, SIG_IGN);
  3067. #endif /* !(SMTP_IS_WINDOWS) */
  3068. if(smtp_connect(snew, server, port) < 0){
  3069. return smtp_status_code_set(*smtp, SMTP_STATUS_CONNECT);
  3070. }
  3071. if(smtp_initiate_handshake(snew,
  3072. server,
  3073. connection_security) != SMTP_STATUS_OK){
  3074. return smtp_status_code_set(*smtp, SMTP_STATUS_HANDSHAKE);
  3075. }
  3076. return snew->status_code;
  3077. }
  3078. enum smtp_status_code
  3079. smtp_auth(struct smtp *const smtp,
  3080. enum smtp_authentication_method auth_method,
  3081. const char *const user,
  3082. const char *const pass){
  3083. int auth_rc;
  3084. if(smtp->status_code != SMTP_STATUS_OK){
  3085. return smtp->status_code;
  3086. }
  3087. if(auth_method == SMTP_AUTH_PLAIN){
  3088. auth_rc = smtp_auth_plain(smtp, user, pass);
  3089. }
  3090. else if(auth_method == SMTP_AUTH_LOGIN){
  3091. auth_rc = smtp_auth_login(smtp, user, pass);
  3092. }
  3093. #ifdef SMTP_OPENSSL
  3094. else if(auth_method == SMTP_AUTH_CRAM_MD5){
  3095. auth_rc = smtp_auth_cram_md5(smtp, user, pass);
  3096. }
  3097. #endif /* SMTP_OPENSSL */
  3098. else if(auth_method == SMTP_AUTH_NONE){
  3099. auth_rc = 0;
  3100. }
  3101. else{
  3102. return smtp_status_code_set(smtp, SMTP_STATUS_PARAM);
  3103. }
  3104. if(auth_rc < 0){
  3105. return smtp_status_code_set(smtp, SMTP_STATUS_AUTH);
  3106. }
  3107. return smtp->status_code;
  3108. }
  3109. enum smtp_status_code
  3110. smtp_mail(struct smtp *const smtp,
  3111. const char *const body){
  3112. size_t i;
  3113. int has_mail_from;
  3114. struct smtp_address *address;
  3115. char date[SMTP_DATE_MAX_SZ];
  3116. if(smtp->status_code != SMTP_STATUS_OK){
  3117. return smtp->status_code;
  3118. }
  3119. /* MAIL timeout 5 minutes. */
  3120. smtp_set_read_timeout(smtp, 60 * 5);
  3121. has_mail_from = 0;
  3122. for(i = 0; i < smtp->num_address; i++){
  3123. address = &smtp->address_list[i];
  3124. if(address->type == SMTP_ADDRESS_FROM){
  3125. if(smtp_mail_envelope_header(smtp,
  3126. "MAIL FROM",
  3127. address) != SMTP_STATUS_OK){
  3128. return smtp->status_code;
  3129. }
  3130. has_mail_from = 1;
  3131. break;
  3132. }
  3133. }
  3134. if(!has_mail_from){
  3135. return smtp_status_code_set(smtp, SMTP_STATUS_PARAM);
  3136. }
  3137. /* RCPT timeout 5 minutes. */
  3138. smtp_set_read_timeout(smtp, 60 * 5);
  3139. for(i = 0; i < smtp->num_address; i++){
  3140. address = &smtp->address_list[i];
  3141. if(address->type != SMTP_ADDRESS_FROM){
  3142. if(smtp_mail_envelope_header(smtp,
  3143. "RCPT TO",
  3144. address) != SMTP_STATUS_OK){
  3145. return smtp->status_code;
  3146. }
  3147. }
  3148. }
  3149. /* DATA timeout 2 minutes. */
  3150. smtp_set_read_timeout(smtp, 60 * 2);
  3151. if(smtp_puts(smtp, "DATA\r\n") != SMTP_STATUS_OK){
  3152. return smtp->status_code;
  3153. }
  3154. /* 354 response to DATA must get returned before we can send the message. */
  3155. if(smtp_read_and_parse_code(smtp) != SMTP_BEGIN_MAIL){
  3156. return smtp_status_code_set(smtp, SMTP_STATUS_SERVER_RESPONSE);
  3157. }
  3158. if(!smtp_header_exists(smtp, "Date")){
  3159. if(smtp_date_rfc_2822(date) < 0){
  3160. return smtp_status_code_set(smtp, SMTP_STATUS_DATE);
  3161. }
  3162. if(smtp_header_add(smtp, "Date", date) != SMTP_STATUS_OK){
  3163. return smtp->status_code;
  3164. }
  3165. }
  3166. /* DATA block timeout 3 minutes. */
  3167. smtp_set_read_timeout(smtp, 60 * 3);
  3168. if(smtp_append_address_to_header(smtp,
  3169. SMTP_ADDRESS_FROM,
  3170. "From") != SMTP_STATUS_OK ||
  3171. smtp_append_address_to_header(smtp,
  3172. SMTP_ADDRESS_TO,
  3173. "To") != SMTP_STATUS_OK ||
  3174. smtp_append_address_to_header(smtp,
  3175. SMTP_ADDRESS_CC,
  3176. "Cc") != SMTP_STATUS_OK){
  3177. return smtp->status_code;
  3178. }
  3179. for(i = 0; i < smtp->num_headers; i++){
  3180. if(smtp_print_header(smtp, &smtp->header_list[i]) != SMTP_STATUS_OK){
  3181. return smtp->status_code;
  3182. }
  3183. }
  3184. if(smtp_print_email(smtp, body)){
  3185. return smtp->status_code;
  3186. }
  3187. /* End of DATA segment. */
  3188. if(smtp_puts(smtp, ".\r\n") != SMTP_STATUS_OK){
  3189. return smtp->status_code;
  3190. }
  3191. /* DATA termination timeout 250 return code - 10 minutes. */
  3192. smtp_set_read_timeout(smtp, 60 * 10);
  3193. if(smtp_read_and_parse_code(smtp) != SMTP_DONE){
  3194. return smtp_status_code_set(smtp, SMTP_STATUS_SERVER_RESPONSE);
  3195. }
  3196. return smtp->status_code;
  3197. }
  3198. enum smtp_status_code
  3199. smtp_close(struct smtp *smtp){
  3200. enum smtp_status_code status_code;
  3201. status_code = smtp->status_code;
  3202. if(smtp->flags == SMTP_FLAG_INVALID_MEMORY){
  3203. return status_code;
  3204. }
  3205. if(smtp->sock != -1){
  3206. /*
  3207. * Do not error out if this fails because we still need to free the
  3208. * SMTP client resources.
  3209. */
  3210. smtp->status_code = SMTP_STATUS_OK;
  3211. smtp_puts(smtp, "QUIT\r\n");
  3212. #ifdef SMTP_OPENSSL
  3213. if(smtp->tls_on){
  3214. SSL_free(smtp->tls);
  3215. SSL_CTX_free(smtp->tls_ctx);
  3216. }
  3217. #endif /* SMTP_OPENSSL */
  3218. #ifdef SMTP_IS_WINDOWS
  3219. closesocket(smtp->sock);
  3220. WSACleanup();
  3221. #else /* POSIX */
  3222. if(close(smtp->sock) < 0){
  3223. if(smtp->status_code == SMTP_STATUS_OK){
  3224. smtp_status_code_set(smtp, SMTP_STATUS_CLOSE);
  3225. }
  3226. }
  3227. #endif /* SMTP_IS_WINDOWS */
  3228. }
  3229. smtp_str_getdelimfd_free(&smtp->gdfd);
  3230. smtp_header_clear_all(smtp);
  3231. smtp_address_clear_all(smtp);
  3232. smtp_attachment_clear_all(smtp);
  3233. if(status_code == SMTP_STATUS_OK){
  3234. status_code = smtp->status_code;
  3235. }
  3236. free(smtp);
  3237. return status_code;
  3238. }
  3239. enum smtp_status_code
  3240. smtp_status_code_get(const struct smtp *const smtp){
  3241. return smtp->status_code;
  3242. }
  3243. enum smtp_status_code
  3244. smtp_status_code_clear(struct smtp *const smtp){
  3245. enum smtp_status_code old_status;
  3246. old_status = smtp_status_code_get(smtp);
  3247. smtp_status_code_set(smtp, SMTP_STATUS_OK);
  3248. return old_status;
  3249. }
  3250. enum smtp_status_code
  3251. smtp_status_code_set(struct smtp *const smtp,
  3252. enum smtp_status_code status_code){
  3253. if((unsigned)status_code >= SMTP_STATUS__LAST){
  3254. return smtp_status_code_set(smtp, SMTP_STATUS_PARAM);
  3255. }
  3256. smtp->status_code = status_code;
  3257. return status_code;
  3258. }
  3259. const char *
  3260. smtp_status_code_errstr(enum smtp_status_code status_code){
  3261. const char *const status_code_err_str[] = {
  3262. /* SMTP_STATUS_OK */
  3263. "Success",
  3264. /* SMTP_STATUS_NOMEM */
  3265. "Memory allocation failed",
  3266. /* SMTP_STATUS_CONNECT */
  3267. "Failed to connect to the mail server",
  3268. /* SMTP_STATUS_HANDSHAKE */
  3269. "Failed to handshake or negotiate a TLS connection with the server",
  3270. /* SMTP_STATUS_AUTH */
  3271. "Failed to authenticate with the given credentials",
  3272. /* SMTP_STATUS_SEND */
  3273. "Failed to send bytes to the server",
  3274. /* SMTP_STATUS_RECV */
  3275. "Failed to receive bytes from the server",
  3276. /* SMTP_STATUS_CLOSE */
  3277. "Failed to properly close a connection",
  3278. /* SMTP_STATUS_SERVER_RESPONSE */
  3279. "SMTP server sent back an unexpected status code",
  3280. /* SMTP_STATUS_PARAM */
  3281. "Invalid parameter",
  3282. /* SMTP_STATUS_FILE */
  3283. "Failed to read or open a local file",
  3284. /* SMTP_STATUS_DATE */
  3285. "Failed to get the local date and time",
  3286. /* SMTP_STATUS__LAST */
  3287. "Unknown error"
  3288. };
  3289. if((unsigned)status_code > SMTP_STATUS__LAST){
  3290. status_code = SMTP_STATUS__LAST;
  3291. }
  3292. return status_code_err_str[status_code];
  3293. }
  3294. enum smtp_status_code
  3295. smtp_header_add(struct smtp *const smtp,
  3296. const char *const key,
  3297. const char *const value){
  3298. struct smtp_header *new_header_list;
  3299. struct smtp_header *new_header;
  3300. size_t num_headers_inc;
  3301. if(smtp->status_code != SMTP_STATUS_OK){
  3302. return smtp->status_code;
  3303. }
  3304. if(smtp_header_key_validate(key) < 0){
  3305. return smtp_status_code_set(smtp, SMTP_STATUS_PARAM);
  3306. }
  3307. if(value && smtp_header_value_validate(value) < 0){
  3308. return smtp_status_code_set(smtp, SMTP_STATUS_PARAM);
  3309. }
  3310. if(smtp_si_add_size_t(smtp->num_headers, 1, &num_headers_inc) ||
  3311. (new_header_list = smtp_reallocarray(
  3312. smtp->header_list,
  3313. num_headers_inc,
  3314. sizeof(*smtp->header_list))) == NULL){
  3315. return smtp_status_code_set(smtp, SMTP_STATUS_NOMEM);
  3316. }
  3317. smtp->header_list = new_header_list;
  3318. new_header = &smtp->header_list[smtp->num_headers];
  3319. new_header->key = smtp_strdup(key);
  3320. if(value){
  3321. new_header->value = smtp_strdup(value);
  3322. }
  3323. else{
  3324. new_header->value = NULL;
  3325. }
  3326. if(new_header->key == NULL ||
  3327. (new_header->value == NULL && value)){
  3328. free(new_header->key);
  3329. free(new_header->value);
  3330. return smtp_status_code_set(smtp, SMTP_STATUS_NOMEM);
  3331. }
  3332. smtp->num_headers = num_headers_inc;
  3333. qsort(smtp->header_list,
  3334. smtp->num_headers,
  3335. sizeof(*smtp->header_list),
  3336. smtp_header_cmp);
  3337. return smtp->status_code;
  3338. }
  3339. void
  3340. smtp_header_clear_all(struct smtp *const smtp){
  3341. size_t i;
  3342. struct smtp_header *header;
  3343. for(i = 0; i < smtp->num_headers; i++){
  3344. header = &smtp->header_list[i];
  3345. free(header->key);
  3346. free(header->value);
  3347. }
  3348. free(smtp->header_list);
  3349. smtp->header_list = NULL;
  3350. smtp->num_headers = 0;
  3351. }
  3352. enum smtp_status_code
  3353. smtp_address_add(struct smtp *const smtp,
  3354. enum smtp_address_type type,
  3355. const char *const email,
  3356. const char *const name){
  3357. struct smtp_address *new_address_list;
  3358. struct smtp_address *new_address;
  3359. size_t num_address_inc;
  3360. if(smtp->status_code != SMTP_STATUS_OK){
  3361. return smtp->status_code;
  3362. }
  3363. if(smtp_address_validate_email(email) < 0){
  3364. return smtp_status_code_set(smtp, SMTP_STATUS_PARAM);
  3365. }
  3366. if(name && smtp_address_validate_name(name) < 0){
  3367. return smtp_status_code_set(smtp, SMTP_STATUS_PARAM);
  3368. }
  3369. if(smtp_si_add_size_t(smtp->num_address, 1, &num_address_inc)){
  3370. return smtp_status_code_set(smtp, SMTP_STATUS_NOMEM);
  3371. }
  3372. new_address_list = smtp_reallocarray(smtp->address_list,
  3373. num_address_inc,
  3374. sizeof(*new_address_list));
  3375. if(new_address_list == NULL){
  3376. return smtp_status_code_set(smtp, SMTP_STATUS_NOMEM);
  3377. }
  3378. new_address = &new_address_list[smtp->num_address];
  3379. smtp->address_list = new_address_list;
  3380. new_address->type = type;
  3381. new_address->email = smtp_strdup(email);
  3382. if(name){
  3383. new_address->name = smtp_strdup(name);
  3384. }
  3385. else{
  3386. new_address->name = NULL;
  3387. }
  3388. if(new_address->email == NULL ||
  3389. (new_address->name == NULL && name)){
  3390. free(new_address->email);
  3391. free(new_address->name);
  3392. return smtp_status_code_set(smtp, SMTP_STATUS_NOMEM);
  3393. }
  3394. smtp->num_address = num_address_inc;
  3395. return smtp->status_code;
  3396. }
  3397. void
  3398. smtp_address_clear_all(struct smtp *const smtp){
  3399. size_t i;
  3400. struct smtp_address *address;
  3401. for(i = 0; i < smtp->num_address; i++){
  3402. address = &smtp->address_list[i];
  3403. free(address->email);
  3404. free(address->name);
  3405. }
  3406. free(smtp->address_list);
  3407. smtp->address_list = NULL;
  3408. smtp->num_address = 0;
  3409. }
  3410. enum smtp_status_code
  3411. smtp_attachment_add_path(struct smtp *const smtp,
  3412. const char *const name,
  3413. const char *const path){
  3414. char *data;
  3415. size_t bytes_read;
  3416. if(smtp->status_code != SMTP_STATUS_OK){
  3417. return smtp->status_code;
  3418. }
  3419. errno = 0;
  3420. if((data = smtp_file_get_contents(path, &bytes_read)) == NULL){
  3421. if(errno == ENOMEM){
  3422. return smtp_status_code_set(smtp, SMTP_STATUS_NOMEM);
  3423. }
  3424. return smtp_status_code_set(smtp, SMTP_STATUS_FILE);
  3425. }
  3426. smtp_attachment_add_mem(smtp, name, data, bytes_read);
  3427. free(data);
  3428. return smtp->status_code;
  3429. }
  3430. enum smtp_status_code
  3431. smtp_attachment_add_fp(struct smtp *const smtp,
  3432. const char *const name,
  3433. FILE *fp){
  3434. char *data;
  3435. size_t bytes_read;
  3436. if(smtp->status_code != SMTP_STATUS_OK){
  3437. return smtp->status_code;
  3438. }
  3439. errno = 0;
  3440. if((data = smtp_ffile_get_contents(fp, &bytes_read)) == NULL){
  3441. if(errno == ENOMEM){
  3442. return smtp_status_code_set(smtp, SMTP_STATUS_NOMEM);
  3443. }
  3444. return smtp_status_code_set(smtp, SMTP_STATUS_FILE);
  3445. }
  3446. smtp_attachment_add_mem(smtp, name, data, bytes_read);
  3447. free(data);
  3448. return smtp->status_code;
  3449. }
  3450. enum smtp_status_code
  3451. smtp_attachment_add_mem(struct smtp *const smtp,
  3452. const char *const name,
  3453. const void *const data,
  3454. size_t datasz){
  3455. size_t num_attachment_inc;
  3456. struct smtp_attachment *new_attachment_list;
  3457. struct smtp_attachment *new_attachment;
  3458. char *b64_encode;
  3459. if(smtp->status_code != SMTP_STATUS_OK){
  3460. return smtp->status_code;
  3461. }
  3462. if(smtp_attachment_validate_name(name) < 0){
  3463. return smtp_status_code_set(smtp, SMTP_STATUS_PARAM);
  3464. }
  3465. if(datasz == SIZE_MAX){
  3466. datasz = strlen(data);
  3467. }
  3468. if(smtp_si_add_size_t(smtp->num_attachment, 1, &num_attachment_inc) ||
  3469. (new_attachment_list = smtp_reallocarray(
  3470. smtp->attachment_list,
  3471. num_attachment_inc,
  3472. sizeof(*new_attachment_list))) == NULL){
  3473. return smtp_status_code_set(smtp, SMTP_STATUS_NOMEM);
  3474. }
  3475. smtp->attachment_list = new_attachment_list;
  3476. new_attachment = &new_attachment_list[smtp->num_attachment];
  3477. new_attachment->name = smtp_strdup(name);
  3478. b64_encode = smtp_base64_encode(data, datasz);
  3479. if(new_attachment->name == NULL || b64_encode == NULL){
  3480. free(new_attachment->name);
  3481. free(b64_encode);
  3482. return smtp_status_code_set(smtp, SMTP_STATUS_NOMEM);
  3483. }
  3484. new_attachment->b64_data = smtp_chunk_split(b64_encode,
  3485. SMTP_LINE_MAX,
  3486. "\r\n");
  3487. free(b64_encode);
  3488. if(new_attachment->b64_data == NULL){
  3489. free(new_attachment->name);
  3490. return smtp_status_code_set(smtp, SMTP_STATUS_NOMEM);
  3491. }
  3492. smtp->num_attachment = num_attachment_inc;
  3493. return smtp->status_code;
  3494. }
  3495. void
  3496. smtp_attachment_clear_all(struct smtp *const smtp){
  3497. size_t i;
  3498. struct smtp_attachment *attachment;
  3499. for(i = 0; i < smtp->num_attachment; i++){
  3500. attachment = &smtp->attachment_list[i];
  3501. free(attachment->name);
  3502. free(attachment->b64_data);
  3503. }
  3504. free(smtp->attachment_list);
  3505. smtp->attachment_list = NULL;
  3506. smtp->num_attachment = 0;
  3507. }
  3508. /////////////////////////////////////////////////////
  3509. #include <stdint.h>
  3510. #include "common.h"
  3511. #include "thread.h"
  3512. #include "xlist.h"
  3513. #include "elog.h"
  3514. #include "lock.h"
  3515. #include "sqlite_handle.h"
  3516. #if 1
  3517. #define LOGD log_d
  3518. #define LOGE log_e
  3519. #define LOGW log_w
  3520. #else
  3521. #define LOGD printf
  3522. #define LOGE printf
  3523. #define LOGW printf
  3524. #endif
  3525. #define MAIL_CONNECTION_SECURITY SMTP_SECURITY_STARTTLS
  3526. #define MAIL_FLAGS (SMTP_DEBUG|SMTP_NO_CERT_VERIFY) /* Do not verify cert. */
  3527. #define MAIL_CAFILE NULL
  3528. #define MAIL_AUTH SMTP_AUTH_PLAIN
  3529. static int send_mail(smtp_send_t *send, void *addr, char *sub, char *body, int multi)
  3530. {
  3531. int i,r=-1,flag=0;
  3532. struct smtp *smtp=NULL;
  3533. enum smtp_flag flags=(SMTP_DEBUG|SMTP_NO_CERT_VERIFY);
  3534. enum smtp_connection_security security=SMTP_SECURITY_STARTTLS;
  3535. enum smtp_authentication_method auth=SMTP_AUTH_PLAIN;
  3536. lock_s_hold(LOCK_ID_SMTP);
  3537. if(!sub || !body || send->mode==0) {
  3538. goto out;
  3539. }
  3540. if(strcmp(send->auth, "LOGIN")==0) {
  3541. auth = SMTP_AUTH_LOGIN;
  3542. }
  3543. else if(strcmp(send->auth, "CRAM-MD5")==0) {
  3544. auth = SMTP_AUTH_CRAM_MD5;
  3545. }
  3546. if(strcmp(send->port,"465")==0) {
  3547. security = SMTP_SECURITY_TLS;
  3548. }
  3549. r = smtp_open(send->server, send->port, security, flags, NULL, &smtp);
  3550. if(r != SMTP_STATUS_OK) {
  3551. LOGE("___ smtp_open failed, %s\n", smtp_status_code_errstr(r));
  3552. return -1;
  3553. }
  3554. r = smtp_auth(smtp, auth, send->account, send->password);
  3555. if(r != SMTP_STATUS_OK) {
  3556. LOGE("___ smtp_auth failed, %s\n", smtp_status_code_errstr(r));
  3557. goto quit;
  3558. }
  3559. r = smtp_address_add(smtp, SMTP_ADDRESS_FROM, send->account, send->account);
  3560. if(r != SMTP_STATUS_OK) {
  3561. LOGE("___ smtp_address_add fr failed\n, %s", smtp_status_code_errstr(r));
  3562. goto quit;
  3563. }
  3564. if(multi) {
  3565. smtp_recv_t *recv=(smtp_recv_t*)addr;
  3566. for(i=0; i<SMTP_RECV_MAX; i++) {
  3567. if(recv[i].use && strlen(recv[i].account)>0) {
  3568. r = smtp_address_add(smtp, SMTP_ADDRESS_TO, recv[i].account, recv[i].account);
  3569. if(r != SMTP_STATUS_OK) {
  3570. LOGE("___ smtp_address_add to %s failed, %s\n", recv[i].account, smtp_status_code_errstr(r));
  3571. }
  3572. else {
  3573. flag = 1;
  3574. }
  3575. }
  3576. }
  3577. }
  3578. else {
  3579. char *sendto=(char*)addr;
  3580. r = smtp_address_add(smtp, SMTP_ADDRESS_TO, sendto, sendto);
  3581. if(r != SMTP_STATUS_OK) {
  3582. LOGE("___ smtp_address_add to %s failed, %s\n", sendto, smtp_status_code_errstr(r));
  3583. }
  3584. else {
  3585. flag = 1;
  3586. }
  3587. }
  3588. if(flag>0) {
  3589. r = smtp_header_add(smtp, "Subject", sub);
  3590. if(r != SMTP_STATUS_OK) {
  3591. LOGE("___ smtp_header_add failed, %s\n", smtp_status_code_errstr(r));
  3592. goto quit;
  3593. }
  3594. //r = smtp_attachment_add_mem(smtp, "test.txt", "Test email attachment.", -1);
  3595. smtp_mail(smtp, body);
  3596. }
  3597. quit:
  3598. smtp_close(smtp);
  3599. if(r != SMTP_STATUS_OK){
  3600. LOGE("___ send_mail failed, server: %s, port: %s failed\n", send->server, send->port);
  3601. }
  3602. out:
  3603. lock_s_release(LOCK_ID_SMTP);
  3604. return r;
  3605. }
  3606. typedef struct {
  3607. char sub[128];
  3608. char body[2048];
  3609. }smtp_pkt_t;
  3610. typedef struct {
  3611. handle_t list;
  3612. smtp_info_t *info;
  3613. GlobalDeviceManager *dm;
  3614. }smtp_handle_t;
  3615. static smtp_handle_t smHandle;
  3616. static void sleep_ms(int ms)
  3617. {
  3618. usleep(ms*1000);
  3619. }
  3620. static void* smtp_thread(void *arg)
  3621. {
  3622. int r;
  3623. thread_handle_t *th=(thread_handle_t*)arg;
  3624. smtp_handle_t *h=(smtp_handle_t*)th->arg;
  3625. list_node_t *ln=NULL;
  3626. smtp_pkt_t *pkt=NULL;
  3627. smtp_send_t *send=&h->info->send;
  3628. smtp_recv_t *recv=h->info->recv;
  3629. while(th->quit==0) {
  3630. r = xlist_take_node(h->list, &ln, 0);
  3631. if(r==0) {
  3632. pkt = (smtp_pkt_t*)ln->data.buf;
  3633. send_mail(send, recv, pkt->sub, pkt->body, 1);
  3634. }
  3635. xlist_back_node(h->list, ln);
  3636. if(r) {
  3637. sleep_ms(300);
  3638. }
  3639. }
  3640. pthread_exit(NULL);
  3641. }
  3642. #endif
  3643. int smtp_init(void)
  3644. {
  3645. #ifdef USE_SMTP
  3646. list_cfg_t lc;
  3647. smtp_handle_t *h=&smHandle;
  3648. GlobalDeviceManager *dm=&__globalDeviceManage;
  3649. lc.mode = LIST_FULL_FIFO;
  3650. lc.max = 100;
  3651. lc.log = 0;
  3652. h->list = xlist_init(&lc);
  3653. h->dm = dm;
  3654. h->info = &h->dm->smtpInfo;
  3655. dev_smtp_init(dm->db, h->info);
  3656. thread_start(THREAD_ID_SMTP, smtp_thread, h, 5*MB, 0);
  3657. //smtp_test();
  3658. #endif
  3659. return 0;
  3660. }
  3661. int smtp_deinit(void)
  3662. {
  3663. #ifdef USE_SMTP
  3664. smtp_handle_t *h=&smHandle;
  3665. thread_stop(THREAD_ID_SMTP);
  3666. xlist_free(h->list);
  3667. #endif
  3668. return 0;
  3669. }
  3670. static int post_data(char *sub, char *body)
  3671. {
  3672. int r=0;
  3673. #ifdef USE_SMTP
  3674. smtp_pkt_t pkt;
  3675. smtp_handle_t *h=&smHandle;
  3676. snprintf(pkt.sub, sizeof(pkt.sub), "%s", sub);
  3677. snprintf(pkt.body, sizeof(pkt.body), "%s", body);
  3678. r = xlist_append(h->list, 0, &pkt, sizeof(pkt));
  3679. #endif
  3680. return r;
  3681. }
  3682. int smtp_send(char *sub, char *body)
  3683. {
  3684. int r=0;
  3685. #ifdef USE_SMTP
  3686. smtp_handle_t *h=&smHandle;
  3687. r = send_mail(&h->info->send, h->info->recv, sub, body, 1);
  3688. #endif
  3689. return r;
  3690. }
  3691. int smtp_post(char *sub, char *body)
  3692. {
  3693. int r=0;
  3694. #ifdef USE_SMTP
  3695. r = post_data(sub, body);
  3696. #endif
  3697. return r;
  3698. }
  3699. int smtp_post_alarm(int type, int subtype, int alarm_type, char *content)
  3700. {
  3701. int r=0;
  3702. #ifdef USE_SMTP
  3703. smtp_pkt_t pkt;
  3704. pkt.sub[0] = pkt.body[0] = 0;
  3705. switch(type) {
  3706. case ALARM_TYPE_POWER:
  3707. {
  3708. switch(alarm_type) {
  3709. case WARNING_V_UP:
  3710. //strcpy(pkt.sub, "");
  3711. break;
  3712. case WARNING_V_DOWN:
  3713. break;
  3714. case WARNING_A_UP:
  3715. break;
  3716. case WARNING_W_UP:
  3717. break;
  3718. case WARNING_P_UP:
  3719. break;
  3720. case 0 ... 2:
  3721. break;
  3722. default:
  3723. return -1;
  3724. }
  3725. }
  3726. break;
  3727. case ALARM_TYPE_SENSOR:
  3728. {
  3729. switch(subtype) {
  3730. case SENSOR_TYPE_TEMPERATURE:
  3731. break;
  3732. case SENSOR_TYPE_SMOKE:
  3733. break;
  3734. case SENSOR_TYPE_WATER:
  3735. break;
  3736. case SENSOR_TYPE_DOOR:
  3737. break;
  3738. case SENSOR_TYPE_GAS:
  3739. break;
  3740. case SENSOR_TYPE_AIR_PRESS:
  3741. break;
  3742. case SENSOR_TYPE_DoubleT:
  3743. break;
  3744. default:
  3745. return -1;
  3746. }
  3747. }
  3748. break;
  3749. case ALARM_TYPE_NETWORK:
  3750. {
  3751. //
  3752. }
  3753. break;
  3754. default:
  3755. return -1;
  3756. }
  3757. snprintf(pkt.sub, sizeof(pkt.sub), "ALARM");
  3758. snprintf(pkt.body, sizeof(pkt.body), content);
  3759. r = post_data(pkt.sub, pkt.body);
  3760. #endif
  3761. return r;
  3762. }
  3763. int smtp_test(void)
  3764. {
  3765. int r=0,cnt=0;
  3766. char temp[200];
  3767. smtp_handle_t *h=&smHandle;
  3768. #ifdef USE_SMTP
  3769. smtp_info_t info={
  3770. .send = {
  3771. .product_id = 0,
  3772. .mode = 1,
  3773. .account = "rcp064867@163.com",
  3774. .password = "UODRIFWDFBTJTVLW",
  3775. .server = "smtp.163.com",
  3776. .port = "25",
  3777. //.port = "465",
  3778. //.port = "587",
  3779. .auth = "PLAIN",
  3780. //.auth = "LOGIN",
  3781. //.auth = "CRAM-MD5",
  3782. },
  3783. .recv = {
  3784. {0, 1, "1556907721@qq.com"},
  3785. {1, 1, "rcp064867@163.com"},
  3786. {2, 1, "cijiu0219@sina.com"},
  3787. {3, 1, "jiuci4902@gmail.com"},
  3788. {4, 1, "cijiu0219@hotmail.com"},
  3789. {5, 1, "cijiu990219@outlook.com"},
  3790. }
  3791. };
  3792. *h->info = info;
  3793. char *sub="123";
  3794. char *body="hello everyone";
  3795. while(cnt++<5) {
  3796. sprintf(temp, "%s %d", body, cnt);
  3797. r = smtp_send(sub, temp);
  3798. sleep(2);
  3799. }
  3800. #endif
  3801. return r;
  3802. }