Small security patch: Make sure that the envelope sender address doesn't
[squirrelmail.git] / functions / smtp.php
1 <?php
2 /** smtp.php
3 **
4 ** This contains all the functions needed to send messages through
5 ** an smtp server or sendmail.
6 **/
7
8 $smtp_php = true;
9
10 // Returns true only if this message is multipart
11 function isMultipart () {
12 global $attachments;
13
14 if (count($attachments)>0)
15 return true;
16 else
17 return false;
18 }
19
20 // Attach the files that are due to be attached
21 function attachFiles ($fp) {
22 global $attachments, $attachment_dir;
23
24 $length = 0;
25
26 if (isMultipart()) {
27 reset($attachments);
28 while (list($localname, $remotename) = each($attachments)) {
29 // This is to make sure noone is giving a filename in another
30 // directory
31 $localname = ereg_replace ("\\/", "", $localname);
32
33 $fileinfo = fopen ($attachment_dir.$localname.".info", "r");
34 $filetype = fgets ($fileinfo, 8192);
35 fclose ($fileinfo);
36 $filetype = trim ($filetype);
37 if ($filetype=="")
38 $filetype = "application/octet-stream";
39
40 $header = "--".mimeBoundary()."\r\n";
41 $header .= "Content-Type: $filetype\r\n";
42 $header .= "Content-Disposition: attachment; filename=\"$remotename\"\r\n";
43 $header .= "Content-Transfer-Encoding: base64\r\n\r\n";
44 fputs ($fp, $header);
45 $length += strlen($header);
46
47 $file = fopen ($attachment_dir.$localname, "r");
48 while ($tmp = fread($file, 570)) {
49 $encoded = chunk_split(base64_encode($tmp));
50 $length += strlen($encoded);
51 fputs ($fp, $encoded);
52 }
53 fclose ($file);
54 }
55 }
56
57 return $length;
58 }
59
60 // Delete files that are uploaded for attaching
61 function deleteAttachments() {
62 global $attachments, $attachment_dir;
63
64 if (isMultipart()) {
65 reset($attachments);
66 while (list($localname, $remotename) = each($attachments)) {
67 if (!ereg ("\\/", $localname)) {
68 unlink ($attachment_dir.$localname);
69 unlink ($attachment_dir.$localname.".info");
70 }
71 }
72 }
73 }
74
75 // Return a nice MIME-boundary
76 function mimeBoundary () {
77 global $version, $REMOTE_ADDR, $SERVER_NAME, $REMOTE_PORT;
78
79 static $mimeBoundaryString;
80
81 if ($mimeBoundaryString == "") {
82 $temp = "SquirrelMail".$version.$REMOTE_ADDR.$SERVER_NAME.
83 $REMOTE_PORT;
84 $mimeBoundaryString = "=-_+".substr(md5($temp),1,20);
85 }
86
87 return $mimeBoundaryString;
88 }
89
90 /* Time offset for correct timezone */
91 function timezone () {
92 $diff_second = date("Z");
93 if ($diff_second > 0)
94 $sign = "+";
95 else
96 $sign = "-";
97
98 $diff_second = abs($diff_second);
99
100 $diff_hour = floor ($diff_second / 3600);
101 $diff_minute = floor (($diff_second-3600*$diff_hour) / 60);
102
103 $zonename = "(".strftime("%Z").")";
104 $result = sprintf ("%s%02d%02d %s", $sign, $diff_hour, $diff_minute, $zonename);
105 return ($result);
106 }
107
108 /* Print all the needed RFC822 headers */
109 function write822Header ($fp, $t, $c, $b, $subject, $more_headers) {
110 global $REMOTE_ADDR, $SERVER_NAME, $REMOTE_PORT;
111 global $data_dir, $username, $domain, $version, $useSendmail;
112 global $default_charset, $HTTP_VIA, $HTTP_X_FORWARDED_FOR;
113 global $REMOTE_HOST;
114
115 // Storing the header to make sure the header is the same
116 // everytime the header is printed.
117 static $header, $headerlength;
118
119 if ($header == "") {
120 $to = parseAddrs($t);
121 $cc = parseAddrs($c);
122 $bcc = parseAddrs($b);
123 $reply_to = getPref($data_dir, $username, "reply_to");
124 $from = getPref($data_dir, $username, "full_name");
125 $from_addr = getPref($data_dir, $username, "email_address");
126
127 if ($from_addr == "")
128 $from_addr = "$username@$domain";
129
130 $to_list = getLineOfAddrs($to);
131 $cc_list = getLineOfAddrs($cc);
132 $bcc_list = getLineOfAddrs($bcc);
133
134 /* Encoding 8-bit characters and making from line */
135 $subject = sqStripSlashes(encodeHeader($subject));
136 if ($from == "")
137 $from = "<$from_addr>";
138 else
139 $from = "\"" . encodeHeader($from) . "\" <$from_addr>";
140
141 /* This creates an RFC 822 date */
142 $date = date("D, j M Y H:i:s ", mktime()) . timezone();
143
144 /* Create a message-id */
145 $message_id = "<" . $REMOTE_PORT . "." . $REMOTE_ADDR . ".";
146 $message_id .= time() . ".squirrel@" . $SERVER_NAME .">";
147
148 /* Make an RFC822 Received: line */
149 if (isset($REMOTE_HOST))
150 $received_from = "$REMOTE_HOST ([$REMOTE_ADDR])";
151 else
152 $received_from = $REMOTE_ADDR;
153
154 if (isset($HTTP_VIA) || isset ($HTTP_X_FORWARDED_FOR)) {
155 if ($HTTP_X_FORWARDED_FOR == "")
156 $HTTP_X_FORWARDED_FOR = "unknown";
157 $received_from .= " (proxying for $HTTP_X_FORWARDED_FOR)";
158 }
159
160 $header = "Received: from $received_from\r\n";
161 $header .= " (SquirrelMail authenticated user $username)\r\n";
162 $header .= " by $SERVER_NAME with HTTP;\r\n";
163 $header .= " $date\r\n";
164
165 /* Insert the rest of the header fields */
166 $header .= "Message-ID: $message_id\r\n";
167 $header .= "Date: $date\r\n";
168 $header .= "Subject: $subject\r\n";
169 $header .= "From: $from\r\n";
170 $header .= "To: $to_list \r\n"; // Who it's TO
171
172 /* Insert headers from the $more_headers array */
173 if(is_array($more_headers)) {
174 reset($more_headers);
175 while(list($h_name, $h_val) = each($more_headers)) {
176 $header .= sprintf("%s: %s\r\n", $h_name, $h_val);
177 }
178 }
179
180 if ($cc_list) {
181 $header .= "Cc: $cc_list\r\n"; // Who the CCs are
182 }
183
184 if ($reply_to != "")
185 $header .= "Reply-To: $reply_to\r\n";
186
187 if ($useSendmail) {
188 if ($bcc_list) {
189 // BCCs is removed from header by sendmail
190 $header .= "Bcc: $bcc_list\r\n";
191 }
192 }
193
194 $header .= "X-Mailer: SquirrelMail (version $version)\r\n"; // Identify SquirrelMail
195
196 // Do the MIME-stuff
197 $header .= "MIME-Version: 1.0\r\n";
198
199 if (isMultipart()) {
200 $header .= "Content-Type: multipart/mixed; boundary=\"";
201 $header .= mimeBoundary();
202 $header .= "\"\r\n";
203 } else {
204 if ($default_charset != "")
205 $header .= "Content-Type: text/plain; charset=$default_charset\r\n";
206 else
207 $header .= "Content-Type: text/plain;\r\n";
208 $header .= "Content-Transfer-Encoding: 8bit\r\n";
209 }
210 $header .= "\r\n"; // One blank line to separate header and body
211
212 $headerlength = strlen($header);
213 }
214
215 // Write the header
216 fputs ($fp, $header);
217
218 return $headerlength;
219 }
220
221 // Send the body
222 function writeBody ($fp, $passedBody) {
223 global $default_charset;
224
225 $attachmentlength = 0;
226
227 if (isMultipart()) {
228 $body = "--".mimeBoundary()."\r\n";
229
230 if ($default_charset != "")
231 $body .= "Content-Type: text/plain; charset=$default_charset\r\n";
232 else
233 $body .= "Content-Type: text/plain\r\n";
234
235 $body .= "Content-Transfer-Encoding: 8bit\r\n\r\n";
236 $body .= sqStripSlashes($passedBody) . "\r\n";
237 fputs ($fp, $body);
238
239 $attachmentlength = attachFiles($fp);
240
241 $postbody .= "\r\n--".mimeBoundary()."--\r\n\r\n";
242 fputs ($fp, $postbody);
243 } else {
244 $body = sqStripSlashes($passedBody) . "\r\n";
245 fputs ($fp, $body);
246 $postbody = "\r\n";
247 fputs ($fp, $postbody);
248 }
249
250 return (strlen($body) + strlen($postbody) + $attachmentlength);
251 }
252
253 // Send mail using the sendmail command
254 function sendSendmail($t, $c, $b, $subject, $body, $more_headers) {
255 global $sendmail_path, $username, $domain;
256
257 // Build envelope sender address. Make sure it doesn't contain
258 // spaces or other "weird" chars that would allow a user to
259 // exploit the shell/pipe it is used in.
260 $envelopefrom = "$username@$domain";
261 $envelopefrom = ereg_replace("[[:blank:]]","", $envelopefrom);
262 $envelopefrom = ereg_replace("[[:space:]]","", $envelopefrom);
263 $envelopefrom = ereg_replace("[[:cntrl:]]","", $envelopefrom);
264
265 // open pipe to sendmail
266 $fp = popen (escapeshellcmd("$sendmail_path -t -f$envelopefrom"), "w");
267
268 $headerlength = write822Header ($fp, $t, $c, $b, $subject, $more_headers);
269 $bodylength = writeBody($fp, $body);
270
271 pclose($fp);
272
273 return ($headerlength + $bodylength);
274 }
275
276 function smtpReadData($smtpConnection) {
277 $read = fgets($smtpConnection, 1024);
278 $counter = 0;
279 while ($read) {
280 echo $read . "<BR>";
281 $data[$counter] = $read;
282 $read = fgets($smtpConnection, 1024);
283 $counter++;
284 }
285 }
286
287 function sendSMTP($t, $c, $b, $subject, $body, $more_headers) {
288 global $username, $domain, $version, $smtpServerAddress, $smtpPort,
289 $data_dir, $color;
290
291 $to = parseAddrs($t);
292 $cc = parseAddrs($c);
293 $bcc = parseAddrs($b);
294 $from_addr = getPref($data_dir, $username, "email_address");
295
296
297 /*
298 * A patch from Bill Thousand <billyt@claritytech.com>
299 *
300 * "I don't know if anyone else needs this or not, but it totally makes squirrelmail usable for us.
301 * This quick patch checks the username and from address for the domain information. We use
302 * a virtual domain patch for our imap server that allows multiple domains by using username@domain.com
303 * as the login username."
304 */
305 if ($from_addr == "") {
306 if (strstr($username, "@")) {
307 $from_addr = $username;
308 $address_pieces = explode("@",$username);
309 $domain = $address_pieces[1];
310 } else {
311 $from_addr = "$username@$domain";
312 }
313 } else {
314 // If the From Address is specified, use the domain in the from
315 // address if it's there.
316 if (strstr($from_addr, "@")) {
317 $address_pieces = explode("@", $from_addr);
318 $domain = $address_pieces[1];
319 }
320 }
321 /*
322 * End patch from Bill Thousand
323 */
324
325
326 $smtpConnection = fsockopen($smtpServerAddress, $smtpPort, $errorNumber, $errorString);
327 if (!$smtpConnection) {
328 echo "Error connecting to SMTP Server.<br>";
329 echo "$errorNumber : $errorString<br>";
330 exit;
331 }
332 $tmp = fgets($smtpConnection, 1024);
333 errorCheck($tmp, $smtpConnection);
334
335 $to_list = getLineOfAddrs($to);
336 $cc_list = getLineOfAddrs($cc);
337
338 /** Lets introduce ourselves */
339 fputs($smtpConnection, "HELO $domain\r\n");
340 $tmp = fgets($smtpConnection, 1024);
341 errorCheck($tmp, $smtpConnection);
342
343 /** Ok, who is sending the message? */
344 fputs($smtpConnection, "MAIL FROM:<$from_addr>\r\n");
345 $tmp = fgets($smtpConnection, 1024);
346 errorCheck($tmp, $smtpConnection);
347
348 /** send who the recipients are */
349 for ($i = 0; $i < count($to); $i++) {
350 fputs($smtpConnection, "RCPT TO:<$to[$i]>\r\n");
351 $tmp = fgets($smtpConnection, 1024);
352 errorCheck($tmp, $smtpConnection);
353 }
354 for ($i = 0; $i < count($cc); $i++) {
355 fputs($smtpConnection, "RCPT TO:<$cc[$i]>\r\n");
356 $tmp = fgets($smtpConnection, 1024);
357 errorCheck($tmp, $smtpConnection);
358 }
359 for ($i = 0; $i < count($bcc); $i++) {
360 fputs($smtpConnection, "RCPT TO:<$bcc[$i]>\r\n");
361 $tmp = fgets($smtpConnection, 1024);
362 errorCheck($tmp, $smtpConnection);
363 }
364
365 /** Lets start sending the actual message */
366 fputs($smtpConnection, "DATA\r\n");
367 $tmp = fgets($smtpConnection, 1024);
368 errorCheck($tmp, $smtpConnection);
369
370 // Send the message
371 $headerlength = write822Header ($smtpConnection, $t, $c, $b, $subject, $more_headers);
372 $bodylength = writeBody($smtpConnection, $body);
373
374 fputs($smtpConnection, ".\r\n"); // end the DATA part
375 $tmp = fgets($smtpConnection, 1024);
376 $num = errorCheck($tmp, $smtpConnection);
377 if ($num != 250) {
378 $tmp = nl2br(htmlspecialchars($tmp));
379 echo "ERROR<BR>Message not sent!<BR>Reason given: $tmp<BR></BODY></HTML>";
380 }
381
382 fputs($smtpConnection, "QUIT\r\n"); // log off
383
384 fclose($smtpConnection);
385
386 return ($headerlength + $bodylength);
387 }
388
389
390 function errorCheck($line, $smtpConnection) {
391 global $page_header_php;
392 global $color;
393 if (!isset($page_header_php)) {
394 include "../functions/page_header.php";
395 }
396
397 // Read new lines on a multiline response
398 $lines = $line;
399 while(ereg("^[0-9]+-", $line)) {
400 $line = fgets($smtpConnection, 1024);
401 $lines .= $line;
402 }
403
404 // Status: 0 = fatal
405 // 5 = ok
406
407 $err_num = substr($line, 0, strpos($line, " "));
408 switch ($err_num) {
409 case 500: $message = "Syntax error; command not recognized";
410 $status = 0;
411 break;
412 case 501: $message = "Syntax error in parameters or arguments";
413 $status = 0;
414 break;
415 case 502: $message = "Command not implemented";
416 $status = 0;
417 break;
418 case 503: $message = "Bad sequence of commands";
419 $status = 0;
420 break;
421 case 504: $message = "Command parameter not implemented";
422 $status = 0;
423 break;
424
425
426 case 211: $message = "System status, or system help reply";
427 $status = 5;
428 break;
429 case 214: $message = "Help message";
430 $status = 5;
431 break;
432
433
434 case 220: $message = "Service ready";
435 $status = 5;
436 break;
437 case 221: $message = "Service closing transmission channel";
438 $status = 5;
439 break;
440 case 421: $message = "Service not available, closing chanel";
441 $status = 0;
442 break;
443
444
445 case 250: $message = "Requested mail action okay, completed";
446 $status = 5;
447 break;
448 case 251: $message = "User not local; will forward";
449 $status = 5;
450 break;
451 case 450: $message = "Requested mail action not taken: mailbox unavailable";
452 $status = 0;
453 break;
454 case 550: $message = "Requested action not taken: mailbox unavailable";
455 $status = 0;
456 break;
457 case 451: $message = "Requested action aborted: error in processing";
458 $status = 0;
459 break;
460 case 551: $message = "User not local; please try forwarding";
461 $status = 0;
462 break;
463 case 452: $message = "Requested action not taken: insufficient system storage";
464 $status = 0;
465 break;
466 case 552: $message = "Requested mail action aborted: exceeding storage allocation";
467 $status = 0;
468 break;
469 case 553: $message = "Requested action not taken: mailbox name not allowed";
470 $status = 0;
471 break;
472 case 354: $message = "Start mail input; end with .";
473 $status = 5;
474 break;
475 case 554: $message = "Transaction failed";
476 $status = 0;
477 break;
478 default: $message = "Unknown response: ". nl2br(htmlspecialchars($lines));
479 $status = 0;
480 $error_num = "001";
481 break;
482 }
483
484 if ($status == 0) {
485 displayPageHeader($color, "None");
486 echo "<TT>";
487 echo "<br><b><font color=\"$color[1]\">ERROR</font></b><br><br>";
488 echo "&nbsp;&nbsp;&nbsp;<B>Error Number: </B>$err_num<BR>";
489 echo "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<B>Reason: </B>$message<BR>";
490 $lines = nl2br(htmlspecialchars($lines));
491 echo "<B>Server Response: </B>$lines<BR>";
492 echo "<BR>MAIL NOT SENT";
493 echo "</TT></BODY></HTML>";
494 exit;
495 }
496 return $err_num;
497 }
498
499 function sendMessage($t, $c, $b, $subject, $body, $reply_id) {
500 global $useSendmail, $msg_id, $is_reply, $mailbox;
501 global $data_dir, $username, $domain, $key, $version, $sent_folder, $imapServerAddress, $imapPort;
502 $more_headers = Array();
503
504 $imap_stream = sqimap_login($username, $key, $imapServerAddress, $imapPort, 1);
505
506 if ($reply_id) {
507 sqimap_mailbox_select ($imap_stream, $mailbox);
508 sqimap_messages_flag ($imap_stream, $reply_id, $reply_id, "Answered");
509
510 // Insert In-Reply-To and References headers if the
511 // message-id of the message we reply to is set (longer than "<>")
512 // The References header should really be the old Referenced header
513 // with the message ID appended, but it can be only the message ID too.
514 $hdr = sqimap_get_small_header ($imap_stream, $reply_id, false);
515 if(strlen($hdr->message_id) > 2) {
516 $more_headers["In-Reply-To"] = $hdr->message_id;
517 $more_headers["References"] = $hdr->message_id;
518 }
519 sqimap_mailbox_close($imap_stream);
520 }
521
522 if ($useSendmail==true) {
523 $length = sendSendmail($t, $c, $b, $subject, $body, $more_headers);
524 } else {
525 $length = sendSMTP($t, $c, $b, $subject, $body, $more_headers);
526 }
527
528 if (sqimap_mailbox_exists ($imap_stream, $sent_folder)) {
529 sqimap_append ($imap_stream, $sent_folder, $length);
530 write822Header ($imap_stream, $t, $c, $b, $subject, $more_headers);
531 writeBody ($imap_stream, $body);
532 sqimap_append_done ($imap_stream);
533 }
534 sqimap_logout($imap_stream);
535 // Delete the files uploaded for attaching (if any).
536 deleteAttachments();
537 }
538 ?>