drv_imap.c 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318
  1. /*
  2. * mbsync - mailbox synchronizer
  3. * Copyright (C) 2000-2002 Michael R. Elkins <me@mutt.org>
  4. * Copyright (C) 2002-2006,2008 Oswald Buddenhagen <ossi@users.sf.net>
  5. * Copyright (C) 2004 Theodore Y. Ts'o <tytso@mit.edu>
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program; if not, write to the Free Software Foundation,
  19. * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
  20. *
  21. * As a special exception, mbsync may be linked with the OpenSSL library,
  22. * despite that library's more restrictive license.
  23. */
  24. /* This must come before isync.h to avoid our #define S messing up
  25. * blowfish.h on MacOS X. */
  26. #include <config.h>
  27. #ifdef HAVE_LIBSSL
  28. # include <openssl/ssl.h>
  29. # include <openssl/err.h>
  30. # include <openssl/hmac.h>
  31. #endif
  32. #include "isync.h"
  33. #include <assert.h>
  34. #include <unistd.h>
  35. #include <sys/mman.h>
  36. #include <sys/time.h>
  37. #include <stdlib.h>
  38. #include <stdio.h>
  39. #include <stddef.h>
  40. #include <limits.h>
  41. #include <errno.h>
  42. #include <string.h>
  43. #include <ctype.h>
  44. #include <sys/socket.h>
  45. #include <sys/ioctl.h>
  46. #ifdef HAVE_SYS_FILIO_H
  47. # include <sys/filio.h>
  48. #endif
  49. #include <netinet/in.h>
  50. #include <netinet/tcp.h>
  51. #include <arpa/inet.h>
  52. #include <netdb.h>
  53. typedef struct imap_server_conf {
  54. struct imap_server_conf *next;
  55. char *name;
  56. char *tunnel;
  57. char *host;
  58. int port;
  59. char *user;
  60. char *pass;
  61. #ifdef HAVE_LIBSSL
  62. char *cert_file;
  63. unsigned use_imaps:1;
  64. unsigned require_ssl:1;
  65. unsigned use_sslv2:1;
  66. unsigned use_sslv3:1;
  67. unsigned use_tlsv1:1;
  68. unsigned require_cram:1;
  69. X509_STORE *cert_store;
  70. #endif
  71. } imap_server_conf_t;
  72. typedef struct imap_store_conf {
  73. store_conf_t gen;
  74. imap_server_conf_t *server;
  75. unsigned use_namespace:1;
  76. } imap_store_conf_t;
  77. typedef struct imap_message {
  78. message_t gen;
  79. /* int seq; will be needed when expunges are tracked */
  80. } imap_message_t;
  81. #define NIL (void*)0x1
  82. #define LIST (void*)0x2
  83. typedef struct _list {
  84. struct _list *next, *child;
  85. char *val;
  86. int len;
  87. } list_t;
  88. typedef struct {
  89. int fd;
  90. #ifdef HAVE_LIBSSL
  91. SSL *ssl;
  92. #endif
  93. } Socket_t;
  94. typedef struct {
  95. Socket_t sock;
  96. int bytes;
  97. int offset;
  98. char buf[1024];
  99. } buffer_t;
  100. struct imap_cmd;
  101. #define max_in_progress 50 /* make this configurable? */
  102. typedef struct imap_store {
  103. store_t gen;
  104. const char *prefix;
  105. int ref_count;
  106. int uidnext; /* from SELECT responses */
  107. unsigned trashnc:1; /* trash folder's existence is not confirmed yet */
  108. unsigned got_namespace:1;
  109. list_t *ns_personal, *ns_other, *ns_shared; /* NAMESPACE info */
  110. message_t **msgapp; /* FETCH results */
  111. unsigned caps; /* CAPABILITY results */
  112. /* command queue */
  113. int nexttag, num_in_progress, literal_pending;
  114. struct imap_cmd *in_progress, **in_progress_append;
  115. #ifdef HAVE_LIBSSL
  116. SSL_CTX *SSLContext;
  117. #endif
  118. /* Used during sequential operations like connect */
  119. enum { GreetingPending = 0, GreetingBad, GreetingOk, GreetingPreauth } greeting;
  120. union {
  121. void (*imap_open)( store_t *srv, void *aux );
  122. } callbacks;
  123. void *callback_aux;
  124. buffer_t buf; /* this is BIG, so put it last */
  125. } imap_store_t;
  126. struct imap_cmd {
  127. struct imap_cmd *next;
  128. char *cmd;
  129. int tag;
  130. struct {
  131. /* Will be called on each continuation request until it resets this pointer.
  132. * Needs to invoke bad_callback and return -1 on error, otherwise return 0. */
  133. int (*cont)( imap_store_t *ctx, struct imap_cmd *cmd, const char *prompt );
  134. void (*done)( imap_store_t *ctx, struct imap_cmd *cmd, int response );
  135. char *data;
  136. int data_len;
  137. int uid; /* to identify fetch responses */
  138. unsigned
  139. to_trash:1, /* we are storing to trash, not current. */
  140. create:1, /* create the mailbox if we get an error ... */
  141. trycreate:1; /* ... but only if this is true or the server says so. */
  142. } param;
  143. };
  144. struct imap_cmd_simple {
  145. struct imap_cmd gen;
  146. void (*callback)( int sts, void *aux );
  147. void *callback_aux;
  148. };
  149. struct imap_cmd_fetch_msg {
  150. struct imap_cmd_simple gen;
  151. msg_data_t *msg_data;
  152. };
  153. struct imap_cmd_out_uid {
  154. struct imap_cmd gen;
  155. void (*callback)( int sts, int uid, void *aux );
  156. void *callback_aux;
  157. int out_uid;
  158. };
  159. struct imap_cmd_refcounted_state {
  160. void (*callback)( int sts, void *aux );
  161. void *callback_aux;
  162. int ref_count;
  163. int ret_val;
  164. };
  165. struct imap_cmd_refcounted {
  166. struct imap_cmd gen;
  167. struct imap_cmd_refcounted_state *state;
  168. };
  169. #define CAP(cap) (ctx->caps & (1 << (cap)))
  170. enum CAPABILITY {
  171. NOLOGIN = 0,
  172. UIDPLUS,
  173. LITERALPLUS,
  174. NAMESPACE,
  175. #ifdef HAVE_LIBSSL
  176. CRAM,
  177. STARTTLS,
  178. #endif
  179. };
  180. static const char *cap_list[] = {
  181. "LOGINDISABLED",
  182. "UIDPLUS",
  183. "LITERAL+",
  184. "NAMESPACE",
  185. #ifdef HAVE_LIBSSL
  186. "AUTH=CRAM-MD5",
  187. "STARTTLS",
  188. #endif
  189. };
  190. #define RESP_OK 0
  191. #define RESP_NO 1
  192. #define RESP_CANCEL 2
  193. static int get_cmd_result( imap_store_t *ctx, struct imap_cmd *tcmd );
  194. static INLINE void imap_ref( imap_store_t *ctx ) { ++ctx->ref_count; }
  195. static int imap_deref( imap_store_t *ctx );
  196. static void imap_invoke_bad_callback( imap_store_t *ctx );
  197. static const char *Flags[] = {
  198. "Draft",
  199. "Flagged",
  200. "Answered",
  201. "Seen",
  202. "Deleted",
  203. };
  204. #ifdef HAVE_LIBSSL
  205. /* Some of this code is inspired by / lifted from mutt. */
  206. static int
  207. compare_certificates( X509 *cert, X509 *peercert,
  208. unsigned char *peermd, unsigned peermdlen )
  209. {
  210. unsigned char md[EVP_MAX_MD_SIZE];
  211. unsigned mdlen;
  212. /* Avoid CPU-intensive digest calculation if the certificates are
  213. * not even remotely equal. */
  214. if (X509_subject_name_cmp( cert, peercert ) ||
  215. X509_issuer_name_cmp( cert, peercert ))
  216. return -1;
  217. if (!X509_digest( cert, EVP_sha1(), md, &mdlen ) ||
  218. peermdlen != mdlen || memcmp( peermd, md, mdlen ))
  219. return -1;
  220. return 0;
  221. }
  222. #if OPENSSL_VERSION_NUMBER >= 0x00904000L
  223. #define READ_X509_KEY(fp, key) PEM_read_X509( fp, key, 0, 0 )
  224. #else
  225. #define READ_X509_KEY(fp, key) PEM_read_X509( fp, key, 0 )
  226. #endif
  227. /* this gets called when a certificate is to be verified */
  228. static int
  229. verify_cert( imap_store_t *ctx )
  230. {
  231. imap_server_conf_t *srvc = ((imap_store_conf_t *)ctx->gen.conf)->server;
  232. SSL *ssl = ctx->buf.sock.ssl;
  233. X509 *cert, *lcert;
  234. BIO *bio;
  235. FILE *fp;
  236. int err;
  237. unsigned n, i;
  238. X509_STORE_CTX xsc;
  239. char buf[256];
  240. unsigned char md[EVP_MAX_MD_SIZE];
  241. cert = SSL_get_peer_certificate( ssl );
  242. if (!cert) {
  243. error( "Error, no server certificate\n" );
  244. return -1;
  245. }
  246. while (srvc->cert_file) { // So break works
  247. if (X509_cmp_current_time( X509_get_notBefore( cert )) >= 0) {
  248. error( "Server certificate is not yet valid" );
  249. break;
  250. }
  251. if (X509_cmp_current_time( X509_get_notAfter( cert )) <= 0) {
  252. error( "Server certificate has expired" );
  253. break;
  254. }
  255. if (!X509_digest( cert, EVP_sha1(), md, &n )) {
  256. error( "*** Unable to calculate digest\n" );
  257. break;
  258. }
  259. if (!(fp = fopen( srvc->cert_file, "rt" ))) {
  260. error( "Unable to load CertificateFile '%s': %s\n",
  261. srvc->cert_file, strerror( errno ) );
  262. return 0;
  263. }
  264. err = -1;
  265. for (lcert = 0; READ_X509_KEY( fp, &lcert ); )
  266. if (!(err = compare_certificates( lcert, cert, md, n )))
  267. break;
  268. X509_free( lcert );
  269. fclose( fp );
  270. if (!err)
  271. return 0;
  272. break;
  273. }
  274. if (!srvc->cert_store) {
  275. if (!(srvc->cert_store = X509_STORE_new())) {
  276. error( "Error creating certificate store\n" );
  277. return -1;
  278. }
  279. if (!X509_STORE_set_default_paths( srvc->cert_store ))
  280. warn( "Error while loading default certificate files: %s\n",
  281. ERR_error_string( ERR_get_error(), 0 ) );
  282. if (!srvc->cert_file) {
  283. info( "Note: CertificateFile not defined\n" );
  284. } else if (!X509_STORE_load_locations( srvc->cert_store, srvc->cert_file, 0 )) {
  285. error( "Error while loading certificate file '%s': %s\n",
  286. srvc->cert_file, ERR_error_string( ERR_get_error(), 0 ) );
  287. return -1;
  288. }
  289. }
  290. X509_STORE_CTX_init( &xsc, srvc->cert_store, cert, 0 );
  291. err = X509_verify_cert( &xsc ) > 0 ? 0 : X509_STORE_CTX_get_error( &xsc );
  292. X509_STORE_CTX_cleanup( &xsc );
  293. if (!err)
  294. return 0;
  295. error( "Error, can't verify certificate: %s (%d)\n",
  296. X509_verify_cert_error_string( err ), err );
  297. X509_NAME_oneline( X509_get_subject_name( cert ), buf, sizeof(buf) );
  298. info( "\nSubject: %s\n", buf );
  299. X509_NAME_oneline( X509_get_issuer_name( cert ), buf, sizeof(buf) );
  300. info( "Issuer: %s\n", buf );
  301. bio = BIO_new( BIO_s_mem() );
  302. ASN1_TIME_print( bio, X509_get_notBefore( cert ) );
  303. memset( buf, 0, sizeof(buf) );
  304. BIO_read( bio, buf, sizeof(buf) - 1 );
  305. info( "Valid from: %s\n", buf );
  306. ASN1_TIME_print( bio, X509_get_notAfter( cert ) );
  307. memset( buf, 0, sizeof(buf) );
  308. BIO_read( bio, buf, sizeof(buf) - 1 );
  309. BIO_free( bio );
  310. info( " to: %s\n", buf );
  311. if (!X509_digest( cert, EVP_md5(), md, &n )) {
  312. error( "*** Unable to calculate fingerprint\n" );
  313. } else {
  314. info( "Fingerprint: " );
  315. for (i = 0; i < n; i += 2)
  316. info( "%02X%02X ", md[i], md[i + 1] );
  317. info( "\n" );
  318. }
  319. fputs( "\nAccept certificate? [y/N]: ", stderr );
  320. if (fgets( buf, sizeof(buf), stdin ) && (buf[0] == 'y' || buf[0] == 'Y'))
  321. return 0;
  322. return -1;
  323. }
  324. static int
  325. init_ssl_ctx( imap_store_t *ctx )
  326. {
  327. imap_server_conf_t *srvc = ((imap_store_conf_t *)ctx->gen.conf)->server;
  328. const SSL_METHOD *method;
  329. int options = 0;
  330. if (srvc->use_tlsv1 && !srvc->use_sslv2 && !srvc->use_sslv3)
  331. method = TLSv1_client_method();
  332. else
  333. method = SSLv23_client_method();
  334. ctx->SSLContext = SSL_CTX_new( method );
  335. if (!srvc->use_sslv2)
  336. options |= SSL_OP_NO_SSLv2;
  337. if (!srvc->use_sslv3)
  338. options |= SSL_OP_NO_SSLv3;
  339. if (!srvc->use_tlsv1)
  340. options |= SSL_OP_NO_TLSv1;
  341. SSL_CTX_set_options( ctx->SSLContext, options );
  342. /* we check the result of the verification after SSL_connect() */
  343. SSL_CTX_set_verify( ctx->SSLContext, SSL_VERIFY_NONE, 0 );
  344. return 0;
  345. }
  346. #endif /* HAVE_LIBSSL */
  347. static void
  348. socket_perror( const char *func, Socket_t *sock, int ret )
  349. {
  350. #ifdef HAVE_LIBSSL
  351. int err;
  352. if (sock->ssl) {
  353. switch ((err = SSL_get_error( sock->ssl, ret ))) {
  354. case SSL_ERROR_SYSCALL:
  355. case SSL_ERROR_SSL:
  356. if ((err = ERR_get_error()) == 0) {
  357. if (ret == 0)
  358. error( "SSL_%s: got EOF\n", func );
  359. else
  360. error( "SSL_%s: %s\n", func, strerror(errno) );
  361. } else
  362. error( "SSL_%s: %s\n", func, ERR_error_string( err, 0 ) );
  363. return;
  364. default:
  365. error( "SSL_%s: unhandled SSL error %d\n", func, err );
  366. break;
  367. }
  368. return;
  369. }
  370. #else
  371. (void)sock;
  372. #endif
  373. if (ret < 0)
  374. perror( func );
  375. else
  376. error( "%s: unexpected EOF\n", func );
  377. }
  378. static int
  379. socket_read( Socket_t *sock, char *buf, int len )
  380. {
  381. int n;
  382. assert( sock->fd >= 0 );
  383. n =
  384. #ifdef HAVE_LIBSSL
  385. sock->ssl ? SSL_read( sock->ssl, buf, len ) :
  386. #endif
  387. read( sock->fd, buf, len );
  388. if (n <= 0) {
  389. socket_perror( "read", sock, n );
  390. close( sock->fd );
  391. sock->fd = -1;
  392. }
  393. return n;
  394. }
  395. static int
  396. socket_write( Socket_t *sock, char *buf, int len )
  397. {
  398. int n;
  399. assert( sock->fd >= 0 );
  400. n =
  401. #ifdef HAVE_LIBSSL
  402. sock->ssl ? SSL_write( sock->ssl, buf, len ) :
  403. #endif
  404. write( sock->fd, buf, len );
  405. if (n != len) {
  406. socket_perror( "write", sock, n );
  407. close( sock->fd );
  408. sock->fd = -1;
  409. }
  410. return n;
  411. }
  412. static int
  413. socket_pending( Socket_t *sock )
  414. {
  415. int num = -1;
  416. if (ioctl( sock->fd, FIONREAD, &num ) < 0)
  417. return -1;
  418. if (num > 0)
  419. return num;
  420. #ifdef HAVE_LIBSSL
  421. if (sock->ssl)
  422. return SSL_pending( sock->ssl );
  423. #endif
  424. return 0;
  425. }
  426. /* simple line buffering */
  427. static int
  428. buffer_gets( buffer_t * b, char **s )
  429. {
  430. int n;
  431. int start = b->offset;
  432. *s = b->buf + start;
  433. for (;;) {
  434. /* make sure we have enough data to read the \r\n sequence */
  435. if (b->offset + 1 >= b->bytes) {
  436. if (start) {
  437. /* shift down used bytes */
  438. *s = b->buf;
  439. assert( start <= b->bytes );
  440. n = b->bytes - start;
  441. if (n)
  442. memmove( b->buf, b->buf + start, n );
  443. b->offset -= start;
  444. b->bytes = n;
  445. start = 0;
  446. }
  447. n = socket_read( &b->sock, b->buf + b->bytes,
  448. sizeof(b->buf) - b->bytes );
  449. if (n <= 0)
  450. return -1;
  451. b->bytes += n;
  452. }
  453. if (b->buf[b->offset] == '\r') {
  454. assert( b->offset + 1 < b->bytes );
  455. if (b->buf[b->offset + 1] == '\n') {
  456. b->buf[b->offset] = 0; /* terminate the string */
  457. b->offset += 2; /* next line */
  458. if (DFlags & VERBOSE)
  459. puts( *s );
  460. return 0;
  461. }
  462. }
  463. b->offset++;
  464. }
  465. /* not reached */
  466. }
  467. static struct imap_cmd *
  468. new_imap_cmd( int size )
  469. {
  470. struct imap_cmd *cmd = nfmalloc( size );
  471. memset( &cmd->param, 0, sizeof(cmd->param) );
  472. return cmd;
  473. }
  474. #define INIT_IMAP_CMD(type, cmdp, cb, aux) \
  475. cmdp = (struct type *)new_imap_cmd( sizeof(*cmdp) ); \
  476. cmdp->callback = cb; \
  477. cmdp->callback_aux = aux;
  478. #define INIT_IMAP_CMD_X(type, cmdp, cb, aux) \
  479. cmdp = (struct type *)new_imap_cmd( sizeof(*cmdp) ); \
  480. cmdp->gen.callback = cb; \
  481. cmdp->gen.callback_aux = aux;
  482. static struct imap_cmd *
  483. v_submit_imap_cmd( imap_store_t *ctx, struct imap_cmd *cmd,
  484. const char *fmt, va_list ap )
  485. {
  486. int bufl, litplus;
  487. const char *buffmt;
  488. char buf[1024];
  489. assert( ctx );
  490. assert( ctx->gen.bad_callback );
  491. assert( cmd );
  492. assert( cmd->param.done );
  493. while (ctx->literal_pending)
  494. if (get_cmd_result( ctx, 0 ) == RESP_CANCEL)
  495. goto bail2;
  496. cmd->tag = ++ctx->nexttag;
  497. if (fmt)
  498. nfvasprintf( &cmd->cmd, fmt, ap );
  499. if (!cmd->param.data) {
  500. buffmt = "%d %s\r\n";
  501. litplus = 0;
  502. } else if ((cmd->param.to_trash && ctx->trashnc) || !CAP(LITERALPLUS)) {
  503. buffmt = "%d %s{%d}\r\n";
  504. litplus = 0;
  505. } else {
  506. buffmt = "%d %s{%d+}\r\n";
  507. litplus = 1;
  508. }
  509. bufl = nfsnprintf( buf, sizeof(buf), buffmt,
  510. cmd->tag, cmd->cmd, cmd->param.data_len );
  511. if (DFlags & VERBOSE) {
  512. if (ctx->num_in_progress)
  513. printf( "(%d in progress) ", ctx->num_in_progress );
  514. if (memcmp( cmd->cmd, "LOGIN", 5 ))
  515. printf( ">>> %s", buf );
  516. else
  517. printf( ">>> %d LOGIN <user> <pass>\n", cmd->tag );
  518. }
  519. if (socket_write( &ctx->buf.sock, buf, bufl ) != bufl)
  520. goto bail;
  521. if (litplus) {
  522. if (socket_write( &ctx->buf.sock, cmd->param.data, cmd->param.data_len ) != cmd->param.data_len ||
  523. socket_write( &ctx->buf.sock, "\r\n", 2 ) != 2)
  524. goto bail;
  525. free( cmd->param.data );
  526. cmd->param.data = 0;
  527. } else if (cmd->param.cont || cmd->param.data) {
  528. ctx->literal_pending = 1;
  529. }
  530. cmd->next = 0;
  531. *ctx->in_progress_append = cmd;
  532. ctx->in_progress_append = &cmd->next;
  533. ctx->num_in_progress++;
  534. return cmd;
  535. bail:
  536. imap_invoke_bad_callback( ctx );
  537. bail2:
  538. cmd->param.done( ctx, cmd, RESP_CANCEL );
  539. free( cmd->param.data );
  540. free( cmd->cmd );
  541. free( cmd );
  542. return NULL;
  543. }
  544. static struct imap_cmd *
  545. submit_imap_cmd( imap_store_t *ctx, struct imap_cmd *cmd, const char *fmt, ... )
  546. {
  547. struct imap_cmd *ret;
  548. va_list ap;
  549. va_start( ap, fmt );
  550. ret = v_submit_imap_cmd( ctx, cmd, fmt, ap );
  551. va_end( ap );
  552. return ret;
  553. }
  554. static int
  555. imap_exec( imap_store_t *ctx, struct imap_cmd *cmdp,
  556. void (*done)( imap_store_t *ctx, struct imap_cmd *cmd, int response ),
  557. const char *fmt, ... )
  558. {
  559. va_list ap;
  560. if (!cmdp)
  561. cmdp = new_imap_cmd( sizeof(*cmdp) );
  562. cmdp->param.done = done;
  563. va_start( ap, fmt );
  564. cmdp = v_submit_imap_cmd( ctx, cmdp, fmt, ap );
  565. va_end( ap );
  566. if (!cmdp)
  567. return RESP_CANCEL;
  568. return get_cmd_result( ctx, cmdp );
  569. }
  570. static void
  571. transform_box_response( int *response )
  572. {
  573. switch (*response) {
  574. case RESP_CANCEL: *response = DRV_CANCELED; break;
  575. case RESP_NO: *response = DRV_BOX_BAD; break;
  576. default: *response = DRV_OK; break;
  577. }
  578. }
  579. static void
  580. imap_done_simple_box( imap_store_t *ctx ATTR_UNUSED,
  581. struct imap_cmd *cmd, int response )
  582. {
  583. struct imap_cmd_simple *cmdp = (struct imap_cmd_simple *)cmd;
  584. transform_box_response( &response );
  585. cmdp->callback( response, cmdp->callback_aux );
  586. }
  587. static void
  588. transform_msg_response( int *response )
  589. {
  590. switch (*response) {
  591. case RESP_CANCEL: *response = DRV_CANCELED; break;
  592. case RESP_NO: *response = DRV_MSG_BAD; break;
  593. default: *response = DRV_OK; break;
  594. }
  595. }
  596. static void
  597. imap_done_simple_msg( imap_store_t *ctx ATTR_UNUSED,
  598. struct imap_cmd *cmd, int response )
  599. {
  600. struct imap_cmd_simple *cmdp = (struct imap_cmd_simple *)cmd;
  601. transform_msg_response( &response );
  602. cmdp->callback( response, cmdp->callback_aux );
  603. }
  604. static struct imap_cmd_refcounted_state *
  605. imap_refcounted_new_state( void (*cb)( int, void * ), void *aux )
  606. {
  607. struct imap_cmd_refcounted_state *sts = nfmalloc( sizeof(*sts) );
  608. sts->callback = cb;
  609. sts->callback_aux = aux;
  610. sts->ref_count = 1; /* so forced sync does not cause an early exit */
  611. sts->ret_val = DRV_OK;
  612. return sts;
  613. }
  614. static struct imap_cmd *
  615. imap_refcounted_new_cmd( struct imap_cmd_refcounted_state *sts )
  616. {
  617. struct imap_cmd_refcounted *cmd = (struct imap_cmd_refcounted *)new_imap_cmd( sizeof(*cmd) );
  618. cmd->state = sts;
  619. sts->ref_count++;
  620. return &cmd->gen;
  621. }
  622. static void
  623. imap_refcounted_done( struct imap_cmd_refcounted_state *sts )
  624. {
  625. sts->callback( sts->ret_val, sts->callback_aux );
  626. free( sts );
  627. }
  628. /*
  629. static void
  630. drain_imap_replies( imap_store_t *ctx )
  631. {
  632. while (ctx->num_in_progress)
  633. get_cmd_result( ctx, 0 );
  634. }
  635. */
  636. static int
  637. process_imap_replies( imap_store_t *ctx )
  638. {
  639. while (ctx->num_in_progress > max_in_progress ||
  640. socket_pending( &ctx->buf.sock ))
  641. if (get_cmd_result( ctx, 0 ) == RESP_CANCEL)
  642. return RESP_CANCEL;
  643. return RESP_OK;
  644. }
  645. static int
  646. is_atom( list_t *list )
  647. {
  648. return list && list->val && list->val != NIL && list->val != LIST;
  649. }
  650. static int
  651. is_list( list_t *list )
  652. {
  653. return list && list->val == LIST;
  654. }
  655. static void
  656. free_list( list_t *list )
  657. {
  658. list_t *tmp;
  659. for (; list; list = tmp) {
  660. tmp = list->next;
  661. if (is_list( list ))
  662. free_list( list->child );
  663. else if (is_atom( list ))
  664. free( list->val );
  665. free( list );
  666. }
  667. }
  668. static int
  669. parse_imap_list_l( imap_store_t *ctx, char **sp, list_t **curp, int level )
  670. {
  671. list_t *cur;
  672. char *s = *sp, *p;
  673. int n, bytes;
  674. for (;;) {
  675. while (isspace( (unsigned char)*s ))
  676. s++;
  677. if (level && *s == ')') {
  678. s++;
  679. break;
  680. }
  681. *curp = cur = nfmalloc( sizeof(*cur) );
  682. curp = &cur->next;
  683. cur->val = 0; /* for clean bail */
  684. if (*s == '(') {
  685. /* sublist */
  686. s++;
  687. cur->val = LIST;
  688. if (parse_imap_list_l( ctx, &s, &cur->child, level + 1 ))
  689. goto bail;
  690. } else if (ctx && *s == '{') {
  691. /* literal */
  692. bytes = cur->len = strtol( s + 1, &s, 10 );
  693. if (*s != '}')
  694. goto bail;
  695. s = cur->val = nfmalloc( cur->len );
  696. /* dump whats left over in the input buffer */
  697. n = ctx->buf.bytes - ctx->buf.offset;
  698. if (n > bytes)
  699. /* the entire message fit in the buffer */
  700. n = bytes;
  701. memcpy( s, ctx->buf.buf + ctx->buf.offset, n );
  702. s += n;
  703. bytes -= n;
  704. /* mark that we used part of the buffer */
  705. ctx->buf.offset += n;
  706. /* now read the rest of the message */
  707. while (bytes > 0) {
  708. if ((n = socket_read( &ctx->buf.sock, s, bytes )) <= 0)
  709. goto bail;
  710. s += n;
  711. bytes -= n;
  712. }
  713. if (DFlags & XVERBOSE) {
  714. puts( "=========" );
  715. fwrite( cur->val, cur->len, 1, stdout );
  716. puts( "=========" );
  717. }
  718. if (buffer_gets( &ctx->buf, &s ))
  719. goto bail;
  720. } else if (*s == '"') {
  721. /* quoted string */
  722. s++;
  723. p = s;
  724. for (; *s != '"'; s++)
  725. if (!*s)
  726. goto bail;
  727. cur->len = s - p;
  728. s++;
  729. cur->val = nfmalloc( cur->len + 1 );
  730. memcpy( cur->val, p, cur->len );
  731. cur->val[cur->len] = 0;
  732. } else {
  733. /* atom */
  734. p = s;
  735. for (; *s && !isspace( (unsigned char)*s ); s++)
  736. if (level && *s == ')')
  737. break;
  738. cur->len = s - p;
  739. if (cur->len == 3 && !memcmp ("NIL", p, 3))
  740. cur->val = NIL;
  741. else {
  742. cur->val = nfmalloc( cur->len + 1 );
  743. memcpy( cur->val, p, cur->len );
  744. cur->val[cur->len] = 0;
  745. }
  746. }
  747. if (!level)
  748. break;
  749. if (!*s)
  750. goto bail;
  751. }
  752. *sp = s;
  753. *curp = 0;
  754. return 0;
  755. bail:
  756. *curp = 0;
  757. return -1;
  758. }
  759. static list_t *
  760. parse_imap_list( imap_store_t *ctx, char **sp )
  761. {
  762. list_t *head;
  763. if (!parse_imap_list_l( ctx, sp, &head, 0 ))
  764. return head;
  765. free_list( head );
  766. return NULL;
  767. }
  768. static list_t *
  769. parse_list( char **sp )
  770. {
  771. return parse_imap_list( 0, sp );
  772. }
  773. static int
  774. parse_fetch( imap_store_t *ctx, char *cmd ) /* move this down */
  775. {
  776. list_t *tmp, *list, *flags;
  777. char *body = 0;
  778. imap_message_t *cur;
  779. msg_data_t *msgdata;
  780. struct imap_cmd *cmdp;
  781. int uid = 0, mask = 0, status = 0, size = 0;
  782. unsigned i;
  783. list = parse_imap_list( ctx, &cmd );
  784. if (!is_list( list )) {
  785. error( "IMAP error: bogus FETCH response\n" );
  786. free_list( list );
  787. return -1;
  788. }
  789. for (tmp = list->child; tmp; tmp = tmp->next) {
  790. if (is_atom( tmp )) {
  791. if (!strcmp( "UID", tmp->val )) {
  792. tmp = tmp->next;
  793. if (is_atom( tmp ))
  794. uid = atoi( tmp->val );
  795. else
  796. error( "IMAP error: unable to parse UID\n" );
  797. } else if (!strcmp( "FLAGS", tmp->val )) {
  798. tmp = tmp->next;
  799. if (is_list( tmp )) {
  800. for (flags = tmp->child; flags; flags = flags->next) {
  801. if (is_atom( flags )) {
  802. if (flags->val[0] == '\\') { /* ignore user-defined flags for now */
  803. if (!strcmp( "Recent", flags->val + 1)) {
  804. status |= M_RECENT;
  805. goto flagok;
  806. }
  807. for (i = 0; i < as(Flags); i++)
  808. if (!strcmp( Flags[i], flags->val + 1 )) {
  809. mask |= 1 << i;
  810. goto flagok;
  811. }
  812. if (flags->val[1] == 'X' && flags->val[2] == '-')
  813. goto flagok; /* ignore system flag extensions */
  814. error( "IMAP warning: unknown system flag %s\n", flags->val );
  815. }
  816. flagok: ;
  817. } else
  818. error( "IMAP error: unable to parse FLAGS list\n" );
  819. }
  820. status |= M_FLAGS;
  821. } else
  822. error( "IMAP error: unable to parse FLAGS\n" );
  823. } else if (!strcmp( "RFC822.SIZE", tmp->val )) {
  824. tmp = tmp->next;
  825. if (is_atom( tmp ))
  826. size = atoi( tmp->val );
  827. else
  828. error( "IMAP error: unable to parse RFC822.SIZE\n" );
  829. } else if (!strcmp( "BODY[]", tmp->val )) {
  830. tmp = tmp->next;
  831. if (is_atom( tmp )) {
  832. body = tmp->val;
  833. tmp->val = 0; /* don't free together with list */
  834. size = tmp->len;
  835. } else
  836. error( "IMAP error: unable to parse BODY[]\n" );
  837. }
  838. }
  839. }
  840. if (body) {
  841. for (cmdp = ctx->in_progress; cmdp; cmdp = cmdp->next)
  842. if (cmdp->param.uid == uid)
  843. goto gotuid;
  844. error( "IMAP error: unexpected FETCH response (UID %d)\n", uid );
  845. free_list( list );
  846. return -1;
  847. gotuid:
  848. msgdata = ((struct imap_cmd_fetch_msg *)cmdp)->msg_data;
  849. msgdata->data = body;
  850. msgdata->len = size;
  851. if (status & M_FLAGS)
  852. msgdata->flags = mask;
  853. } else if (uid) { /* ignore async flag updates for now */
  854. /* XXX this will need sorting for out-of-order (multiple queries) */
  855. cur = nfcalloc( sizeof(*cur) );
  856. *ctx->msgapp = &cur->gen;
  857. ctx->msgapp = &cur->gen.next;
  858. cur->gen.next = 0;
  859. cur->gen.uid = uid;
  860. cur->gen.flags = mask;
  861. cur->gen.status = status;
  862. cur->gen.size = size;
  863. }
  864. free_list( list );
  865. return 0;
  866. }
  867. static void
  868. parse_capability( imap_store_t *ctx, char *cmd )
  869. {
  870. char *arg;
  871. unsigned i;
  872. ctx->caps = 0x80000000;
  873. while ((arg = next_arg( &cmd )))
  874. for (i = 0; i < as(cap_list); i++)
  875. if (!strcmp( cap_list[i], arg ))
  876. ctx->caps |= 1 << i;
  877. }
  878. static int
  879. parse_response_code( imap_store_t *ctx, struct imap_cmd *cmd, char *s )
  880. {
  881. char *arg, *earg, *p;
  882. if (*s != '[')
  883. return RESP_OK; /* no response code */
  884. s++;
  885. if (!(p = strchr( s, ']' ))) {
  886. error( "IMAP error: malformed response code\n" );
  887. return RESP_CANCEL;
  888. }
  889. *p++ = 0;
  890. arg = next_arg( &s );
  891. if (!strcmp( "UIDVALIDITY", arg )) {
  892. if (!(arg = next_arg( &s )) ||
  893. (ctx->gen.uidvalidity = strtoll( arg, &earg, 10 ), *earg))
  894. {
  895. error( "IMAP error: malformed UIDVALIDITY status\n" );
  896. return RESP_CANCEL;
  897. }
  898. } else if (!strcmp( "UIDNEXT", arg )) {
  899. if (!(arg = next_arg( &s )) || (ctx->uidnext = strtol( arg, &p, 10 ), *p)) {
  900. error( "IMAP error: malformed NEXTUID status\n" );
  901. return RESP_CANCEL;
  902. }
  903. } else if (!strcmp( "CAPABILITY", arg )) {
  904. parse_capability( ctx, s );
  905. } else if (!strcmp( "ALERT", arg )) {
  906. /* RFC2060 says that these messages MUST be displayed
  907. * to the user
  908. */
  909. for (; isspace( (unsigned char)*p ); p++);
  910. error( "*** IMAP ALERT *** %s\n", p );
  911. } else if (cmd && !strcmp( "APPENDUID", arg )) {
  912. if (!(arg = next_arg( &s )) ||
  913. (ctx->gen.uidvalidity = strtoll( arg, &earg, 10 ), *earg) ||
  914. !(arg = next_arg( &s )) ||
  915. !(((struct imap_cmd_out_uid *)cmd)->out_uid = atoi( arg )))
  916. {
  917. error( "IMAP error: malformed APPENDUID status\n" );
  918. return RESP_CANCEL;
  919. }
  920. }
  921. return RESP_OK;
  922. }
  923. static void
  924. parse_search( imap_store_t *ctx, char *cmd )
  925. {
  926. char *arg;
  927. struct imap_cmd *cmdp;
  928. int uid;
  929. if (!(arg = next_arg( &cmd )))
  930. uid = -1;
  931. else if (!(uid = atoi( arg ))) {
  932. error( "IMAP error: malformed SEARCH response\n" );
  933. return;
  934. } else if (next_arg( &cmd )) {
  935. warn( "IMAP warning: SEARCH returns multiple matches\n" );
  936. uid = -1; /* to avoid havoc */
  937. }
  938. /* Find the first command that expects a UID - this is guaranteed
  939. * to come in-order, as there are no other means to identify which
  940. * SEARCH response belongs to which request.
  941. */
  942. for (cmdp = ctx->in_progress; cmdp; cmdp = cmdp->next)
  943. if (cmdp->param.uid == -1) {
  944. ((struct imap_cmd_out_uid *)cmdp)->out_uid = uid;
  945. return;
  946. }
  947. error( "IMAP error: unexpected SEARCH response (UID %u)\n", uid );
  948. }
  949. static void
  950. parse_list_rsp( imap_store_t *ctx, char *cmd )
  951. {
  952. char *arg;
  953. list_t *list, *lp;
  954. int l;
  955. list = parse_list( &cmd );
  956. if (list->val == LIST)
  957. for (lp = list->child; lp; lp = lp->next)
  958. if (is_atom( lp ) && !strcasecmp( lp->val, "\\NoSelect" )) {
  959. free_list( list );
  960. return;
  961. }
  962. free_list( list );
  963. (void) next_arg( &cmd ); /* skip delimiter */
  964. arg = next_arg( &cmd );
  965. l = strlen( ctx->gen.conf->path );
  966. if (memcmp( arg, ctx->gen.conf->path, l ))
  967. return;
  968. arg += l;
  969. if (!memcmp( arg + strlen( arg ) - 5, ".lock", 5 )) /* workaround broken servers */
  970. return;
  971. add_string_list( &ctx->gen.boxes, arg );
  972. }
  973. struct imap_cmd_trycreate {
  974. struct imap_cmd gen;
  975. struct imap_cmd *orig_cmd;
  976. };
  977. static void imap_open_store_greeted( imap_store_t * );
  978. static void get_cmd_result_p2( imap_store_t *, struct imap_cmd *, int );
  979. static int
  980. get_cmd_result( imap_store_t *ctx, struct imap_cmd *tcmd )
  981. {
  982. struct imap_cmd *cmdp, **pcmdp;
  983. char *cmd, *arg, *arg1, *p;
  984. int n, resp, resp2, tag, greeted;
  985. greeted = ctx->greeting;
  986. for (;;) {
  987. if (buffer_gets( &ctx->buf, &cmd ))
  988. break;
  989. arg = next_arg( &cmd );
  990. if (*arg == '*') {
  991. arg = next_arg( &cmd );
  992. if (!arg) {
  993. error( "IMAP error: unable to parse untagged response\n" );
  994. break;
  995. }
  996. if (!strcmp( "NAMESPACE", arg )) {
  997. ctx->ns_personal = parse_list( &cmd );
  998. ctx->ns_other = parse_list( &cmd );
  999. ctx->ns_shared = parse_list( &cmd );
  1000. } else if (ctx->greeting == GreetingPending && !strcmp( "PREAUTH", arg )) {
  1001. ctx->greeting = GreetingPreauth;
  1002. parse_response_code( ctx, 0, cmd );
  1003. } else if (!strcmp( "OK", arg )) {
  1004. ctx->greeting = GreetingOk;
  1005. parse_response_code( ctx, 0, cmd );
  1006. } else if (!strcmp( "BAD", arg ) || !strcmp( "NO", arg ) || !strcmp( "BYE", arg )) {
  1007. ctx->greeting = GreetingBad;
  1008. parse_response_code( ctx, 0, cmd );
  1009. } else if (!strcmp( "CAPABILITY", arg ))
  1010. parse_capability( ctx, cmd );
  1011. else if (!strcmp( "LIST", arg ))
  1012. parse_list_rsp( ctx, cmd );
  1013. else if (!strcmp( "SEARCH", arg ))
  1014. parse_search( ctx, cmd );
  1015. else if ((arg1 = next_arg( &cmd ))) {
  1016. if (!strcmp( "EXISTS", arg1 ))
  1017. ctx->gen.count = atoi( arg );
  1018. else if (!strcmp( "RECENT", arg1 ))
  1019. ctx->gen.recent = atoi( arg );
  1020. else if(!strcmp ( "FETCH", arg1 )) {
  1021. if (parse_fetch( ctx, cmd ))
  1022. break; /* stream is likely to be useless now */
  1023. }
  1024. } else {
  1025. error( "IMAP error: unrecognized untagged response '%s'\n", arg );
  1026. break; /* this may mean anything, so prefer not to spam the log */
  1027. }
  1028. if (greeted == GreetingPending) {
  1029. imap_ref( ctx );
  1030. imap_open_store_greeted( ctx );
  1031. return imap_deref( ctx ) ? RESP_CANCEL : RESP_OK;
  1032. }
  1033. } else if (!ctx->in_progress) {
  1034. error( "IMAP error: unexpected reply: %s %s\n", arg, cmd ? cmd : "" );
  1035. break; /* this may mean anything, so prefer not to spam the log */
  1036. } else if (*arg == '+') {
  1037. /* This can happen only with the last command underway, as
  1038. it enforces a round-trip. */
  1039. cmdp = ctx->in_progress;
  1040. if (cmdp->param.data) {
  1041. if (cmdp->param.to_trash)
  1042. ctx->trashnc = 0; /* Can't get NO [TRYCREATE] any more. */
  1043. n = socket_write( &ctx->buf.sock, cmdp->param.data, cmdp->param.data_len );
  1044. free( cmdp->param.data );
  1045. cmdp->param.data = 0;
  1046. if (n != (int)cmdp->param.data_len)
  1047. break;
  1048. } else if (cmdp->param.cont) {
  1049. if (cmdp->param.cont( ctx, cmdp, cmd ))
  1050. break;
  1051. } else {
  1052. error( "IMAP error: unexpected command continuation request\n" );
  1053. break;
  1054. }
  1055. if (socket_write( &ctx->buf.sock, "\r\n", 2 ) != 2)
  1056. break;
  1057. if (!cmdp->param.cont)
  1058. ctx->literal_pending = 0;
  1059. if (!tcmd)
  1060. return RESP_OK;
  1061. } else {
  1062. tag = atoi( arg );
  1063. for (pcmdp = &ctx->in_progress; (cmdp = *pcmdp); pcmdp = &cmdp->next)
  1064. if (cmdp->tag == tag)
  1065. goto gottag;
  1066. error( "IMAP error: unexpected tag %s\n", arg );
  1067. break;
  1068. gottag:
  1069. if (!(*pcmdp = cmdp->next))
  1070. ctx->in_progress_append = pcmdp;
  1071. ctx->num_in_progress--;
  1072. if (cmdp->param.cont || cmdp->param.data)
  1073. ctx->literal_pending = 0;
  1074. arg = next_arg( &cmd );
  1075. if (!strcmp( "OK", arg )) {
  1076. if (cmdp->param.to_trash)
  1077. ctx->trashnc = 0; /* Can't get NO [TRYCREATE] any more. */
  1078. resp = RESP_OK;
  1079. } else {
  1080. if (!strcmp( "NO", arg )) {
  1081. if (cmdp->param.create &&
  1082. (cmdp->param.trycreate ||
  1083. (cmd && !memcmp( cmd, "[TRYCREATE]", 11 ))))
  1084. { /* SELECT, APPEND or UID COPY */
  1085. struct imap_cmd_trycreate *cmd2 =
  1086. (struct imap_cmd_trycreate *)new_imap_cmd( sizeof(*cmd2) );
  1087. cmd2->orig_cmd = cmdp;
  1088. cmd2->gen.param.done = get_cmd_result_p2;
  1089. p = strchr( cmdp->cmd, '"' );
  1090. if (!submit_imap_cmd( ctx, &cmd2->gen, "CREATE %.*s", strchr( p + 1, '"' ) - p + 1, p ))
  1091. return RESP_CANCEL;
  1092. continue;
  1093. }
  1094. resp = RESP_NO;
  1095. } else /*if (!strcmp( "BAD", arg ))*/
  1096. resp = RESP_CANCEL;
  1097. error( "IMAP command '%s' returned an error: %s %s\n",
  1098. memcmp( cmdp->cmd, "LOGIN", 5 ) ? cmdp->cmd : "LOGIN <user> <pass>",
  1099. arg, cmd ? cmd : "" );
  1100. }
  1101. if ((resp2 = parse_response_code( ctx, cmdp, cmd )) > resp)
  1102. resp = resp2;
  1103. imap_ref( ctx );
  1104. if (resp == RESP_CANCEL)
  1105. imap_invoke_bad_callback( ctx );
  1106. cmdp->param.done( ctx, cmdp, resp );
  1107. if (imap_deref( ctx ))
  1108. resp = RESP_CANCEL;
  1109. free( cmdp->param.data );
  1110. free( cmdp->cmd );
  1111. free( cmdp );
  1112. if (resp == RESP_CANCEL || !tcmd || tcmd == cmdp)
  1113. return resp;
  1114. }
  1115. }
  1116. imap_invoke_bad_callback( ctx );
  1117. return RESP_CANCEL;
  1118. }
  1119. static void
  1120. get_cmd_result_p2( imap_store_t *ctx, struct imap_cmd *cmd, int response )
  1121. {
  1122. struct imap_cmd_trycreate *cmdp = (struct imap_cmd_trycreate *)cmd;
  1123. struct imap_cmd *ocmd = cmdp->orig_cmd;
  1124. if (response != RESP_OK) {
  1125. ocmd->param.done( ctx, ocmd, response );
  1126. free( ocmd->param.data );
  1127. free( ocmd->cmd );
  1128. free( ocmd );
  1129. } else {
  1130. ctx->uidnext = 0;
  1131. ocmd->param.create = 0;
  1132. submit_imap_cmd( ctx, ocmd, 0 );
  1133. }
  1134. }
  1135. /******************* imap_cancel_store *******************/
  1136. static void
  1137. imap_cancel_store( store_t *gctx )
  1138. {
  1139. imap_store_t *ctx = (imap_store_t *)gctx;
  1140. free_generic_messages( ctx->gen.msgs );
  1141. free_string_list( ctx->gen.boxes );
  1142. if (ctx->buf.sock.fd >= 0)
  1143. close( ctx->buf.sock.fd );
  1144. #ifdef HAVE_LIBSSL
  1145. if (ctx->buf.sock.ssl)
  1146. SSL_free( ctx->buf.sock.ssl );
  1147. if (ctx->SSLContext)
  1148. SSL_CTX_free( ctx->SSLContext );
  1149. #endif
  1150. free_list( ctx->ns_personal );
  1151. free_list( ctx->ns_other );
  1152. free_list( ctx->ns_shared );
  1153. imap_deref( ctx );
  1154. }
  1155. static int
  1156. imap_deref( imap_store_t *ctx )
  1157. {
  1158. if (!--ctx->ref_count) {
  1159. free( ctx );
  1160. return -1;
  1161. }
  1162. return 0;
  1163. }
  1164. static void
  1165. imap_invoke_bad_callback( imap_store_t *ctx )
  1166. {
  1167. ctx->gen.bad_callback( ctx->gen.bad_callback_aux );
  1168. }
  1169. /******************* imap_disown_store & imap_own_store *******************/
  1170. static store_t *unowned;
  1171. static void
  1172. imap_cancel_unowned( void *gctx )
  1173. {
  1174. store_t *store, **storep;
  1175. for (storep = &unowned; (store = *storep); storep = &store->next)
  1176. if (store == gctx) {
  1177. *storep = store->next;
  1178. break;
  1179. }
  1180. imap_cancel_store( gctx );
  1181. }
  1182. static void
  1183. imap_disown_store( store_t *gctx )
  1184. {
  1185. free_generic_messages( gctx->msgs );
  1186. gctx->msgs = 0;
  1187. set_bad_callback( gctx, imap_cancel_unowned, gctx );
  1188. gctx->next = unowned;
  1189. unowned = gctx;
  1190. }
  1191. static store_t *
  1192. imap_own_store( store_conf_t *conf )
  1193. {
  1194. store_t *store, **storep;
  1195. for (storep = &unowned; (store = *storep); storep = &store->next)
  1196. if (store->conf == conf) {
  1197. *storep = store->next;
  1198. return store;
  1199. }
  1200. return 0;
  1201. }
  1202. /******************* imap_cleanup *******************/
  1203. static void imap_cleanup_p2( imap_store_t *, struct imap_cmd *, int );
  1204. static void
  1205. imap_cleanup( void )
  1206. {
  1207. store_t *ctx, *nctx;
  1208. for (ctx = unowned; ctx; ctx = nctx) {
  1209. nctx = ctx->next;
  1210. set_bad_callback( ctx, (void (*)(void *))imap_cancel_store, ctx );
  1211. imap_exec( (imap_store_t *)ctx, 0, imap_cleanup_p2, "LOGOUT" );
  1212. }
  1213. }
  1214. static void
  1215. imap_cleanup_p2( imap_store_t *ctx,
  1216. struct imap_cmd *cmd ATTR_UNUSED, int response )
  1217. {
  1218. if (response != RESP_CANCEL)
  1219. imap_cancel_store( &ctx->gen );
  1220. }
  1221. /******************* imap_open_store *******************/
  1222. #ifdef HAVE_LIBSSL
  1223. static int
  1224. start_tls( imap_store_t *ctx )
  1225. {
  1226. int ret;
  1227. static int ssl_inited;
  1228. if (!ssl_inited) {
  1229. SSL_library_init();
  1230. SSL_load_error_strings();
  1231. ssl_inited = 1;
  1232. }
  1233. if (init_ssl_ctx( ctx ))
  1234. return 1;
  1235. ctx->buf.sock.ssl = SSL_new( ctx->SSLContext );
  1236. SSL_set_fd( ctx->buf.sock.ssl, ctx->buf.sock.fd );
  1237. if ((ret = SSL_connect( ctx->buf.sock.ssl )) <= 0) {
  1238. socket_perror( "connect", &ctx->buf.sock, ret );
  1239. return 1;
  1240. }
  1241. /* verify the server certificate */
  1242. if (verify_cert( ctx ))
  1243. return 1;
  1244. info( "Connection is now encrypted\n" );
  1245. return 0;
  1246. }
  1247. #define ENCODED_SIZE(n) (4*((n+2)/3))
  1248. static char
  1249. hexchar( unsigned int b )
  1250. {
  1251. if (b < 10)
  1252. return '0' + b;
  1253. return 'a' + (b - 10);
  1254. }
  1255. static void
  1256. cram( const char *challenge, const char *user, const char *pass, char **_final, int *_finallen )
  1257. {
  1258. unsigned char *response, *final;
  1259. unsigned hashlen;
  1260. int i, clen, rlen, blen, flen, olen;
  1261. unsigned char hash[16];
  1262. char buf[256], hex[33];
  1263. HMAC_CTX hmac;
  1264. HMAC_Init( &hmac, (unsigned char *)pass, strlen( pass ), EVP_md5() );
  1265. clen = strlen( challenge );
  1266. /* response will always be smaller than challenge because we are decoding. */
  1267. response = nfcalloc( 1 + clen );
  1268. rlen = EVP_DecodeBlock( response, (unsigned char *)challenge, clen );
  1269. HMAC_Update( &hmac, response, rlen );
  1270. free( response );
  1271. hashlen = sizeof(hash);
  1272. HMAC_Final( &hmac, hash, &hashlen );
  1273. assert( hashlen == sizeof(hash) );
  1274. hex[32] = 0;
  1275. for (i = 0; i < 16; i++) {
  1276. hex[2 * i] = hexchar( (hash[i] >> 4) & 0xf );
  1277. hex[2 * i + 1] = hexchar( hash[i] & 0xf );
  1278. }
  1279. blen = nfsnprintf( buf, sizeof(buf), "%s %s", user, hex );
  1280. flen = ENCODED_SIZE( blen );
  1281. final = nfmalloc( flen + 1 );
  1282. final[flen] = 0;
  1283. olen = EVP_EncodeBlock( (unsigned char *)final, (unsigned char *)buf, blen );
  1284. assert( olen == flen );
  1285. *_final = (char *)final;
  1286. *_finallen = flen;
  1287. }
  1288. static int
  1289. do_cram_auth( imap_store_t *ctx, struct imap_cmd *cmdp, const char *prompt )
  1290. {
  1291. imap_server_conf_t *srvc = ((imap_store_conf_t *)ctx->gen.conf)->server;
  1292. char *resp;
  1293. int n, l;
  1294. cram( prompt, srvc->user, srvc->pass, &resp, &l );
  1295. if (DFlags & VERBOSE)
  1296. printf( ">+> %s\n", resp );
  1297. n = socket_write( &ctx->buf.sock, resp, l );
  1298. free( resp );
  1299. if (n != l)
  1300. return -1;
  1301. cmdp->param.cont = 0;
  1302. return 0;
  1303. }
  1304. #endif
  1305. static void imap_open_store_p2( imap_store_t *, struct imap_cmd *, int );
  1306. static void imap_open_store_authenticate( imap_store_t * );
  1307. #ifdef HAVE_LIBSSL
  1308. static void imap_open_store_authenticate_p2( imap_store_t *, struct imap_cmd *, int );
  1309. static void imap_open_store_authenticate_p3( imap_store_t *, struct imap_cmd *, int );
  1310. #endif
  1311. static void imap_open_store_authenticate2( imap_store_t * );
  1312. static void imap_open_store_authenticate2_p2( imap_store_t *, struct imap_cmd *, int );
  1313. static void imap_open_store_namespace( imap_store_t * );
  1314. static void imap_open_store_namespace_p2( imap_store_t *, struct imap_cmd *, int );
  1315. static void imap_open_store_namespace2( imap_store_t * );
  1316. static void imap_open_store_finalize( imap_store_t * );
  1317. #ifdef HAVE_LIBSSL
  1318. static void imap_open_store_ssl_bail( imap_store_t * );
  1319. #endif
  1320. static void imap_open_store_bail( imap_store_t * );
  1321. static void
  1322. imap_open_store( store_conf_t *conf,
  1323. void (*cb)( store_t *srv, void *aux ), void *aux )
  1324. {
  1325. imap_store_conf_t *cfg = (imap_store_conf_t *)conf;
  1326. imap_server_conf_t *srvc = cfg->server;
  1327. imap_store_t *ctx;
  1328. store_t **ctxp;
  1329. struct hostent *he;
  1330. struct sockaddr_in addr;
  1331. int s, a[2];
  1332. for (ctxp = &unowned; (ctx = (imap_store_t *)*ctxp); ctxp = &ctx->gen.next)
  1333. if (((imap_store_conf_t *)ctx->gen.conf)->server == srvc) {
  1334. *ctxp = ctx->gen.next;
  1335. /* One could ping the server here, but given that the idle timeout
  1336. * is at least 30 minutes, this sounds pretty pointless. */
  1337. free_string_list( ctx->gen.boxes );
  1338. ctx->gen.boxes = 0;
  1339. ctx->gen.listed = 0;
  1340. ctx->gen.conf = conf;
  1341. ctx->callbacks.imap_open = cb;
  1342. ctx->callback_aux = aux;
  1343. set_bad_callback( &ctx->gen, (void (*)(void *))imap_open_store_bail, ctx );
  1344. imap_open_store_namespace( ctx );
  1345. return;
  1346. }
  1347. ctx = nfcalloc( sizeof(*ctx) );
  1348. ctx->gen.conf = conf;
  1349. ctx->buf.sock.fd = -1;
  1350. ctx->ref_count = 1;
  1351. ctx->callbacks.imap_open = cb;
  1352. ctx->callback_aux = aux;
  1353. set_bad_callback( &ctx->gen, (void (*)(void *))imap_open_store_bail, ctx );
  1354. ctx->in_progress_append = &ctx->in_progress;
  1355. /* open connection to IMAP server */
  1356. if (srvc->tunnel) {
  1357. infon( "Starting tunnel '%s'... ", srvc->tunnel );
  1358. if (socketpair( PF_UNIX, SOCK_STREAM, 0, a )) {
  1359. perror( "socketpair" );
  1360. exit( 1 );
  1361. }
  1362. if (fork() == 0) {
  1363. if (dup2( a[0], 0 ) == -1 || dup2( a[0], 1 ) == -1)
  1364. _exit( 127 );
  1365. close( a[0] );
  1366. close( a[1] );
  1367. execl( "/bin/sh", "sh", "-c", srvc->tunnel, (char *)0 );
  1368. _exit( 127 );
  1369. }
  1370. close (a[0]);
  1371. ctx->buf.sock.fd = a[1];
  1372. info( "ok\n" );
  1373. } else {
  1374. memset( &addr, 0, sizeof(addr) );
  1375. addr.sin_port = srvc->port ? htons( srvc->port ) :
  1376. #ifdef HAVE_LIBSSL
  1377. srvc->use_imaps ? htons( 993 ) :
  1378. #endif
  1379. htons( 143 );
  1380. addr.sin_family = AF_INET;
  1381. infon( "Resolving %s... ", srvc->host );
  1382. he = gethostbyname( srvc->host );
  1383. if (!he) {
  1384. error( "IMAP error: Cannot resolve server '%s'\n", srvc->host );
  1385. goto bail;
  1386. }
  1387. info( "ok\n" );
  1388. addr.sin_addr.s_addr = *((int *) he->h_addr_list[0]);
  1389. s = socket( PF_INET, SOCK_STREAM, 0 );
  1390. if (s < 0) {
  1391. perror( "socket" );
  1392. exit( 1 );
  1393. }
  1394. infon( "Connecting to %s:%hu... ", inet_ntoa( addr.sin_addr ), ntohs( addr.sin_port ) );
  1395. if (connect( s, (struct sockaddr *)&addr, sizeof(addr) )) {
  1396. close( s );
  1397. perror( "connect" );
  1398. goto bail;
  1399. }
  1400. info( "ok\n" );
  1401. ctx->buf.sock.fd = s;
  1402. }
  1403. #ifdef HAVE_LIBSSL
  1404. if (srvc->use_imaps) {
  1405. if (start_tls( ctx )) {
  1406. imap_open_store_ssl_bail( ctx );
  1407. return;
  1408. }
  1409. }
  1410. #endif
  1411. get_cmd_result( ctx, 0 );
  1412. return;
  1413. bail:
  1414. imap_open_store_bail( ctx );
  1415. }
  1416. static void
  1417. imap_open_store_greeted( imap_store_t *ctx )
  1418. {
  1419. if (ctx->greeting == GreetingBad) {
  1420. error( "IMAP error: unknown greeting response\n" );
  1421. imap_open_store_bail( ctx );
  1422. return;
  1423. }
  1424. if (!ctx->caps)
  1425. imap_exec( ctx, 0, imap_open_store_p2, "CAPABILITY" );
  1426. else
  1427. imap_open_store_authenticate( ctx );
  1428. }
  1429. static void
  1430. imap_open_store_p2( imap_store_t *ctx, struct imap_cmd *cmd ATTR_UNUSED, int response )
  1431. {
  1432. if (response != RESP_OK)
  1433. imap_open_store_bail( ctx );
  1434. else
  1435. imap_open_store_authenticate( ctx );
  1436. }
  1437. static void
  1438. imap_open_store_authenticate( imap_store_t *ctx )
  1439. {
  1440. if (ctx->greeting != GreetingPreauth) {
  1441. #ifdef HAVE_LIBSSL
  1442. imap_store_conf_t *cfg = (imap_store_conf_t *)ctx->gen.conf;
  1443. imap_server_conf_t *srvc = cfg->server;
  1444. if (!srvc->use_imaps && (srvc->use_sslv2 || srvc->use_sslv3 || srvc->use_tlsv1)) {
  1445. /* always try to select SSL support if available */
  1446. if (CAP(STARTTLS)) {
  1447. imap_exec( ctx, 0, imap_open_store_authenticate_p2, "STARTTLS" );
  1448. return;
  1449. } else {
  1450. if (srvc->require_ssl) {
  1451. error( "IMAP error: SSL support not available\n" );
  1452. imap_open_store_bail( ctx );
  1453. return;
  1454. } else {
  1455. warn( "IMAP warning: SSL support not available\n" );
  1456. }
  1457. }
  1458. }
  1459. #endif
  1460. imap_open_store_authenticate2( ctx );
  1461. } else {
  1462. imap_open_store_namespace( ctx );
  1463. }
  1464. }
  1465. #ifdef HAVE_LIBSSL
  1466. static void
  1467. imap_open_store_authenticate_p2( imap_store_t *ctx, struct imap_cmd *cmd ATTR_UNUSED, int response )
  1468. {
  1469. if (response != RESP_OK)
  1470. imap_open_store_bail( ctx );
  1471. else if (start_tls( ctx ))
  1472. imap_open_store_ssl_bail( ctx );
  1473. else
  1474. imap_exec( ctx, 0, imap_open_store_authenticate_p3, "CAPABILITY" );
  1475. }
  1476. static void
  1477. imap_open_store_authenticate_p3( imap_store_t *ctx, struct imap_cmd *cmd ATTR_UNUSED, int response )
  1478. {
  1479. if (response != RESP_OK)
  1480. imap_open_store_bail( ctx );
  1481. else
  1482. imap_open_store_authenticate2( ctx );
  1483. }
  1484. #endif
  1485. static void
  1486. imap_open_store_authenticate2( imap_store_t *ctx )
  1487. {
  1488. imap_store_conf_t *cfg = (imap_store_conf_t *)ctx->gen.conf;
  1489. imap_server_conf_t *srvc = cfg->server;
  1490. char *arg;
  1491. info ("Logging in...\n");
  1492. if (!srvc->user) {
  1493. error( "Skipping account %s, no user\n", srvc->name );
  1494. goto bail;
  1495. }
  1496. if (!srvc->pass) {
  1497. char prompt[80];
  1498. sprintf( prompt, "Password (%s): ", srvc->name );
  1499. arg = getpass( prompt );
  1500. if (!arg) {
  1501. perror( "getpass" );
  1502. exit( 1 );
  1503. }
  1504. if (!*arg) {
  1505. error( "Skipping account %s, no password\n", srvc->name );
  1506. goto bail;
  1507. }
  1508. /*
  1509. * getpass() returns a pointer to a static buffer. make a copy
  1510. * for long term storage.
  1511. */
  1512. srvc->pass = nfstrdup( arg );
  1513. }
  1514. #ifdef HAVE_LIBSSL
  1515. if (CAP(CRAM)) {
  1516. struct imap_cmd *cmd = new_imap_cmd( sizeof(*cmd) );
  1517. info( "Authenticating with CRAM-MD5\n" );
  1518. cmd->param.cont = do_cram_auth;
  1519. imap_exec( ctx, cmd, imap_open_store_authenticate2_p2, "AUTHENTICATE CRAM-MD5" );
  1520. return;
  1521. }
  1522. if (srvc->require_cram) {
  1523. error( "IMAP error: CRAM-MD5 authentication is not supported by server\n" );
  1524. goto bail;
  1525. }
  1526. #endif
  1527. if (CAP(NOLOGIN)) {
  1528. error( "Skipping account %s, server forbids LOGIN\n", srvc->name );
  1529. goto bail;
  1530. }
  1531. #ifdef HAVE_LIBSSL
  1532. if (!ctx->buf.sock.ssl)
  1533. #endif
  1534. warn( "*** IMAP Warning *** Password is being sent in the clear\n" );
  1535. imap_exec( ctx, 0, imap_open_store_authenticate2_p2,
  1536. "LOGIN \"%s\" \"%s\"", srvc->user, srvc->pass );
  1537. return;
  1538. bail:
  1539. imap_open_store_bail( ctx );
  1540. }
  1541. static void
  1542. imap_open_store_authenticate2_p2( imap_store_t *ctx, struct imap_cmd *cmd ATTR_UNUSED, int response )
  1543. {
  1544. if (response != RESP_OK)
  1545. imap_open_store_bail( ctx );
  1546. else
  1547. imap_open_store_namespace( ctx );
  1548. }
  1549. static void
  1550. imap_open_store_namespace( imap_store_t *ctx )
  1551. {
  1552. imap_store_conf_t *cfg = (imap_store_conf_t *)ctx->gen.conf;
  1553. ctx->prefix = "";
  1554. if (*cfg->gen.path)
  1555. ctx->prefix = cfg->gen.path;
  1556. else if (cfg->use_namespace && CAP(NAMESPACE)) {
  1557. /* get NAMESPACE info */
  1558. if (!ctx->got_namespace)
  1559. imap_exec( ctx, 0, imap_open_store_namespace_p2, "NAMESPACE" );
  1560. else
  1561. imap_open_store_namespace2( ctx );
  1562. return;
  1563. }
  1564. imap_open_store_finalize( ctx );
  1565. }
  1566. static void
  1567. imap_open_store_namespace_p2( imap_store_t *ctx, struct imap_cmd *cmd ATTR_UNUSED, int response )
  1568. {
  1569. if (response != RESP_OK) {
  1570. imap_open_store_bail( ctx );
  1571. } else {
  1572. ctx->got_namespace = 1;
  1573. imap_open_store_namespace2( ctx );
  1574. }
  1575. }
  1576. static void
  1577. imap_open_store_namespace2( imap_store_t *ctx )
  1578. {
  1579. /* XXX for now assume personal namespace */
  1580. if (is_list( ctx->ns_personal ) &&
  1581. is_list( ctx->ns_personal->child ) &&
  1582. is_atom( ctx->ns_personal->child->child ))
  1583. ctx->prefix = ctx->ns_personal->child->child->val;
  1584. imap_open_store_finalize( ctx );
  1585. }
  1586. static void
  1587. imap_open_store_finalize( imap_store_t *ctx )
  1588. {
  1589. set_bad_callback( &ctx->gen, 0, 0 );
  1590. ctx->trashnc = 1;
  1591. ctx->callbacks.imap_open( &ctx->gen, ctx->callback_aux );
  1592. }
  1593. #ifdef HAVE_LIBSSL
  1594. static void
  1595. imap_open_store_ssl_bail( imap_store_t *ctx )
  1596. {
  1597. /* This avoids that we try to send LOGOUT to an unusable socket. */
  1598. close( ctx->buf.sock.fd );
  1599. ctx->buf.sock.fd = -1;
  1600. imap_open_store_bail( ctx );
  1601. }
  1602. #endif
  1603. static void
  1604. imap_open_store_bail( imap_store_t *ctx )
  1605. {
  1606. void (*cb)( store_t *srv, void *aux ) = ctx->callbacks.imap_open;
  1607. void *aux = ctx->callback_aux;
  1608. imap_cancel_store( &ctx->gen );
  1609. cb( 0, aux );
  1610. }
  1611. /******************* imap_prepare_opts *******************/
  1612. static void
  1613. imap_prepare_opts( store_t *gctx, int opts )
  1614. {
  1615. gctx->opts = opts;
  1616. }
  1617. /******************* imap_select *******************/
  1618. static void
  1619. imap_select( store_t *gctx, int create,
  1620. void (*cb)( int sts, void *aux ), void *aux )
  1621. {
  1622. imap_store_t *ctx = (imap_store_t *)gctx;
  1623. struct imap_cmd_simple *cmd;
  1624. const char *prefix;
  1625. free_generic_messages( gctx->msgs );
  1626. gctx->msgs = 0;
  1627. if (!strcmp( gctx->name, "INBOX" )) {
  1628. prefix = "";
  1629. } else {
  1630. prefix = ctx->prefix;
  1631. }
  1632. ctx->uidnext = -1;
  1633. INIT_IMAP_CMD(imap_cmd_simple, cmd, cb, aux)
  1634. cmd->gen.param.create = create;
  1635. cmd->gen.param.trycreate = 1;
  1636. imap_exec( ctx, &cmd->gen, imap_done_simple_box,
  1637. "SELECT \"%s%s\"", prefix, gctx->name );
  1638. }
  1639. /******************* imap_load *******************/
  1640. static int imap_submit_load( imap_store_t *, const char *, struct imap_cmd_refcounted_state *,
  1641. struct imap_cmd ** );
  1642. static void imap_load_p2( imap_store_t *, struct imap_cmd *, int );
  1643. static void
  1644. imap_load( store_t *gctx, int minuid, int maxuid, int *excs, int nexcs,
  1645. void (*cb)( int sts, void *aux ), void *aux )
  1646. {
  1647. imap_store_t *ctx = (imap_store_t *)gctx;
  1648. int i, j, bl;
  1649. char buf[1000];
  1650. if (!ctx->gen.count) {
  1651. free( excs );
  1652. cb( DRV_OK, aux );
  1653. } else {
  1654. struct imap_cmd *cmd2 = 0;
  1655. struct imap_cmd_refcounted_state *sts = imap_refcounted_new_state( cb, aux );
  1656. ctx->msgapp = &ctx->gen.msgs;
  1657. sort_ints( excs, nexcs );
  1658. for (i = 0; i < nexcs; ) {
  1659. for (bl = 0; i < nexcs && bl < 960; i++) {
  1660. if (bl)
  1661. buf[bl++] = ',';
  1662. bl += sprintf( buf + bl, "%d", excs[i] );
  1663. j = i;
  1664. for (; i + 1 < nexcs && excs[i + 1] == excs[i] + 1; i++) {}
  1665. if (i != j)
  1666. bl += sprintf( buf + bl, ":%d", excs[i] );
  1667. }
  1668. if (imap_submit_load( ctx, buf, sts, &cmd2 ) < 0)
  1669. goto done;
  1670. }
  1671. if (maxuid == INT_MAX)
  1672. maxuid = ctx->uidnext >= 0 ? ctx->uidnext - 1 : 1000000000;
  1673. if (maxuid >= minuid) {
  1674. sprintf( buf, "%d:%d", minuid, maxuid );
  1675. imap_submit_load( ctx, buf, sts, &cmd2 );
  1676. }
  1677. done:
  1678. free( excs );
  1679. if (!--sts->ref_count)
  1680. imap_refcounted_done( sts );
  1681. else
  1682. get_cmd_result( ctx, cmd2 );
  1683. }
  1684. }
  1685. static int
  1686. imap_submit_load( imap_store_t *ctx, const char *buf, struct imap_cmd_refcounted_state *sts,
  1687. struct imap_cmd **cmdp )
  1688. {
  1689. struct imap_cmd *cmd = imap_refcounted_new_cmd( sts );
  1690. cmd->param.done = imap_load_p2;
  1691. *cmdp = cmd;
  1692. return submit_imap_cmd( ctx, cmd,
  1693. "UID FETCH %s (UID%s%s)", buf,
  1694. (ctx->gen.opts & OPEN_FLAGS) ? " FLAGS" : "",
  1695. (ctx->gen.opts & OPEN_SIZE) ? " RFC822.SIZE" : "" ) ? 0 : -1;
  1696. }
  1697. static void
  1698. imap_load_p2( imap_store_t *ctx ATTR_UNUSED, struct imap_cmd *cmd, int response )
  1699. {
  1700. struct imap_cmd_refcounted_state *sts = ((struct imap_cmd_refcounted *)cmd)->state;
  1701. switch (response) {
  1702. case RESP_CANCEL:
  1703. sts->ret_val = DRV_CANCELED;
  1704. break;
  1705. case RESP_NO:
  1706. if (sts->ret_val == DRV_OK) /* Don't override cancelation. */
  1707. sts->ret_val = DRV_BOX_BAD;
  1708. break;
  1709. }
  1710. if (!--sts->ref_count)
  1711. imap_refcounted_done( sts );
  1712. }
  1713. /******************* imap_fetch_msg *******************/
  1714. static void
  1715. imap_fetch_msg( store_t *ctx, message_t *msg, msg_data_t *data,
  1716. void (*cb)( int sts, void *aux ), void *aux )
  1717. {
  1718. struct imap_cmd_fetch_msg *cmd;
  1719. INIT_IMAP_CMD_X(imap_cmd_fetch_msg, cmd, cb, aux)
  1720. cmd->gen.gen.param.uid = msg->uid;
  1721. cmd->msg_data = data;
  1722. imap_exec( (imap_store_t *)ctx, &cmd->gen.gen, imap_done_simple_msg,
  1723. "UID FETCH %d (%sBODY.PEEK[])",
  1724. msg->uid, (msg->status & M_FLAGS) ? "" : "FLAGS " );
  1725. }
  1726. /******************* imap_set_flags *******************/
  1727. static void imap_set_flags_p2( imap_store_t *, struct imap_cmd *, int );
  1728. static int
  1729. imap_make_flags( int flags, char *buf )
  1730. {
  1731. const char *s;
  1732. unsigned i, d;
  1733. for (i = d = 0; i < as(Flags); i++)
  1734. if (flags & (1 << i)) {
  1735. buf[d++] = ' ';
  1736. buf[d++] = '\\';
  1737. for (s = Flags[i]; *s; s++)
  1738. buf[d++] = *s;
  1739. }
  1740. buf[0] = '(';
  1741. buf[d++] = ')';
  1742. return d;
  1743. }
  1744. static int
  1745. imap_flags_helper( imap_store_t *ctx, int uid, char what, int flags,
  1746. struct imap_cmd_refcounted_state *sts )
  1747. {
  1748. char buf[256];
  1749. struct imap_cmd *cmd = imap_refcounted_new_cmd( sts );
  1750. cmd->param.done = imap_set_flags_p2;
  1751. buf[imap_make_flags( flags, buf )] = 0;
  1752. if (!submit_imap_cmd( ctx, cmd, "UID STORE %d %cFLAGS.SILENT %s", uid, what, buf ))
  1753. return -1;
  1754. return process_imap_replies( ctx ) == RESP_CANCEL ? -1 : 0;
  1755. }
  1756. static void
  1757. imap_set_flags( store_t *gctx, message_t *msg, int uid, int add, int del,
  1758. void (*cb)( int sts, void *aux ), void *aux )
  1759. {
  1760. imap_store_t *ctx = (imap_store_t *)gctx;
  1761. if (msg) {
  1762. uid = msg->uid;
  1763. add &= ~msg->flags;
  1764. del &= msg->flags;
  1765. msg->flags |= add;
  1766. msg->flags &= ~del;
  1767. }
  1768. if (add || del) {
  1769. struct imap_cmd_refcounted_state *sts = imap_refcounted_new_state( cb, aux );
  1770. if ((add && imap_flags_helper( ctx, uid, '+', add, sts ) < 0) ||
  1771. (del && imap_flags_helper( ctx, uid, '-', del, sts ) < 0)) {}
  1772. if (!--sts->ref_count)
  1773. imap_refcounted_done( sts );
  1774. } else {
  1775. cb( DRV_OK, aux );
  1776. }
  1777. }
  1778. static void
  1779. imap_set_flags_p2( imap_store_t *ctx ATTR_UNUSED, struct imap_cmd *cmd, int response )
  1780. {
  1781. struct imap_cmd_refcounted_state *sts = ((struct imap_cmd_refcounted *)cmd)->state;
  1782. switch (response) {
  1783. case RESP_CANCEL:
  1784. sts->ret_val = DRV_CANCELED;
  1785. break;
  1786. case RESP_NO:
  1787. if (sts->ret_val == DRV_OK) /* Don't override cancelation. */
  1788. sts->ret_val = DRV_MSG_BAD;
  1789. break;
  1790. }
  1791. if (!--sts->ref_count)
  1792. imap_refcounted_done( sts );
  1793. }
  1794. /******************* imap_close *******************/
  1795. static void
  1796. imap_close( store_t *ctx,
  1797. void (*cb)( int sts, void *aux ), void *aux )
  1798. {
  1799. struct imap_cmd_simple *cmd;
  1800. INIT_IMAP_CMD(imap_cmd_simple, cmd, cb, aux)
  1801. imap_exec( (imap_store_t *)ctx, &cmd->gen, imap_done_simple_box, "CLOSE" );
  1802. }
  1803. /******************* imap_trash_msg *******************/
  1804. static void
  1805. imap_trash_msg( store_t *gctx, message_t *msg,
  1806. void (*cb)( int sts, void *aux ), void *aux )
  1807. {
  1808. imap_store_t *ctx = (imap_store_t *)gctx;
  1809. struct imap_cmd_simple *cmd;
  1810. INIT_IMAP_CMD(imap_cmd_simple, cmd, cb, aux)
  1811. cmd->gen.param.create = 1;
  1812. cmd->gen.param.to_trash = 1;
  1813. imap_exec( ctx, &cmd->gen, imap_done_simple_msg,
  1814. "UID COPY %d \"%s%s\"",
  1815. msg->uid, ctx->prefix, gctx->conf->trash );
  1816. }
  1817. /******************* imap_store_msg *******************/
  1818. static void imap_store_msg_p2( imap_store_t *, struct imap_cmd *, int );
  1819. static void
  1820. imap_store_msg( store_t *gctx, msg_data_t *data, int to_trash,
  1821. void (*cb)( int sts, int uid, void *aux ), void *aux )
  1822. {
  1823. imap_store_t *ctx = (imap_store_t *)gctx;
  1824. struct imap_cmd_out_uid *cmd;
  1825. const char *prefix, *box;
  1826. int d;
  1827. char flagstr[128];
  1828. d = 0;
  1829. if (data->flags) {
  1830. d = imap_make_flags( data->flags, flagstr );
  1831. flagstr[d++] = ' ';
  1832. }
  1833. flagstr[d] = 0;
  1834. INIT_IMAP_CMD(imap_cmd_out_uid, cmd, cb, aux)
  1835. cmd->gen.param.data_len = data->len;
  1836. cmd->gen.param.data = data->data;
  1837. cmd->out_uid = -2;
  1838. if (to_trash) {
  1839. box = gctx->conf->trash;
  1840. prefix = ctx->prefix;
  1841. cmd->gen.param.create = 1;
  1842. cmd->gen.param.to_trash = 1;
  1843. } else {
  1844. box = gctx->name;
  1845. prefix = !strcmp( box, "INBOX" ) ? "" : ctx->prefix;
  1846. }
  1847. imap_exec( ctx, &cmd->gen, imap_store_msg_p2,
  1848. "APPEND \"%s%s\" %s", prefix, box, flagstr );
  1849. }
  1850. static void
  1851. imap_store_msg_p2( imap_store_t *ctx ATTR_UNUSED, struct imap_cmd *cmd, int response )
  1852. {
  1853. struct imap_cmd_out_uid *cmdp = (struct imap_cmd_out_uid *)cmd;
  1854. transform_msg_response( &response );
  1855. cmdp->callback( response, cmdp->out_uid, cmdp->callback_aux );
  1856. }
  1857. /******************* imap_find_msg *******************/
  1858. static void imap_find_msg_p2( imap_store_t *, struct imap_cmd *, int );
  1859. static void
  1860. imap_find_msg( store_t *gctx, const char *tuid,
  1861. void (*cb)( int sts, int uid, void *aux ), void *aux )
  1862. {
  1863. imap_store_t *ctx = (imap_store_t *)gctx;
  1864. struct imap_cmd_out_uid *cmd;
  1865. INIT_IMAP_CMD(imap_cmd_out_uid, cmd, cb, aux)
  1866. cmd->gen.param.uid = -1; /* we're looking for a UID */
  1867. cmd->out_uid = -1; /* in case we get no SEARCH response at all */
  1868. imap_exec( ctx, &cmd->gen, imap_find_msg_p2,
  1869. "UID SEARCH HEADER X-TUID %." stringify(TUIDL) "s", tuid );
  1870. }
  1871. static void
  1872. imap_find_msg_p2( imap_store_t *ctx ATTR_UNUSED, struct imap_cmd *cmd, int response )
  1873. {
  1874. struct imap_cmd_out_uid *cmdp = (struct imap_cmd_out_uid *)cmd;
  1875. transform_msg_response( &response );
  1876. if (response != DRV_OK)
  1877. cmdp->callback( response, -1, cmdp->callback_aux );
  1878. else
  1879. cmdp->callback( cmdp->out_uid <= 0 ? DRV_MSG_BAD : DRV_OK,
  1880. cmdp->out_uid, cmdp->callback_aux );
  1881. }
  1882. /******************* imap_list *******************/
  1883. static void
  1884. imap_list( store_t *gctx,
  1885. void (*cb)( int sts, void *aux ), void *aux )
  1886. {
  1887. imap_store_t *ctx = (imap_store_t *)gctx;
  1888. struct imap_cmd_simple *cmd;
  1889. INIT_IMAP_CMD(imap_cmd_simple, cmd, cb, aux)
  1890. imap_exec( ctx, &cmd->gen, imap_done_simple_box,
  1891. "LIST \"\" \"%s%%\"", ctx->prefix );
  1892. }
  1893. /******************* imap_cancel *******************/
  1894. static void
  1895. imap_cancel( store_t *gctx,
  1896. void (*cb)( void *aux ), void *aux )
  1897. {
  1898. (void)gctx;
  1899. cb( aux );
  1900. }
  1901. /******************* imap_commit *******************/
  1902. static void
  1903. imap_commit( store_t *gctx )
  1904. {
  1905. (void)gctx;
  1906. }
  1907. /******************* imap_parse_store *******************/
  1908. imap_server_conf_t *servers, **serverapp = &servers;
  1909. static int
  1910. imap_parse_store( conffile_t *cfg, store_conf_t **storep, int *err )
  1911. {
  1912. imap_store_conf_t *store;
  1913. imap_server_conf_t *server, *srv, sserver;
  1914. int acc_opt = 0;
  1915. if (!strcasecmp( "IMAPAccount", cfg->cmd )) {
  1916. server = nfcalloc( sizeof(*server) );
  1917. server->name = nfstrdup( cfg->val );
  1918. *serverapp = server;
  1919. serverapp = &server->next;
  1920. store = 0;
  1921. *storep = 0;
  1922. } else if (!strcasecmp( "IMAPStore", cfg->cmd )) {
  1923. store = nfcalloc( sizeof(*store) );
  1924. store->gen.driver = &imap_driver;
  1925. store->gen.name = nfstrdup( cfg->val );
  1926. store->use_namespace = 1;
  1927. *storep = &store->gen;
  1928. memset( &sserver, 0, sizeof(sserver) );
  1929. server = &sserver;
  1930. } else
  1931. return 0;
  1932. #ifdef HAVE_LIBSSL
  1933. /* this will probably annoy people, but its the best default just in
  1934. * case people forget to turn it on
  1935. */
  1936. server->require_ssl = 1;
  1937. server->use_tlsv1 = 1;
  1938. #endif
  1939. while (getcline( cfg ) && cfg->cmd) {
  1940. if (!strcasecmp( "Host", cfg->cmd )) {
  1941. /* The imap[s]: syntax is just a backwards compat hack. */
  1942. #ifdef HAVE_LIBSSL
  1943. if (!memcmp( "imaps:", cfg->val, 6 )) {
  1944. cfg->val += 6;
  1945. server->use_imaps = 1;
  1946. server->use_sslv2 = 1;
  1947. server->use_sslv3 = 1;
  1948. } else
  1949. #endif
  1950. {
  1951. if (!memcmp( "imap:", cfg->val, 5 ))
  1952. cfg->val += 5;
  1953. }
  1954. if (!memcmp( "//", cfg->val, 2 ))
  1955. cfg->val += 2;
  1956. server->host = nfstrdup( cfg->val );
  1957. }
  1958. else if (!strcasecmp( "User", cfg->cmd ))
  1959. server->user = nfstrdup( cfg->val );
  1960. else if (!strcasecmp( "Pass", cfg->cmd ))
  1961. server->pass = nfstrdup( cfg->val );
  1962. else if (!strcasecmp( "Port", cfg->cmd ))
  1963. server->port = parse_int( cfg );
  1964. #ifdef HAVE_LIBSSL
  1965. else if (!strcasecmp( "CertificateFile", cfg->cmd )) {
  1966. server->cert_file = expand_strdup( cfg->val );
  1967. if (access( server->cert_file, R_OK )) {
  1968. error( "%s:%d: CertificateFile '%s': %s\n",
  1969. cfg->file, cfg->line, server->cert_file, strerror( errno ) );
  1970. *err = 1;
  1971. }
  1972. } else if (!strcasecmp( "RequireSSL", cfg->cmd ))
  1973. server->require_ssl = parse_bool( cfg );
  1974. else if (!strcasecmp( "UseIMAPS", cfg->cmd ))
  1975. server->use_imaps = parse_bool( cfg );
  1976. else if (!strcasecmp( "UseSSLv2", cfg->cmd ))
  1977. server->use_sslv2 = parse_bool( cfg );
  1978. else if (!strcasecmp( "UseSSLv3", cfg->cmd ))
  1979. server->use_sslv3 = parse_bool( cfg );
  1980. else if (!strcasecmp( "UseTLSv1", cfg->cmd ))
  1981. server->use_tlsv1 = parse_bool( cfg );
  1982. else if (!strcasecmp( "RequireCRAM", cfg->cmd ))
  1983. server->require_cram = parse_bool( cfg );
  1984. #endif
  1985. else if (!strcasecmp( "Tunnel", cfg->cmd ))
  1986. server->tunnel = nfstrdup( cfg->val );
  1987. else if (store) {
  1988. if (!strcasecmp( "Account", cfg->cmd )) {
  1989. for (srv = servers; srv; srv = srv->next)
  1990. if (srv->name && !strcmp( srv->name, cfg->val ))
  1991. goto gotsrv;
  1992. error( "%s:%d: unknown IMAP account '%s'\n", cfg->file, cfg->line, cfg->val );
  1993. *err = 1;
  1994. continue;
  1995. gotsrv:
  1996. store->server = srv;
  1997. } else if (!strcasecmp( "UseNamespace", cfg->cmd ))
  1998. store->use_namespace = parse_bool( cfg );
  1999. else if (!strcasecmp( "Path", cfg->cmd ))
  2000. store->gen.path = nfstrdup( cfg->val );
  2001. else
  2002. parse_generic_store( &store->gen, cfg, err );
  2003. continue;
  2004. } else {
  2005. error( "%s:%d: unknown/misplaced keyword '%s'\n", cfg->file, cfg->line, cfg->cmd );
  2006. *err = 1;
  2007. continue;
  2008. }
  2009. acc_opt = 1;
  2010. }
  2011. if (!store || !store->server) {
  2012. if (!server->tunnel && !server->host) {
  2013. if (store)
  2014. error( "IMAP store '%s' has incomplete/missing connection details\n", store->gen.name );
  2015. else
  2016. error( "IMAP account '%s' has incomplete/missing connection details\n", server->name );
  2017. *err = 1;
  2018. return 1;
  2019. }
  2020. }
  2021. if (store) {
  2022. if (!store->server) {
  2023. store->server = nfmalloc( sizeof(sserver) );
  2024. memcpy( store->server, &sserver, sizeof(sserver) );
  2025. store->server->name = store->gen.name;
  2026. } else if (acc_opt) {
  2027. error( "IMAP store '%s' has both Account and account-specific options\n", store->gen.name );
  2028. *err = 1;
  2029. }
  2030. }
  2031. return 1;
  2032. }
  2033. struct driver imap_driver = {
  2034. DRV_CRLF,
  2035. imap_parse_store,
  2036. imap_cleanup,
  2037. imap_open_store,
  2038. imap_disown_store,
  2039. imap_own_store,
  2040. imap_cancel_store,
  2041. imap_list,
  2042. imap_prepare_opts,
  2043. imap_select,
  2044. imap_load,
  2045. imap_fetch_msg,
  2046. imap_store_msg,
  2047. imap_find_msg,
  2048. imap_set_flags,
  2049. imap_trash_msg,
  2050. imap_close,
  2051. imap_cancel,
  2052. imap_commit,
  2053. };