changeset 17645:9a1c7a566d7c

explicit merge of '1c5a391126b5b506a29f0b9e34160d239cb783c6' and '8dee13b251ac588bb5ba3c9565e3badd0678254f'
author Jeffrey Connelly <jaconnel@calpoly.edu>
date Mon, 18 Jun 2007 01:48:35 +0000
parents 821ae99678d6 (current diff) d198d62c5ff5 (diff)
children c77daec18cbd
files COPYRIGHT configure.ac libpurple/cipher.c libpurple/protocols/bonjour/dns_sd.c libpurple/protocols/bonjour/dns_sd.h pidgin/pixmaps/emotes/default/22/theme pidgin/pixmaps/emotes/none/theme po/POTFILES.in
diffstat 20 files changed, 4296 insertions(+), 4 deletions(-) [+]
line wrap: on
line diff
--- a/configure.ac	Fri Jun 15 02:57:13 2007 +0000
+++ b/configure.ac	Mon Jun 18 01:48:35 2007 +0000
@@ -814,7 +814,7 @@
 fi
 
 if test "x$STATIC_PRPLS" = "xall" ; then
-	STATIC_PRPLS="bonjour gg irc jabber msn novell oscar qq sametime silc simple yahoo zephyr"
+	STATIC_PRPLS="bonjour gg irc jabber msn myspace novell oscar qq sametime silc simple yahoo zephyr"
 fi
 if test "x$have_meanwhile" != "xyes" ; then
 	STATIC_PRPLS=`echo $STATIC_PRPLS | $sedpath 's/sametime//'`
@@ -858,6 +858,7 @@
 		irc)		static_irc=yes ;;
 		jabber)		static_jabber=yes ;;
 		msn)		static_msn=yes ;;
+		myspace)	static_myspace=yes ;;
 		novell)		static_novell=yes ;;
 		oscar)		static_oscar=yes ;;
 		aim)		static_oscar=yes ;;
@@ -878,6 +879,7 @@
 AM_CONDITIONAL(STATIC_IRC, test "x$static_irc" = "xyes")
 AM_CONDITIONAL(STATIC_JABBER, test "x$static_jabber" = "xyes")
 AM_CONDITIONAL(STATIC_MSN, test "x$static_msn" = "xyes")
+AM_CONDITIONAL(STATIC_MYSPACE, test "x$static_myspace" = "xyes")
 AM_CONDITIONAL(STATIC_NOVELL, test "x$static_novell" = "xyes")
 AM_CONDITIONAL(STATIC_OSCAR, test "x$static_oscar" = "xyes")
 AM_CONDITIONAL(STATIC_QQ, test "x$static_qq" = "xyes")
@@ -893,7 +895,7 @@
 
 AC_ARG_WITH(dynamic_prpls, [AC_HELP_STRING([--with-dynamic-prpls], [specify which protocols to build dynamically])], [DYNAMIC_PRPLS=`echo $withval | $sedpath 's/,/ /g'`])
 if test "x$DYNAMIC_PRPLS" = "xall" ; then
-	DYNAMIC_PRPLS="bonjour gg irc jabber msn novell oscar qq sametime silc simple yahoo zephyr"
+	DYNAMIC_PRPLS="bonjour gg irc jabber msn myspace novell oscar qq sametime silc simple yahoo zephyr"
 fi
 if test "x$have_meanwhile" != "xyes"; then
 	DYNAMIC_PRPLS=`echo $DYNAMIC_PRPLS | $sedpath 's/sametime//'`
@@ -915,6 +917,7 @@
 		irc)		dynamic_irc=yes ;;
 		jabber)		dynamic_jabber=yes ;;
 		msn)		dynamic_msn=yes ;;
+		myspace)	dynamic_myspace=yes ;;
 		novell)		dynamic_novell=yes ;;
 		oscar)		dynamic_oscar=yes ;;
 		aim)		dynamic_oscar=yes ;;
@@ -935,6 +938,7 @@
 AM_CONDITIONAL(DYNAMIC_IRC, test "x$dynamic_irc" = "xyes")
 AM_CONDITIONAL(DYNAMIC_JABBER, test "x$dynamic_jabber" = "xyes")
 AM_CONDITIONAL(DYNAMIC_MSN, test "x$dynamic_msn" = "xyes")
+AM_CONDITIONAL(DYNAMIC_MYSPACE, test "x$dynamic_myspace" = "xyes")
 AM_CONDITIONAL(DYNAMIC_NOVELL, test "x$dynamic_novell" = "xyes")
 AM_CONDITIONAL(DYNAMIC_OSCAR, test "x$dynamic_oscar" = "xyes")
 AM_CONDITIONAL(DYNAMIC_QQ, test "x$dynamic_qq" = "xyes")
@@ -2134,6 +2138,7 @@
 		   libpurple/protocols/irc/Makefile
 		   libpurple/protocols/jabber/Makefile
 		   libpurple/protocols/msn/Makefile
+		   libpurple/protocols/myspace/Makefile
 		   libpurple/protocols/novell/Makefile
 		   libpurple/protocols/null/Makefile
 		   libpurple/protocols/oscar/Makefile
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libpurple/protocols/myspace/CHANGES	Mon Jun 18 01:48:35 2007 +0000
@@ -0,0 +1,59 @@
+2007-06-14 Jeff Connelly <jeff2@homing.pidgin.im> - 0.7
+* Add/delete buddy now functional (required many other code improvements).
+* Show improved buddy information in tooltip text.
+* Show user profile (in "Get Info" option) for buddies on buddy list.
+* Fix crash when re-logging in. 
+
+2007-06-12 Jeff Connelly <jeff2@homing.pidgin.im> - 0.6
+* Use RC4 code from Libpurple 2.0.1
+* Use a new implementation for sending and receiving messages (MsimMessage).
+  This infrastructural change significantly improves extensibility.
+* Show online buddies as online.
+* Send and receive typing notifications (along with other required changes).
+
+2007-05-22 Jeff Connelly <jeff2@homing.pidgin.im> - 0.5
+* Add protocol escaping, so can now send and receive / and \ characters
+* Designed Pidgin 2.0.0beta7
+* Use RC4 code from Samba
+* Use translations (_ macro)
+* No major changes to code, still getting familiar with tools & community
+
+2007-04-29 Jeff Connelly <jeff2@homing.pidgin.im> 
+
+* NOTE: This code is now being developed under Monotone, in the
+  im.pidgin.soc.2007.msimprpl branch on my local computer, which
+  is periodically sync'd with pidgin.im's Monotone database.
+
+  Changes will be logged to Monotone.
+
+2007-04-15 Jeff Connelly <myspaceim@xyzzy.cjb.net> - 0.4
+
+* Gracefully handle a full receive buffer
+* Handle fatal errors
+* Last version for Gaim 2.0.0beta6
+
+2007-04-14 Jeff Connelly <myspaceim@xyzzy.cjb.net> - 0.3
+
+* Win32 support
+* Add a large number of precondition checks and a handful of assertions
+* Add documentation to each function, for doxygen.
+
+2007-04-10 Jeff Connelly <myspaceim@xyzzy.cjb.net> - 0.2
+
+* Add ability to IM by email address.
+* Show usernames on buddy list instead of userids.
+* Show incoming messages as coming from username, instead of userid.
+* Add status messages and tooltip text.
+
+2007-04-09 Jeff Connelly <myspaceim@xyzzy.cjb.net> - 0.1
+
+* Parsing most of the protocol.
+* Logging in using RC4/SHA1-based authentication.
+* Sending messages, by numeric userid or username.
+* Receiving messages, currently only by numeric userid.
+* Some buddy list support (show all users on buddy list as online, by uid).
+
+2007-04-07 Jeff Connelly <myspaceim@xyzzy.cjb.net> - 0.0
+
+* Initial version. Login only. Not publicly released.
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libpurple/protocols/myspace/ChangeLog	Mon Jun 18 01:48:35 2007 +0000
@@ -0,0 +1,39 @@
+
+2007-04-29 Jeff Connelly <jeff2@homing.pidgin.com> 
+
+* NOTE: This code is now being developed under Monotone, in the
+  im.pidgin.soc.2007.msimprpl branch on my local computer, which
+  is periodically sync'd with pidgin.im's Monotone database.
+
+  Changes will be logged to Monotone.
+
+2007-04-15 Jeff Connelly <myspaceim@xyzzy.cjb.net> - 0.4
+
+* Gracefully handle a full receive buffer
+* Handle fatal errors
+
+2007-04-14 Jeff Connelly <myspaceim@xyzzy.cjb.net> - 0.3
+
+* Win32 support
+* Add a large number of precondition checks and a handful of assertions
+* Add documentation to each function, for doxygen.
+
+2007-04-10 Jeff Connelly <myspaceim@xyzzy.cjb.net> - 0.2
+
+* Add ability to IM by email address.
+* Show usernames on buddy list instead of userids.
+* Show incoming messages as coming from username, instead of userid.
+* Add status messages and tooltip text.
+
+2007-04-09 Jeff Connelly <myspaceim@xyzzy.cjb.net> - 0.1
+
+* Parsing most of the protocol.
+* Logging in using RC4/SHA1-based authentication.
+* Sending messages, by numeric userid or username.
+* Receiving messages, currently only by numeric userid.
+* Some buddy list support (show all users on buddy list as online, by uid).
+
+2007-04-07 Jeff Connelly <myspaceim@xyzzy.cjb.net> - 0.0
+
+* Initial version. Login only. Not publicly released.
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libpurple/protocols/myspace/LICENSE	Mon Jun 18 01:48:35 2007 +0000
@@ -0,0 +1,339 @@
+		    GNU GENERAL PUBLIC LICENSE
+		       Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+			    Preamble
+
+  The licenses for most software are designed to take away your
+freedom to share and change it.  By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users.  This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it.  (Some other Free Software Foundation software is covered by
+the GNU Lesser General Public License instead.)  You can apply it to
+your programs, too.
+
+  When we speak of free software, we are referring to freedom, not
+price.  Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+  To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+  For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have.  You must make sure that they, too, receive or can get the
+source code.  And you must show them these terms so they know their
+rights.
+
+  We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+  Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software.  If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+  Finally, any free program is threatened constantly by software
+patents.  We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary.  To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+  The precise terms and conditions for copying, distribution and
+modification follow.
+
+		    GNU GENERAL PUBLIC LICENSE
+   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+  0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License.  The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language.  (Hereinafter, translation is included without limitation in
+the term "modification".)  Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope.  The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+  1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+  2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+    a) You must cause the modified files to carry prominent notices
+    stating that you changed the files and the date of any change.
+
+    b) You must cause any work that you distribute or publish, that in
+    whole or in part contains or is derived from the Program or any
+    part thereof, to be licensed as a whole at no charge to all third
+    parties under the terms of this License.
+
+    c) If the modified program normally reads commands interactively
+    when run, you must cause it, when started running for such
+    interactive use in the most ordinary way, to print or display an
+    announcement including an appropriate copyright notice and a
+    notice that there is no warranty (or else, saying that you provide
+    a warranty) and that users may redistribute the program under
+    these conditions, and telling the user how to view a copy of this
+    License.  (Exception: if the Program itself is interactive but
+    does not normally print such an announcement, your work based on
+    the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole.  If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works.  But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+  3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+    a) Accompany it with the complete corresponding machine-readable
+    source code, which must be distributed under the terms of Sections
+    1 and 2 above on a medium customarily used for software interchange; or,
+
+    b) Accompany it with a written offer, valid for at least three
+    years, to give any third party, for a charge no more than your
+    cost of physically performing source distribution, a complete
+    machine-readable copy of the corresponding source code, to be
+    distributed under the terms of Sections 1 and 2 above on a medium
+    customarily used for software interchange; or,
+
+    c) Accompany it with the information you received as to the offer
+    to distribute corresponding source code.  (This alternative is
+    allowed only for noncommercial distribution and only if you
+    received the program in object code or executable form with such
+    an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it.  For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable.  However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+  4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License.  Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+  5. You are not required to accept this License, since you have not
+signed it.  However, nothing else grants you permission to modify or
+distribute the Program or its derivative works.  These actions are
+prohibited by law if you do not accept this License.  Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+  6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions.  You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+  7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License.  If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all.  For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices.  Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+  8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded.  In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+  9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time.  Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number.  If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation.  If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+  10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission.  For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this.  Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+			    NO WARRANTY
+
+  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+		     END OF TERMS AND CONDITIONS
+
+	    How to Apply These Terms to Your New Programs
+
+  If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+  To do so, attach the following notices to the program.  It is safest
+to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+    <one line to give the program's name and a brief idea of what it does.>
+    Copyright (C) <year>  <name of author>
+
+    This program is free software; you can redistribute it and/or modify
+    it under the terms of the GNU General Public License as published by
+    the Free Software Foundation; either version 2 of the License, or
+    (at your option) any later version.
+
+    This program is distributed in the hope that it will be useful,
+    but WITHOUT ANY WARRANTY; without even the implied warranty of
+    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+    GNU General Public License for more details.
+
+    You should have received a copy of the GNU General Public License along
+    with this program; if not, write to the Free Software Foundation, Inc.,
+    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+
+Also add information on how to contact you by electronic and paper mail.
+
+If the program is interactive, make it output a short notice like this
+when it starts in an interactive mode:
+
+    Gnomovision version 69, Copyright (C) year name of author
+    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+    This is free software, and you are welcome to redistribute it
+    under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License.  Of course, the commands you use may
+be called something other than `show w' and `show c'; they could even be
+mouse-clicks or menu items--whatever suits your program.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the program, if
+necessary.  Here is a sample; alter the names:
+
+  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
+  `Gnomovision' (which makes passes at compilers) written by James Hacker.
+
+  <signature of Ty Coon>, 1 April 1989
+  Ty Coon, President of Vice
+
+This General Public License does not permit incorporating your program into
+proprietary programs.  If your program is a subroutine library, you may
+consider it more useful to permit linking proprietary applications with the
+library.  If this is what you want to do, use the GNU Lesser General
+Public License instead of this License.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libpurple/protocols/myspace/Makefile.am	Mon Jun 18 01:48:35 2007 +0000
@@ -0,0 +1,30 @@
+EXTRA_DIST = Makefile.mingw
+
+pkgdir = $(libdir)/purple-$(PURPLE_MAJOR_VERSION)
+
+SOURCES = myspace.c message.c
+
+AM_CFLAGS = $(st)
+
+libmyspace_la_LDFLAGS = -module -avoid-version
+
+if STATIC_MYSPACE
+
+st = -DPURPLE_STATIC_PRPL
+noinst_LIBRARIES     = libmyspace.a
+libmyspace_a_SOURCES = $(SOURCES)
+libmyspace_a_CFLAGS  = $(AM_CFLAGS)
+
+else
+
+st =
+pkg_LTLIBRARIES       = libmyspace.la
+libmyspace_la_SOURCES = $(SOURCES)
+libmyspace_la_LIBADD  = $(GLIB_LIBS)
+
+endif
+
+AM_CPPFLAGS = \
+	-I$(top_srcdir)/libpurple \
+	$(GLIB_CFLAGS) \
+	$(DEBUG_CFLAGS)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libpurple/protocols/myspace/Makefile.mingw	Mon Jun 18 01:48:35 2007 +0000
@@ -0,0 +1,81 @@
+#
+# Makefile.mingw
+#
+# Description: Makefile for win32 (mingw) version of libmyspace
+#
+
+PIDGIN_TREE_TOP := ../../..
+include $(PIDGIN_TREE_TOP)/libpurple/win32/global.mak
+
+TARGET = libmyspace
+TYPE = PLUGIN
+
+# Static or Plugin...
+ifeq ($(TYPE),STATIC)
+  DEFINES += -DSTATIC
+  DLL_INSTALL_DIR =	$(PURPLE_INSTALL_DIR)
+else
+ifeq ($(TYPE),PLUGIN)
+  DLL_INSTALL_DIR =	$(PURPLE_INSTALL_PLUGINS_DIR)
+endif
+endif
+
+##
+## INCLUDE PATHS
+##
+INCLUDE_PATHS +=	-I. \
+			-I$(GTK_TOP)/include \
+			-I$(GTK_TOP)/include/glib-2.0 \
+			-I$(GTK_TOP)/lib/glib-2.0/include \
+			-I$(PURPLE_TOP) \
+			-I$(PURPLE_TOP)/win32 \
+			-I$(PIDGIN_TREE_TOP)
+
+LIB_PATHS =		-L$(GTK_TOP)/lib \
+			-L$(PURPLE_TOP)
+
+##
+##  SOURCES, OBJECTS
+##
+C_SRC =			myspace.c message.c
+
+OBJECTS = $(C_SRC:%.c=%.o)
+
+##
+## LIBRARIES
+##
+LIBS =	\
+			-lglib-2.0 \
+			-lws2_32 \
+			-lintl \
+			-lpurple
+
+include $(PIDGIN_COMMON_RULES)
+
+##
+## TARGET DEFINITIONS
+##
+.PHONY: all install clean
+
+all: $(TARGET).dll
+
+install: all $(DLL_INSTALL_DIR)
+	cp $(TARGET).dll $(DLL_INSTALL_DIR)
+
+$(OBJECTS): $(PURPLE_CONFIG_H)
+
+##
+## BUILD DLL
+##
+$(TARGET).dll: $(PURPLE_DLL).a $(OBJECTS)
+	$(CC) -shared $(OBJECTS) $(LIB_PATHS) $(LIBS) $(DLL_LD_FLAGS) -o $(TARGET).dll
+
+##
+## CLEAN RULES
+##
+
+clean:
+	rm -f $(OBJECTS)
+	rm -f $(TARGET).dll
+
+include $(PIDGIN_COMMON_TARGETS)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libpurple/protocols/myspace/README	Mon Jun 18 01:48:35 2007 +0000
@@ -0,0 +1,36 @@
+MySpaceIM Protocol Plugin      by Jeff Connelly 20070414
+
+** Note: this code is being developed under Google Summer of Code.
+
+Greetings. This package contains a plugin for libpurple (as used in
+Pidgin, formerly Gaim) to connect to the new MySpaceIM instant messaging 
+network and send/receive messages. Functionality is only basic as of yet, 
+and this code should be considered beta quality.
+
+For features and TODO, see http://developer.pidgin.im/wiki/MySpaceIM
+
+Login using your _email address_ you use to login to myspace.com. You can't
+login using your numeric ID or alias.
+
+To test it out, send a message to yourself (by your username or numeric 
+uid (email not yet supported)) or tom (6221). In either case you should 
+get a reply. You should also be able to talk to other MySpaceIM users if 
+you desire. Replies will always be shown as coming from a user's username, 
+even if you IM by email or userid.
+
+There is a lot of work still to be done:
+- Better buddy list support, signing on/off
+- Status (online/offline/invisible, w/ message)
+- Typing notifications
+- General clean up of code
+- All the TODOs and XXX's mentioned in myspace.c
+- Every other MySpaceIM feature not yet implemented
+
+Feedback welcome.
+
+Enjoy,
+-Jeff Connelly
+California Polytechnic State University at San Luis Obispo
+myspaceim@xyzzy.cjb.net
+jeff2@homing.pidgin.im
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libpurple/protocols/myspace/message.c	Mon Jun 18 01:48:35 2007 +0000
@@ -0,0 +1,923 @@
+/** MySpaceIM protocol messages
+ *
+ * \author Jeff Connelly
+ *
+ * Copyright (C) 2007, Jeff Connelly <jeff2@homing.pidgin.im>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+#include "myspace.h"
+#include "message.h"
+
+static void msim_msg_free_element(gpointer data, gpointer user_data);
+static void msim_msg_debug_string_element(gpointer data, gpointer user_data);
+static gchar *msim_msg_pack_using(MsimMessage *msg, GFunc gf, const gchar *sep, const gchar *begin, const gchar *end);
+static gchar *msim_msg_pack_element_data(MsimMessageElement *elem);
+static GList *msim_msg_get_node(MsimMessage *msg, const gchar *name);
+static MsimMessage *msim_msg_new_v(va_list argp);
+
+/** Create a new MsimMessage. 
+ * 
+ * @param not_empty FALSE if message is empty, TRUE if variadic arguments follow.
+ * @param ... A sequence of gchar* key/type/value triplets, terminated with NULL. 
+ *
+ * See msim_msg_append() documentation for details on types.
+ */
+MsimMessage *msim_msg_new(gboolean not_empty, ...)
+{
+	va_list argp;
+
+	va_start(argp, not_empty);
+
+	if (not_empty)
+		return msim_msg_new_v(argp);
+	else
+		return NULL;
+}
+
+/** Create a new message from va_list and its first argument.
+ *
+ * @param argp A va_list of variadic arguments, already started with va_start(). Will be va_end()'d.
+ * @return New MsimMessage *, must be freed with msim_msg_free().
+ *
+ * For internal use - users probably want msim_msg_new() or msim_send().
+ */
+static MsimMessage *msim_msg_new_v(va_list argp)
+{
+	gchar *key, *value;
+	MsimMessageType type;
+	GString *gs;
+	MsimMessage *msg;
+
+	/* Begin with an empty message. */
+	msg = NULL;
+
+	/* Read key, type, value triplets until NULL. */
+	do
+	{
+		key = va_arg(argp, gchar *);
+		if (!key)
+		{
+			break;
+		}
+
+		type = va_arg(argp, int);
+
+		/* Interpret variadic arguments. */
+		switch (type)
+		{
+			case MSIM_TYPE_INTEGER: 
+			case MSIM_TYPE_BOOLEAN: 
+				msg = msim_msg_append(msg, key, type, GUINT_TO_POINTER(va_arg(argp, int)));
+				break;
+				
+			case MSIM_TYPE_STRING:
+				value = va_arg(argp, char *);
+
+				g_return_val_if_fail(value != NULL, FALSE);
+
+				msg = msim_msg_append(msg, key, type, value);
+				break;
+
+			case MSIM_TYPE_BINARY:
+				gs = va_arg(argp, GString *);
+
+				g_return_val_if_fail(gs != NULL, FALSE);
+
+				/* msim_msg_free() will free this GString the caller created. */
+				msg = msim_msg_append(msg, key, type, gs);
+				break;
+
+			default:
+				purple_debug_info("msim", "msim_send: unknown type %d (%c)\n", type, type);
+				break;
+		}
+	} while(key);
+	va_end(argp);	
+
+	return msg;
+}
+
+
+/** Clone an individual element.
+ *
+ * @param data MsimMessageElement * to clone.
+ * @param user_data Pointer to MsimMessage * to add cloned element to.
+ */
+static void msim_msg_clone_element(gpointer data, gpointer user_data)
+{
+	MsimMessageElement *elem;
+	MsimMessage **new;
+	gpointer new_data;
+
+	elem = (MsimMessageElement *)data;
+	new = (MsimMessage **)user_data;
+
+	switch (elem->type)
+	{
+		case MSIM_TYPE_BOOLEAN:
+		case MSIM_TYPE_INTEGER:
+			new_data = elem->data;
+			break;
+
+		case MSIM_TYPE_RAW:
+		case MSIM_TYPE_STRING:
+			new_data = g_strdup((gchar *)elem->data);
+			break;
+
+		case MSIM_TYPE_BINARY:
+			{
+				GString *gs;
+
+				gs = (GString *)elem->data;
+
+				new_data = g_string_new_len(gs->str, gs->len);
+			}
+			break;
+		/* TODO: other types */
+		default:
+			purple_debug_info("msim", "msim_msg_clone_element: unknown type %d (%c)\n", elem->type, elem->type);
+			g_return_if_fail(NULL);
+	}
+
+	/* Append cloned data. Note that the 'name' field is a static string, so it
+	 * never needs to be copied nor freed. */
+	*new = msim_msg_append(*new, elem->name, elem->type, new_data);
+}
+
+/** Clone an existing MsimMessage. 
+ *
+ * @return Cloned message; caller should free with msim_msg_free().
+ */
+MsimMessage *msim_msg_clone(MsimMessage *old)
+{
+	MsimMessage *new;
+
+	if (old == NULL)
+		return NULL;
+
+	new = msim_msg_new(FALSE);
+
+	g_list_foreach(old, msim_msg_clone_element, &new);
+
+	return new;
+}
+
+/** Free an individual message element. 
+ *
+ * @param data MsimMessageElement * to free.
+ * @param user_data Not used; required to match g_list_foreach() callback prototype.
+ */
+static void msim_msg_free_element(gpointer data, gpointer user_data)
+{
+	MsimMessageElement *elem;
+
+	elem = (MsimMessageElement *)data;
+
+	switch (elem->type)
+	{
+		case MSIM_TYPE_BOOLEAN:
+		case MSIM_TYPE_INTEGER:
+			/* Integer value stored in gpointer - no need to free(). */
+			break;
+
+		case MSIM_TYPE_RAW:
+		case MSIM_TYPE_STRING:
+			/* Always free strings - caller should have g_strdup()'d if
+			 * string was static or temporary and not to be freed. */
+			g_free(elem->data);
+			break;
+
+		case MSIM_TYPE_BINARY:
+			/* Free the GString itself and the binary data. */
+			g_string_free((GString *)elem->data, TRUE);
+			break;
+
+		case MSIM_TYPE_DICTIONARY:
+			/* TODO: free dictionary */
+			break;
+			
+		case MSIM_TYPE_LIST:
+			/* TODO: free list */
+			break;
+
+		default:
+			purple_debug_info("msim", "msim_msg_free_element: not freeing unknown type %d (%c)\n",
+					elem->type, elem->type);
+			break;
+	}
+
+	g_free(elem);
+}
+
+/** Free a complete message. */
+void msim_msg_free(MsimMessage *msg)
+{
+	if (!msg)
+	{
+		/* already free as can be */
+		return;
+	}
+
+	g_list_foreach(msg, msim_msg_free_element, NULL);
+	g_list_free(msg);
+}
+
+/** Send an existing MsimMessage. */
+gboolean msim_msg_send(MsimSession *session, MsimMessage *msg)
+{
+	gchar *raw;
+	gboolean success;
+	
+	raw = msim_msg_pack(msg);
+	success = msim_send_raw(session, raw);
+	g_free(raw);
+
+	msim_msg_dump("msim_msg_send()ing %s\n", msg);
+	
+	return success;
+}
+
+/**
+ *
+ * Send a message to the server, whose contents is specified using 
+ * variable arguments.
+ *
+ * @param session
+ * @param ... A sequence of gchar* key/type/value triplets, terminated with NULL. 
+ *
+ * This function exists for coding convenience: it allows a message to be created
+ * and sent in one line of code. Internally it calls msim_msg_send(). 
+ *
+ * IMPORTANT: See msim_msg_append() documentation for details on element types.
+ *
+ */
+gboolean msim_send(MsimSession *session, ...)
+{
+	gboolean success;
+	MsimMessage *msg;
+	va_list argp;
+    
+	va_start(argp, session);
+	msg = msim_msg_new_v(argp);
+
+	/* Actually send the message. */
+	success = msim_msg_send(session, msg);
+
+	/* Cleanup. */
+	msim_msg_free(msg);
+
+	return success;
+}
+
+/** Create a new MsimMessageElement * - must be g_free()'d. 
+ *
+ * For internal use; users probably want msim_msg_append() or msim_msg_insert_before(). 
+ */
+static MsimMessageElement *msim_msg_element_new(const gchar *name, MsimMessageType type, gpointer data)
+{
+	MsimMessageElement *elem;
+
+	elem = g_new0(MsimMessageElement, 1);
+
+	elem->name = name;
+	elem->type = type;
+	elem->data = data;
+
+	return elem;
+}
+
+
+/** Append a new element to a message. 
+ *
+ * @param name Textual name of element (static string, neither copied nor freed).
+ * @param type An MSIM_TYPE_* code.
+ * @param data Pointer to data, see below.
+ *
+ * @return The new message - must be assigned to as with GList*. For example:
+ *
+ * 		msg = msim_msg_append(msg, ...)
+ *
+ * The data parameter depends on the type given:
+ *
+ * * MSIM_TYPE_INTEGER: Use GUINT_TO_POINTER(x).
+ *
+ * * MSIM_TYPE_BINARY: Same as integer, non-zero is TRUE and zero is FALSE.
+ *
+ * * MSIM_TYPE_STRING: gchar *. The data WILL BE FREED - use g_strdup() if needed.
+ *
+ * * MSIM_TYPE_RAW: gchar *. The data WILL BE FREED - use g_strdup() if needed.
+ *
+ * * MSIM_TYPE_BINARY: g_string_new_len(data, length). The data AND GString will be freed.
+ *
+ * * MSIM_TYPE_DICTIONARY: TODO
+ *
+ * * MSIM_TYPE_LIST: TODO
+ *
+ * */
+MsimMessage *msim_msg_append(MsimMessage *msg, const gchar *name, MsimMessageType type, gpointer data)
+{
+	return g_list_append(msg, msim_msg_element_new(name, type, data));
+}
+
+/** Insert a new element into a message, before the given element name.
+ *
+ * @param name_before Name of the element to insert the new element before. If 
+ * 					  could not be found or NULL, new element will be inserted at end.
+ *
+ * See msim_msg_append() for usage of other parameters, and an important note about return value.
+ */
+MsimMessage *msim_msg_insert_before(MsimMessage *msg, const gchar *name_before, const gchar *name, MsimMessageType type, gpointer data)
+{
+	MsimMessageElement *new_elem;
+	GList *node_before;
+
+	new_elem = msim_msg_element_new(name, type, data);	
+
+	node_before = msim_msg_get_node(msg, name_before);
+
+	return g_list_insert_before(msg, node_before, new_elem);
+}
+
+/** Pack a string using the given GFunc and seperator.
+ * Used by msim_msg_dump() and msim_msg_pack().
+ */
+gchar *msim_msg_pack_using(MsimMessage *msg, GFunc gf, const gchar *sep, const gchar *begin, const gchar *end)
+{
+	gchar **strings;
+	gchar **strings_tmp;
+	gchar *joined;
+	gchar *final;
+	int i;
+
+	g_return_val_if_fail(msg != NULL, NULL);
+
+	/* Add one for NULL terminator for g_strjoinv(). */
+	strings = (gchar **)g_new0(gchar *, g_list_length(msg) + 1);
+
+	strings_tmp = strings;
+	g_list_foreach(msg, gf, &strings_tmp);
+
+	joined = g_strjoinv(sep, strings);
+	final = g_strconcat(begin, joined, end, NULL);
+	g_free(joined);
+
+	/* Clean up. */
+	for (i = 0; i < g_list_length(msg); ++i)
+	{
+		g_free(strings[i]);
+	}
+
+	g_free(strings);
+
+	return final;
+}
+/** Store a human-readable string describing the element.
+ *
+ * @param data Pointer to an MsimMessageElement.
+ * @param user_data 
+ */
+static void msim_msg_debug_string_element(gpointer data, gpointer user_data)
+{
+	MsimMessageElement *elem;
+	gchar *string;
+	GString *gs;
+	gchar *binary;
+	gchar ***items;	 	/* wow, a pointer to a pointer to a pointer */
+
+	elem = (MsimMessageElement *)data;
+	items = user_data;
+
+	switch (elem->type)
+	{
+		case MSIM_TYPE_INTEGER:
+			string = g_strdup_printf("%s(integer): %d", elem->name, GPOINTER_TO_UINT(elem->data));
+			break;
+
+		case MSIM_TYPE_RAW:
+			string = g_strdup_printf("%s(raw): %s", elem->name, (gchar *)elem->data);
+			break;
+
+		case MSIM_TYPE_STRING:
+			string = g_strdup_printf("%s(string): %s", elem->name, (gchar *)elem->data);
+			break;
+
+		case MSIM_TYPE_BINARY:
+			gs = (GString *)elem->data;
+			binary = purple_base64_encode((guchar*)gs->str, gs->len);
+			string = g_strdup_printf("%s(binary, %d bytes): %s", elem->name, (int)gs->len, binary);
+			g_free(binary);
+			break;
+
+		case MSIM_TYPE_BOOLEAN:
+			string = g_strdup_printf("%s(boolean): %s", elem->name,
+					GPOINTER_TO_UINT(elem->data) ? "TRUE" : "FALSE");
+			break;
+
+		case MSIM_TYPE_DICTIONARY:
+			/* TODO: provide human-readable output of dictionary. */
+			string = g_strdup_printf("%s(dict): TODO", elem->name);
+			break;
+			
+		case MSIM_TYPE_LIST:
+			/* TODO: provide human-readable output of list. */
+			string = g_strdup_printf("%s(list): TODO", elem->name);
+			break;
+
+		default:
+			string = g_strdup_printf("%s(unknown type %d (%c)", elem->name, elem->type, elem->type);
+			break;
+	}
+
+	**items = string;
+	++(*items);
+}
+
+/** Print a human-readable string of the message to Purple's debug log.
+ *
+ * @param fmt_string A static string, in which '%s' will be replaced.
+ */
+void msim_msg_dump(const gchar *fmt_string, MsimMessage *msg)
+{
+	gchar *debug_str;
+
+	if (!msg)
+	{
+		debug_str = g_strdup("<MsimMessage: empty>");
+	} else {
+		debug_str = msim_msg_pack_using(msg, msim_msg_debug_string_element, 
+				"\n", "<MsimMessage: \n", "\n/MsimMessage>");
+	}
+
+	purple_debug_info("msim", fmt_string, debug_str);
+
+	g_free(debug_str);
+}
+
+/** Return a message element data as a new string for a raw protocol message, converting from other types (integer, etc.) if necessary.
+ *
+ * @return const gchar * The data as a string, or NULL. Caller must g_free().
+ *
+ * Returns a string suitable for inclusion in a raw protocol message, not necessarily
+ * optimal for human consumption. For example, strings are escaped. Use 
+ * msim_msg_get_string() if you want a string, which in some cases is same as this.
+ */
+static gchar *msim_msg_pack_element_data(MsimMessageElement *elem)
+{
+	switch (elem->type)
+	{
+		case MSIM_TYPE_INTEGER:
+			return g_strdup_printf("%d", GPOINTER_TO_UINT(elem->data));
+
+		case MSIM_TYPE_RAW:
+			/* Not un-escaped - this is a raw element, already escaped if necessary. */
+			return (gchar *)g_strdup((gchar *)elem->data);
+
+		case MSIM_TYPE_STRING:
+			/* Strings get escaped. msim_escape() creates a new string. */
+			return msim_escape((gchar *)elem->data);
+
+		case MSIM_TYPE_BINARY:
+			{
+				GString *gs;
+
+				gs = (GString *)elem->data;
+				/* Do not escape! */
+				return purple_base64_encode((guchar *)gs->str, gs->len);
+			}
+
+		case MSIM_TYPE_BOOLEAN:
+			/* Not used by the wire protocol * -- see msim_msg_pack_element. */
+			return NULL;
+
+		case MSIM_TYPE_DICTIONARY:
+			/* TODO: pack using k=v\034k2=v2\034... */
+			return NULL;
+			
+		case MSIM_TYPE_LIST:
+			/* TODO: pack using a|b|c|d|... */
+			return NULL;
+
+		default:
+			purple_debug_info("msim", "field %s, unknown type %d (%c)\n", elem->name, elem->type, elem->type);
+			return NULL;
+	}
+}
+
+/** Pack an element into its protocol representation. 
+ *
+ * @param data Pointer to an MsimMessageElement.
+ * @param user_data Pointer to a gchar ** array of string items.
+ *
+ * Called by msim_msg_pack(). Will pack the MsimMessageElement into
+ * a part of the protocol string and append it to the array. Caller
+ * is responsible for creating array to correct dimensions, and
+ * freeing each string element of the array added by this function.
+ */
+static void msim_msg_pack_element(gpointer data, gpointer user_data)
+{
+	MsimMessageElement *elem;
+	gchar *string, *data_string;
+	gchar ***items;
+
+	elem = (MsimMessageElement *)data;
+	items = user_data;
+
+	/* Exclude elements beginning with '_' from packed protocol messages. */
+	if (elem->name[0] == '_')
+	{
+		return;
+	}
+
+	data_string = msim_msg_pack_element_data(elem);
+
+	switch (elem->type)
+	{
+		/* These types are represented by key name/value pairs (converted above). */
+		case MSIM_TYPE_INTEGER:
+		case MSIM_TYPE_RAW:
+		case MSIM_TYPE_STRING:
+		case MSIM_TYPE_BINARY:
+		case MSIM_TYPE_DICTIONARY:
+		case MSIM_TYPE_LIST:
+			string = g_strconcat(elem->name, "\\", data_string, NULL);
+			break;
+
+		/* Boolean is represented by absence or presence of name. */
+		case MSIM_TYPE_BOOLEAN:
+			if (GPOINTER_TO_UINT(elem->data))
+			{
+				/* True - leave in, with blank value. */
+				string = g_strdup_printf("%s\\", elem->name);
+			} else {
+				/* False - leave out. */
+				string = g_strdup("");
+			}
+			break;
+
+		default:
+			g_free(data_string);
+			g_return_if_fail(FALSE);
+			break;
+	}
+
+	g_free(data_string);
+
+	**items = string;
+	++(*items);
+}
+
+
+/** Return a packed string suitable for sending over the wire.
+ *
+ * @return A string. Caller must g_free().
+ */
+gchar *msim_msg_pack(MsimMessage *msg)
+{
+	g_return_val_if_fail(msg != NULL, NULL);
+
+	return msim_msg_pack_using(msg, msim_msg_pack_element, "\\", "\\", "\\final\\");
+}
+
+/** 
+ * Parse a raw protocol message string into a MsimMessage *.
+ *
+ * @param raw The raw message string to parse, will be g_free()'d.
+ *
+ * @return MsimMessage *. Caller should msim_msg_free() when done.
+ */
+MsimMessage *msim_parse(gchar *raw)
+{
+	MsimMessage *msg;
+    gchar *token;
+    gchar **tokens;
+    gchar *key;
+    gchar *value;
+    int i;
+
+    g_return_val_if_fail(raw != NULL, NULL);
+
+    purple_debug_info("msim", "msim_parse: got <%s>\n", raw);
+
+    key = NULL;
+
+    /* All messages begin with a \. */
+    if (raw[0] != '\\' || raw[1] == 0)
+    {
+        purple_debug_info("msim", "msim_parse: incomplete/bad string, "
+                "missing initial backslash: <%s>\n", raw);
+        /* XXX: Should we try to recover, and read to first backslash? */
+
+        g_free(raw);
+        return NULL;
+    }
+
+    msg = msim_msg_new(FALSE);
+
+    for (tokens = g_strsplit(raw + 1, "\\", 0), i = 0; 
+            (token = tokens[i]);
+            i++)
+    {
+#ifdef MSIM_DEBUG_PARSE
+        purple_debug_info("msim", "tok=<%s>, i%2=%d\n", token, i % 2);
+#endif
+        if (i % 2)
+        {
+			/* Odd-numbered ordinal is a value. */
+
+			value = token;
+		
+			/* Incoming protocol messages get tagged as MSIM_TYPE_RAW, which
+			 * represents an untyped piece of data. msim_msg_get_* will
+			 * convert to appropriate types for caller, and handle unescaping if needed. */
+			msg = msim_msg_append(msg, g_strdup(key), MSIM_TYPE_RAW, g_strdup(value));
+#ifdef MSIM_DEBUG_PARSE
+			purple_debug_info("msim", "insert string: |%s|=|%s|\n", key, value);
+#endif
+        } else {
+			/* Even numbered indexes are key names. */
+            key = token;
+        }
+    }
+    g_strfreev(tokens);
+
+    /* Can free now since all data was copied to hash key/values */
+    g_free(raw);
+
+    return msg;
+}
+
+/**
+ * Parse a \x1c-separated "dictionary" of key=value pairs into a hash table.
+ *
+ * @param body_str The text of the dictionary to parse. Often the
+ *                  value for the 'body' field.
+ *
+ * @return Hash table of the keys and values. Must g_hash_table_destroy() when done.
+ */
+GHashTable *msim_parse_body(const gchar *body_str)
+{
+    GHashTable *table;
+    gchar *item;
+    gchar **items;
+    gchar **elements;
+    guint i;
+
+    g_return_val_if_fail(body_str != NULL, NULL);
+
+    table = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, g_free);
+ 
+    for (items = g_strsplit(body_str, "\x1c", 0), i = 0; 
+        (item = items[i]);
+        i++)
+    {
+        gchar *key, *value;
+
+        elements = g_strsplit(item, "=", 2);
+
+        key = elements[0];
+        if (!key)
+        {
+            purple_debug_info("msim", "msim_parse_body(%s): null key\n", 
+					body_str);
+            g_strfreev(elements);
+            break;
+        }
+
+        value = elements[1];
+        if (!value)
+        {
+            purple_debug_info("msim", "msim_parse_body(%s): null value\n", 
+					body_str);
+            g_strfreev(elements);
+            break;
+        }
+
+#ifdef MSIM_DEBUG_PARSE
+        purple_debug_info("msim", "-- %s: %s\n", key, value);
+#endif
+
+        /* XXX: This overwrites duplicates. */
+        /* TODO: make the GHashTable values be GList's, and append to the list if 
+         * there is already a value of the same key name. This is important for
+         * the WebChallenge message. */
+        g_hash_table_insert(table, g_strdup(key), g_strdup(value));
+        
+        g_strfreev(elements);
+    }
+
+    g_strfreev(items);
+
+    return table;
+}
+
+/** Search for and return the node in msg, matching name, or NULL. 
+ *
+ * @param msg Message to search within.
+ * @param name Field name to search for.
+ *
+ * @return The GList * node for the MsimMessageElement with the given name, or NULL if not found or name is NULL.
+ *
+ * For internal use - users probably want to use msim_msg_get() to
+ * access the MsimMessageElement *, instead of the GList * container.
+ *
+ */
+static GList *msim_msg_get_node(MsimMessage *msg, const gchar *name)
+{
+	GList *i;
+
+	if (!name)
+	{
+		return NULL;
+	}
+
+	/* Linear search for the given name. O(n) but n is small. */
+	for (i = g_list_first(msg); i != NULL; i = g_list_next(i))
+	{
+		MsimMessageElement *elem;
+
+		elem = i->data;
+		g_return_val_if_fail(elem != NULL, NULL);
+
+		if (strcmp(elem->name, name) == 0)
+			return i;
+	}
+	return NULL;
+}
+
+
+
+/** Return the first MsimMessageElement * with given name in the MsimMessage *. 
+ *
+ * @param name Name to search for.
+ *
+ * @return MsimMessageElement * matching name, or NULL.
+ *
+ * Note: useful fields of MsimMessageElement are 'data' and 'type', which
+ * you can access directly. But it is often more convenient to use
+ * another msim_msg_get_* that converts the data to what type you want.
+ */
+MsimMessageElement *msim_msg_get(MsimMessage *msg, const gchar *name)
+{
+	GList *node;
+
+	node = msim_msg_get_node(msg, name);
+	if (node)
+		return (MsimMessageElement *)node->data;
+	else
+		return NULL;
+}
+
+/** Return the data of an element of a given name, as a string.
+ *
+ * @param name Name of element.
+ *
+ * @return gchar * The data as a string. Caller must g_free().
+ *
+ * Note that msim_msg_pack_element_data() is similar, but returns a string
+ * for inclusion into a raw protocol string (escaped and everything).
+ * This function unescapes the string for you, if needed.
+ */
+gchar *msim_msg_get_string(MsimMessage *msg, const gchar *name)
+{
+	MsimMessageElement *elem;
+
+	elem = msim_msg_get(msg, name);
+	if (!elem)
+		return NULL;
+
+	switch (elem->type)
+	{
+		case MSIM_TYPE_INTEGER:
+			return g_strdup_printf("%d", GPOINTER_TO_UINT(elem->data));
+
+		case MSIM_TYPE_RAW:
+			/* Raw element from incoming message - if its a string, it'll
+			 * be escaped. */
+			return msim_unescape((gchar *)elem->data);
+
+		case MSIM_TYPE_STRING:
+			/* Already unescaped. */
+			return (gchar *)elem->data;
+
+		default:
+			purple_debug_info("msim", "msim_msg_get_string: type %d unknown, name %s\n",
+					elem->type, name);
+			return NULL;
+	}
+}
+
+/** Return the data of an element of a given name, as an integer.
+ *
+ * @param name Name of element.
+ *
+ * @return guint Numeric representation of data, or 0 if could not be converted / not found.
+ *
+ * Useful to obtain an element's data if you know it should be an integer,
+ * even if it is not stored as an MSIM_TYPE_INTEGER. MSIM_TYPE_STRING will
+ * be converted handled correctly, for example.
+ */
+guint msim_msg_get_integer(MsimMessage *msg, const gchar *name)
+{
+	MsimMessageElement *elem;
+
+	elem = msim_msg_get(msg, name);
+
+	if (!elem)
+		return 0;
+
+	switch (elem->type)
+	{
+		case MSIM_TYPE_INTEGER:
+			return GPOINTER_TO_UINT(elem->data);
+
+		case MSIM_TYPE_RAW:
+		case MSIM_TYPE_STRING:
+			/* TODO: find out if we need larger integers */
+			return (guint)atoi((gchar *)elem->data);
+
+		default:
+			return 0;
+	}
+}
+
+/** Return the data of an element of a given name, as a binary GString.
+ *
+ * @param binary_data A pointer to a new pointer, which will be filled in with the binary data. CALLER MUST g_free().
+ *
+ * @param binary_length A pointer to an integer, which will be set to the binary data length.
+ *
+ * @return TRUE if successful, FALSE if not.
+ */
+gboolean msim_msg_get_binary(MsimMessage *msg, const gchar *name, gchar **binary_data, gsize *binary_length)
+{
+	MsimMessageElement *elem;
+
+	elem = msim_msg_get(msg, name);
+
+	switch (elem->type)
+	{
+		case MSIM_TYPE_RAW:
+			 /* Incoming messages are tagged with MSIM_TYPE_RAW, and
+			 * converted appropriately. They can still be "strings", just they won't
+			 * be tagged as MSIM_TYPE_STRING (as MSIM_TYPE_STRING is intended to be used
+			 * by msimprpl code for things like instant messages - stuff that should be
+			 * escaped if needed). DWIM.
+			 */
+	
+			/* Previously, incoming messages were stored as MSIM_TYPE_STRING.
+			 * This was fine for integers and strings, since they can easily be
+			 * converted in msim_get_*, as desirable. However, it does not work
+			 * well for binary strings. Consider:
+			 *
+			 * If incoming base64'd elements were tagged as MSIM_TYPE_STRING.
+			 * msim_msg_get_binary() sees MSIM_TYPE_STRING, base64 decodes, returns.
+			 * everything is fine.
+			 * But then, msim_send() is called on the incoming message, which has
+			 * a base64'd MSIM_TYPE_STRING that really is encoded binary. The values
+			 * will be escaped since strings are escaped, and / becomes /2; no good.
+			 *
+			 */
+			*binary_data = (gchar *)purple_base64_decode((const gchar *)elem->data, binary_length);
+			return TRUE;
+
+		case MSIM_TYPE_BINARY:
+			{
+				GString *gs;
+
+				gs = (GString *)elem->data;
+
+				/* Duplicate data, so caller can g_free() it. */
+				*binary_data = g_new0(char, gs->len);
+				memcpy(*binary_data, gs->str, gs->len);
+
+				*binary_length = gs->len;
+
+				return TRUE;
+			}
+
+
+			/* Rejected because if it isn't already a GString, have to g_new0 it and
+			 * then caller has to ALSO free the GString! 
+			 *
+			 * return (GString *)elem->data; */
+
+		default:
+			purple_debug_info("msim", "msim_msg_get_binary: unhandled type %d for key %s\n",
+					elem->type, name);
+			return FALSE;
+	}
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libpurple/protocols/myspace/message.h	Mon Jun 18 01:48:35 2007 +0000
@@ -0,0 +1,78 @@
+/** MySpaceIM protocol messages
+ *
+ * \author Jeff Connelly
+ *
+ * Copyright (C) 2007, Jeff Connelly <jeff2@homing.pidgin.im>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+#ifndef _MYSPACE_MESSAGE_H
+#define _MYSPACE_MESSAGE_H
+
+#include <glib.h>
+
+/* Types */
+#define MsimMessage GList		/* #define instead of typedef to avoid casting */
+typedef struct _MsimMessageElement
+{
+	const gchar *name;				/**< Textual name of element. */
+	guint type;						/**< MSIM_TYPE_* code. */
+	gpointer data;					/**< Pointer to data, or GUINT_TO_POINTER for int/bool. */
+} MsimMessageElement;
+
+typedef gchar MsimMessageType;
+
+/* Protocol field types */
+#define MSIM_TYPE_RAW			'-'
+#define MSIM_TYPE_INTEGER		'i'
+#define MSIM_TYPE_STRING		's'
+#define MSIM_TYPE_BINARY		'b'
+#define MSIM_TYPE_BOOLEAN		'f'
+#define MSIM_TYPE_DICTIONARY	'd'
+#define MSIM_TYPE_LIST			'l'
+
+MsimMessage *msim_msg_new(gboolean not_empty, ...);
+/* No sentinel attribute, because can leave off varargs if not_empty is FALSE. */
+
+MsimMessage *msim_msg_clone(MsimMessage *old);
+void msim_msg_free(MsimMessage *msg);
+MsimMessage *msim_msg_append(MsimMessage *msg, const gchar *name, MsimMessageType type, gpointer data);
+MsimMessage *msim_msg_insert_before(MsimMessage *msg, const gchar *name_before, const gchar *name, MsimMessageType type, gpointer data);
+void msim_msg_dump(const char *fmt_string, MsimMessage *msg);
+gchar *msim_msg_pack(MsimMessage *msg);
+
+/* Defined in myspace.h */
+struct _MsimSession;
+
+gboolean msim_send(struct _MsimSession *session, ...) 
+#ifdef __GNUC__
+	/* Cause gcc to emit "a missing sentinel in function call" if forgot
+	 * to write NULL as last, terminating parameter. */
+	__attribute__((__sentinel__(0)))
+#endif
+	;
+
+gboolean msim_msg_send(struct _MsimSession *session, MsimMessage *msg);
+
+MsimMessage *msim_parse(gchar *raw);
+GHashTable *msim_parse_body(const gchar *body_str);
+
+MsimMessageElement *msim_msg_get(MsimMessage *msg, const gchar *name);
+gchar *msim_msg_get_string(MsimMessage *msg, const gchar *name);
+guint msim_msg_get_integer(MsimMessage *msg, const gchar *name);
+gboolean msim_msg_get_binary(MsimMessage *msg, const gchar *name, gchar **binary_data, gsize *binary_length);
+
+#endif /* _MYSPACE_MESSAGE_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libpurple/protocols/myspace/myspace.c	Mon Jun 18 01:48:35 2007 +0000
@@ -0,0 +1,2235 @@
+/* MySpaceIM Protocol Plugin
+ *
+ * \author Jeff Connelly
+ *
+ * Copyright (C) 2007, Jeff Connelly <jeff2@homing.pidgin.im>
+ *
+ * Based on Purple's "C Plugin HOWTO" hello world example.
+ *
+ * Code also drawn from mockprpl:
+ *  http://snarfed.org/space/purple+mock+protocol+plugin
+ *  Copyright (C) 2004-2007, Ryan Barrett <mockprpl@ryanb.org>
+ *
+ * and some constructs also based on existing Purple plugins, which are:
+ *   Copyright (C) 2003, Robbert Haarman <purple@inglorion.net>
+ *   Copyright (C) 2003, Ethan Blanton <eblanton@cs.purdue.edu>
+ *   Copyright (C) 2000-2003, Rob Flynn <rob@tgflinux.com>
+ *   Copyright (C) 1998-1999, Mark Spencer <markster@marko.net>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+#define PURPLE_PLUGIN
+
+#include "message.h"
+#include "persist.h"
+#include "myspace.h"
+
+/** 
+ * Load the plugin.
+ */
+gboolean msim_load(PurplePlugin *plugin)
+{
+#ifdef MSIM_USE_PURPLE_RC4
+	/* If compiled to use RC4 from libpurple, check if it is really there. */
+	if (!purple_ciphers_find_cipher("rc4"))
+	{
+		purple_debug_error("msim", "compiled with MSIM_USE_PURPLE_RC4 but rc4 not in libpurple - not loading MySpaceIM plugin!\n");
+		purple_notify_error(plugin, _("Missing Cipher"), 
+				_("The RC4 cipher could not be found"),
+				_("Recompile without MSIM_USE_PURPLE_RC4, or upgrade "
+					"to a libpurple with RC4 support (>= 2.0.1). MySpaceIM "
+					"plugin will not be loaded."));
+		return FALSE;
+	}
+#endif
+	return TRUE;
+}
+
+/**
+ * Get possible user status types. Based on mockprpl.
+ *
+ * @return GList of status types.
+ */
+GList *msim_status_types(PurpleAccount *acct)
+{
+    GList *types;
+    PurpleStatusType *status;
+
+    purple_debug_info("myspace", "returning status types\n");
+
+    types = NULL;
+
+	/* TODO: Fix these:
+	 *
+	 * g_log: purple_presence_get_active_status: assertion `presence != NULL' failed
+	 * g_log: purple_status_get_name: assertion `status != NULL' failed
+	 * [...]
+	 *
+	 * and 
+	 * g_log: purple_presence_set_status_active: assertion `status != NULL' failed
+	 * [...]
+	 */
+    status = purple_status_type_new_full(PURPLE_STATUS_AVAILABLE, NULL, NULL, FALSE, TRUE, FALSE);
+    types = g_list_append(types, status);
+
+    status = purple_status_type_new_full(PURPLE_STATUS_AWAY, NULL, NULL, FALSE, TRUE, FALSE);
+    types = g_list_append(types, status);
+
+    status = purple_status_type_new_full(PURPLE_STATUS_OFFLINE, NULL, NULL, FALSE, TRUE, FALSE);
+    types = g_list_append(types, status);
+
+    status = purple_status_type_new_full(PURPLE_STATUS_INVISIBLE, NULL, NULL, FALSE, TRUE, FALSE);
+    types = g_list_append(types, status);
+
+    return types;
+}
+
+/**
+ * Return the icon name for a buddy and account.
+ *
+ * @param acct The account to find the icon for, or NULL for protocol icon.
+ * @param buddy The buddy to find the icon for, or NULL for the account icon.
+ *
+ * @return The base icon name string.
+ */
+const gchar *msim_list_icon(PurpleAccount *acct, PurpleBuddy *buddy)
+{
+    /* Use a MySpace icon submitted by hbons at
+     * http://developer.pidgin.im/wiki/MySpaceIM. */
+    return "myspace";
+}
+
+/**
+ * Unescape a protocol message.
+ *
+ * @return The unescaped message. Caller must g_free().
+ */
+gchar *msim_unescape(const gchar *msg)
+{
+	/* TODO: make more elegant, refactor with msim_escape */
+	gchar *tmp, *ret;
+	
+	tmp = str_replace(msg, "/1", "/");
+	ret = str_replace(tmp, "/2", "\\");
+	g_free(tmp);
+	return ret;
+}
+
+/**
+ * Escape a protocol message.
+ *
+ * @return The escaped message. Caller must g_free().
+ */
+gchar *msim_escape(const gchar *msg)
+{
+	/* TODO: make more elegant, refactor with msim_unescape */
+	gchar *tmp, *ret;
+	
+	tmp = str_replace(msg, "/", "/1");
+	ret = str_replace(tmp, "\\", "/2");
+	g_free(tmp);
+
+	return ret;
+}
+
+/**
+ * Replace 'old' with 'new' in 'str'.
+ *
+ * @param str The original string.
+ * @param old The substring of 'str' to replace.
+ * @param new The replacement for 'old' within 'str'.
+ *
+ * @return A _new_ string, based on 'str', with 'old' replaced
+ * 		by 'new'. Must be g_free()'d by caller.
+ *
+ * This string replace method is based on
+ * http://mail.gnome.org/archives/gtk-app-devel-list/2000-July/msg00201.html
+ *
+ */
+gchar *str_replace(const gchar *str, const gchar *old, const gchar *new)
+{
+	gchar **items;
+	gchar *ret;
+
+	items = g_strsplit(str, old, -1);
+	ret = g_strjoinv(new, items);
+	g_free(items);
+	return ret;
+}
+
+
+
+
+#ifdef MSIM_DEBUG_MSG
+void print_hash_item(gpointer key, gpointer value, gpointer user_data)
+{
+    purple_debug_info("msim", "%s=%s\n", (gchar *)key, (gchar *)value);
+}
+#endif
+
+/** 
+ * Send raw data to the server.
+ *
+ * @param session 
+ * @param msg The raw data to send.
+ *
+ * @return TRUE if succeeded, FALSE if not.
+ *
+ */
+gboolean msim_send_raw(MsimSession *session, const gchar *msg)
+{
+	int total_bytes_sent, total_bytes;
+    
+	purple_debug_info("msim", "msim_send_raw: writing <%s>\n", msg);
+
+    g_return_val_if_fail(MSIM_SESSION_VALID(session), FALSE);
+    g_return_val_if_fail(msg != NULL, FALSE);
+
+
+	/* Loop until all data is sent, or a failure occurs. */
+	total_bytes_sent = 0;
+	total_bytes = strlen(msg);
+	do
+	{
+		int bytes_sent;
+
+		bytes_sent = send(session->fd, msg + total_bytes_sent, 
+			total_bytes - total_bytes_sent, 0);
+
+		if (bytes_sent < 0)
+		{
+			purple_debug_info("msim", "msim_send_raw(%s): send() failed: %s\n",
+					msg, g_strerror(errno));
+			return FALSE;
+		}
+		total_bytes_sent += bytes_sent;
+
+	} while(total_bytes_sent < total_bytes);
+	return TRUE;
+}
+
+/** 
+ * Start logging in to the MSIM servers.
+ * 
+ * @param acct Account information to use to login.
+ */
+void msim_login(PurpleAccount *acct)
+{
+    PurpleConnection *gc;
+    const gchar *host;
+    int port;
+
+    g_return_if_fail(acct != NULL);
+
+    purple_debug_info("myspace", "logging in %s\n", acct->username);
+
+    gc = purple_account_get_connection(acct);
+    gc->proto_data = msim_session_new(acct);
+
+    /* 1. connect to server */
+    purple_connection_update_progress(gc, _("Connecting"),
+                                  0,   /* which connection step this is */
+                                  4);  /* total number of steps */
+
+    host = purple_account_get_string(acct, "server", MSIM_SERVER);
+    port = purple_account_get_int(acct, "port", MSIM_PORT);
+
+    /* From purple.sf.net/api:
+     * """Note that this function name can be misleading--although it is called 
+     * "proxy connect," it is used for establishing any outgoing TCP connection, 
+     * whether through a proxy or not.""" */
+
+    /* Calls msim_connect_cb when connected. */
+    if (purple_proxy_connect(gc, acct, host, port, msim_connect_cb, gc) == NULL)
+    {
+        /* TODO: try other ports if in auto mode, then save
+         * working port and try that first next time. */
+        purple_connection_error(gc, _("Couldn't create socket"));
+        return;
+    }
+}
+/**
+ * Process a login challenge, sending a response. 
+ *
+ * @param session 
+ * @param msg Login challenge message.
+ *
+ * @return TRUE if successful, FALSE if not
+ */
+gboolean msim_login_challenge(MsimSession *session, MsimMessage *msg) 
+{
+    PurpleAccount *account;
+    const gchar *response;
+	guint response_len;
+	gchar *nc;
+	gsize nc_len;
+
+    g_return_val_if_fail(MSIM_SESSION_VALID(session), FALSE);
+    g_return_val_if_fail(msg != NULL, FALSE);
+
+    g_return_val_if_fail(msim_msg_get_binary(msg, "nc", &nc, &nc_len), FALSE);
+
+    account = session->account;
+
+	g_return_val_if_fail(account != NULL, FALSE);
+
+    purple_connection_update_progress(session->gc, _("Reading challenge"), 1, 4);
+
+    purple_debug_info("msim", "nc is %d bytes, decoded\n", nc_len);
+
+    if (nc_len != 0x40)
+    {
+        purple_debug_info("msim", "bad nc length: %x != 0x40\n", nc_len);
+        purple_connection_error(session->gc, _("Unexpected challenge length from server"));
+        return FALSE;
+    }
+
+    purple_connection_update_progress(session->gc, _("Logging in"), 2, 4);
+
+    response = msim_compute_login_response(nc, account->username, account->password, &response_len);
+
+    g_free(nc);
+
+	return msim_send(session, 
+			"login2", MSIM_TYPE_INTEGER, MSIM_AUTH_ALGORITHM,
+			/* This is actually user's email address. */
+			"username", MSIM_TYPE_STRING, g_strdup(account->username),
+			/* GString and gchar * response will be freed in msim_msg_free() in msim_send(). */
+			"response", MSIM_TYPE_BINARY, g_string_new_len(response, response_len),
+			"clientver", MSIM_TYPE_INTEGER, MSIM_CLIENT_VERSION,
+			"reconn", MSIM_TYPE_INTEGER, 0,
+			"status", MSIM_TYPE_INTEGER, 100,
+			"id", MSIM_TYPE_INTEGER, 1,
+			NULL);
+}
+
+#ifndef MSIM_USE_PURPLE_RC4
+/* No RC4 in this version of libpurple, so bring our own. */
+
+/* 
+   Unix SMB/CIFS implementation.
+
+   a partial implementation of RC4 designed for use in the 
+   SMB authentication protocol
+
+   Copyright (C) Andrew Tridgell 1998
+
+   $Id: crypt-rc4.c 12116 2004-09-27 23:29:22Z guy $
+   
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 2 of the License, or
+   (at your option) any later version.
+   
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+   
+   You should have received a copy of the GNU General Public License
+   along with this program; if not, write to the Free Software
+   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+
+   
+   Modified by Jeff Connelly for MySpaceIM Gaim plugin.
+*/
+
+#include <glib.h>
+#include <string.h>
+
+/* Perform RC4 on a block of data using specified key.  "data" is a pointer
+   to the block to be processed.  Output is written to same memory as input,
+   so caller may need to make a copy before calling this function, since
+   the input will be overwritten.  
+   
+   Taken from Samba source code.  Modified to allow us to maintain state
+   between calls to crypt_rc4.
+*/
+
+void crypt_rc4_init(rc4_state_struct *rc4_state, 
+		    const guchar *key, int key_len)
+{
+  int ind;
+  unsigned gchar j = 0;
+  unsigned gchar *s_box;
+
+  memset(rc4_state, 0, sizeof(rc4_state_struct));
+  s_box = rc4_state->s_box;
+  
+  for (ind = 0; ind < 256; ind++)
+  {
+    s_box[ind] = (guchar)ind;
+  }
+
+  for( ind = 0; ind < 256; ind++)
+  {
+     guchar tc;
+
+     j += (s_box[ind] + key[ind%key_len]);
+
+     tc = s_box[ind];
+     s_box[ind] = s_box[j];
+     s_box[j] = tc;
+  }
+
+}
+
+void crypt_rc4(rc4_state_struct *rc4_state, guchar *data, int data_len)
+{
+  guchar *s_box;
+  guchar index_i;
+  guchar index_j;
+  int ind;
+
+  /* retrieve current state from the state struct (so we can resume where
+     we left off) */
+  index_i = rc4_state->index_i;
+  index_j = rc4_state->index_j;
+  s_box = rc4_state->s_box;
+
+  for( ind = 0; ind < data_len; ind++)
+  {
+    guchar tc;
+    guchar t;
+
+    index_i++;
+    index_j += s_box[index_i];
+
+    tc = s_box[index_i];
+    s_box[index_i] = s_box[index_j];
+    s_box[index_j] = tc;
+
+    t = s_box[index_i] + s_box[index_j];
+    data[ind] = data[ind] ^ s_box[t];
+  }
+
+  /* Store the updated state */
+  rc4_state->index_i = index_i;
+  rc4_state->index_j = index_j;
+}
+
+#endif /* !MSIM_USE_PURPLE_RC4 */
+
+
+/**
+ * Compute the base64'd login challenge response based on username, password, nonce, and IPs.
+ *
+ * @param nonce The base64 encoded nonce ('nc') field from the server.
+ * @param email User's email address (used as login name).
+ * @param password User's cleartext password.
+ * @param response_len Will be written with response length.
+ *
+ * @return Binary login challenge response, ready to send to the server. Must be g_free()'d
+ *         when finished.
+ */
+const gchar *msim_compute_login_response(const gchar nonce[2 * NONCE_SIZE], 
+		const gchar *email, const gchar *password, guint *response_len)
+{
+    PurpleCipherContext *key_context;
+    PurpleCipher *sha1;
+#ifdef MSIM_USE_PURPLE_RC4
+	PurpleCipherContext *rc4;
+#else
+	rc4_state_struct rc4;
+#endif
+
+    guchar hash_pw[HASH_SIZE];
+    guchar key[HASH_SIZE];
+    gchar *password_utf16le;
+    guchar *data;
+	guchar *data_out;
+	size_t data_len, data_out_len;
+	gsize conv_bytes_read, conv_bytes_written;
+	GError *conv_error;
+#ifdef MSIM_DEBUG_LOGIN_CHALLENGE
+	int i;
+#endif
+
+    /* Convert ASCII password to UTF16 little endian */
+    purple_debug_info("msim", "converting password to UTF-16LE\n");
+	conv_error = NULL;
+	password_utf16le = g_convert(password, -1, "UTF-16LE", "UTF-8", 
+			&conv_bytes_read, &conv_bytes_written, &conv_error);
+	g_assert(conv_bytes_read == strlen(password));
+	if (conv_error != NULL)
+	{
+		purple_debug_error("msim", 
+				"g_convert password UTF8->UTF16LE failed: %s",
+				conv_error->message);
+		g_error_free(conv_error);
+	}
+
+    /* Compute password hash */ 
+    purple_cipher_digest_region("sha1", (guchar *)password_utf16le, 
+			conv_bytes_written, sizeof(hash_pw), hash_pw, NULL);
+	g_free(password_utf16le);
+
+#ifdef MSIM_DEBUG_LOGIN_CHALLENGE
+    purple_debug_info("msim", "pwhash = ");
+    for (i = 0; i < sizeof(hash_pw); i++)
+        purple_debug_info("msim", "%.2x ", hash_pw[i]);
+    purple_debug_info("msim", "\n");
+#endif
+
+    /* key = sha1(sha1(pw) + nonce2) */
+    sha1 = purple_ciphers_find_cipher("sha1");
+    key_context = purple_cipher_context_new(sha1, NULL);
+    purple_cipher_context_append(key_context, hash_pw, HASH_SIZE);
+    purple_cipher_context_append(key_context, (guchar *)(nonce + NONCE_SIZE), NONCE_SIZE);
+    purple_cipher_context_digest(key_context, sizeof(key), key, NULL);
+
+#ifdef MSIM_DEBUG_LOGIN_CHALLENGE
+    purple_debug_info("msim", "key = ");
+    for (i = 0; i < sizeof(key); i++)
+    {
+        purple_debug_info("msim", "%.2x ", key[i]);
+    }
+    purple_debug_info("msim", "\n");
+#endif
+
+#ifdef MSIM_USE_PURPLE_RC4
+	rc4 = purple_cipher_context_new_by_name("rc4", NULL);
+
+    /* Note: 'key' variable is 0x14 bytes (from SHA-1 hash), 
+     * but only first 0x10 used for the RC4 key. */
+	purple_cipher_context_set_option(rc4, "key_len", (gpointer)0x10);
+	purple_cipher_context_set_key(rc4, key);
+#endif
+
+    /* TODO: obtain IPs of network interfaces. This is not immediately
+     * important because you can still connect and perform basic
+     * functions of the protocol. There is also a high chance that the addreses
+     * are RFC1918 private, so the servers couldn't do anything with them
+     * anyways except make note of that fact. Probably important for any
+     * kind of direct connection, or file transfer functionality.
+     */
+    /* rc4 encrypt:
+     * nonce1+email+IP list */
+    data_len = NONCE_SIZE + strlen(email) 
+		/* TODO: change to length of IP list */
+		+ 25;
+    data = g_new0(guchar, data_len);
+    memcpy(data, nonce, NONCE_SIZE);
+    memcpy(data + NONCE_SIZE, email, strlen(email));
+    memcpy(data + NONCE_SIZE + strlen(email),
+            /* TODO: IP addresses of network interfaces */
+            "\x00\x00\x00\x00\x05\x7f\x00\x00\x01\x00\x00\x00\x00\x0a\x00\x00\x40\xc0\xa8\x58\x01\xc0\xa8\x3c\x01", 25);
+
+#ifdef MSIM_USE_PURPLE_RC4
+	data_out = g_new0(guchar, data_len);
+
+    purple_cipher_context_encrypt(rc4, (const guchar *)data, 
+			data_len, data_out, &data_out_len);
+	purple_cipher_context_destroy(rc4);
+#else
+	/* Use our own RC4 code */
+	purple_debug_info("msim", "Using non-purple RC4 cipher code in this version\n");
+	crypt_rc4_init(&rc4, key, 0x10);
+	crypt_rc4(&rc4, data, data_len);
+	data_out_len = data_len;
+	data_out = data;
+#endif
+
+	g_assert(data_out_len == data_len);
+
+#ifdef MSIM_DEBUG_LOGIN_CHALLENGE
+    purple_debug_info("msim", "response=<%s>\n", data_out);
+#endif
+
+	*response_len = data_out_len;
+
+    return (const gchar *)data_out;
+}
+
+/**
+ * Schedule an IM to be sent once the user ID is looked up. 
+ *
+ * @param gc Connection.
+ * @param who A user id, email, or username to send the message to.
+ * @param message Instant message text to send.
+ * @param flags Flags.
+ *
+ * @return 1 if successful or postponed, -1 if failed
+ *
+ * Allows sending to a user by username, email address, or userid. If
+ * a username or email address is given, the userid must be looked up.
+ * This function does that by calling msim_postprocess_outgoing().
+ */
+int msim_send_im(PurpleConnection *gc, const gchar *who,
+                            const gchar *message, PurpleMessageFlags flags)
+{
+    MsimSession *session;
+    
+    g_return_val_if_fail(gc != NULL, 0);
+    g_return_val_if_fail(who != NULL, 0);
+    g_return_val_if_fail(message != NULL, 0);
+
+	/* 'flags' has many options, not used here. */
+
+	session = gc->proto_data;
+
+	if (msim_send_bm(session, who, message, MSIM_BM_INSTANT))
+	{
+		/* Return 1 to have Purple show this IM as being sent, 0 to not. I always
+		 * return 1 even if the message could not be sent, since I don't know if
+		 * it has failed yet--because the IM is only sent after the userid is
+		 * retrieved from the server (which happens after this function returns).
+		 */
+		return 1;
+	} else {
+		return -1;
+	}
+    /*
+     * TODO: In MySpace, you login with your email address, but don't talk to other
+     * users using their email address. So there is currently an asymmetry in the 
+     * IM windows when using this plugin:
+     *
+     * you@example.com: hello
+     * some_other_user: what's going on?
+     * you@example.com: just coding a prpl
+     *
+     * TODO: Make the sent IM's appear as from the user's username, instead of
+     * their email address. Purple uses the login (in MSIM, the email)--change this.
+     */
+}
+
+/** Send a buddy message of a given type.
+ *
+ * @param session
+ * @param who Username to send message to.
+ * @param text Message text to send. Not freed; will be copied.
+ * @param type A MSIM_BM_* constant.
+ *
+ * Buddy messages ('bm') include instant messages, action messages, status messages, etc.
+ */
+gboolean msim_send_bm(MsimSession *session, const gchar *who, const gchar *text, int type)
+{
+	gboolean rc;
+	MsimMessage *msg;
+    const gchar *from_username;
+   
+	from_username = session->account->username;
+
+    purple_debug_info("msim", "sending %d message from %s to %s: %s\n",
+                  type, from_username, who, text);
+
+	msg = msim_msg_new(TRUE,
+			"bm", MSIM_TYPE_INTEGER, GUINT_TO_POINTER(type),
+			"sesskey", MSIM_TYPE_INTEGER, GUINT_TO_POINTER(session->sesskey),
+			/* 't' will be inserted here */
+			"cv", MSIM_TYPE_INTEGER, GUINT_TO_POINTER(MSIM_CLIENT_VERSION),
+			"msg", MSIM_TYPE_STRING, g_strdup(text),
+			NULL);
+
+	rc = msim_postprocess_outgoing(session, msg, who, "t", "cv");
+
+	msim_msg_free(msg);
+
+	return rc;
+}
+
+/**
+ * Handle an incoming instant message.
+ *
+ * @param session The session
+ * @param msg Message from the server, containing 'f' (userid from) and 'msg'. 
+ * 			  Should also contain username in _username from preprocessing.
+ *
+ * @return TRUE if successful.
+ */
+gboolean msim_incoming_im(MsimSession *session, MsimMessage *msg)
+{
+    gchar *username;
+
+    username = msim_msg_get_string(msg, "_username");
+
+    serv_got_im(session->gc, username, msim_msg_get_string(msg, "msg"), PURPLE_MESSAGE_RECV, time(NULL));
+
+	g_free(username);
+	/* TODO: Free copy cloned from msim_incoming_im(). */
+	//msim_msg_free(msg);
+
+	return TRUE;
+}
+
+/**
+ * Handle an incoming action message.
+ *
+ * @param session
+ * @param msg
+ *
+ * @return TRUE if successful.
+ *
+ * UNTESTED
+ */
+gboolean msim_incoming_action(MsimSession *session, MsimMessage *msg)
+{
+	gchar *msg_text, *username;
+	gboolean rc;
+
+	msg_text = msim_msg_get_string(msg, "msg");
+	username = msim_msg_get_string(msg, "_username");
+
+	purple_debug_info("msim", "msim_incoming_action: action <%s> from <%d>\n", msg_text, username);
+
+	if (strcmp(msg_text, "%typing%") == 0)
+	{
+		/* TODO: find out if msim repeatedly sends typing messages, so we can give it a timeout. */
+		serv_got_typing(session->gc, username, 0, PURPLE_TYPING);
+		rc = TRUE;
+	} else if (strcmp(msg_text, "%stoptyping%") == 0) {
+		serv_got_typing_stopped(session->gc, username);
+		rc = TRUE;
+	} else {
+		/* TODO: make a function, msim_unrecognized(), that logs all unhandled msgs to file. */
+		purple_debug_info("msim", "msim_incoming_action: for %s, unknown msg %s\n",
+				username, msg_text);
+		rc = FALSE;
+	}
+
+
+	g_free(msg_text);
+	g_free(username);
+
+	return rc;
+}
+
+/** 
+ * Handle when our user starts or stops typing to another user.
+ *
+ * @param gc
+ * @param name The buddy name to which our user is typing to
+ * @param state PURPLE_TYPING, PURPLE_TYPED, PURPLE_NOT_TYPING
+ *
+ */
+unsigned int msim_send_typing(PurpleConnection *gc, const gchar *name, PurpleTypingState state)
+{
+	const gchar *typing_str;
+	MsimSession *session;
+
+	session = (MsimSession *)gc->proto_data;
+
+	switch (state)
+	{	
+		case PURPLE_TYPING: 
+			typing_str = "%typing%"; 
+			break;
+
+		case PURPLE_TYPED:
+		case PURPLE_NOT_TYPING:
+		default:
+			typing_str = "%stoptyping%";
+			break;
+	}
+
+	purple_debug_info("msim", "msim_send_typing(%s): %d (%s)\n", name, state, typing_str);
+	msim_send_bm(session, name, typing_str, MSIM_BM_ACTION);
+	return 0;
+}
+
+/** Retrieve a user's profile. */
+void msim_get_info(PurpleConnection *gc, const gchar *name)
+{
+	PurpleNotifyUserInfo *user_info;
+	PurpleBuddy *buddy;
+	MsimSession *session;
+
+	session = (MsimSession *)gc->proto_data;
+
+	user_info = purple_notify_user_info_new();
+
+	buddy = purple_find_buddy(session->account, name);
+	if (!buddy)
+	{
+		/* TODO: profile of buddies not on blist! */
+		purple_notify_user_info_add_pair(user_info, NULL,
+				"Sorry, currently user information can only be retrieved from users on your buddy list.");
+		purple_notify_userinfo(gc, name, user_info, NULL, NULL);
+		purple_notify_user_info_destroy(user_info);
+		return;
+	}
+
+
+	/* Identification */
+	purple_notify_user_info_add_pair(user_info, "User Name",
+			purple_blist_node_get_string(&buddy->node, "UserName")); 
+
+
+	purple_notify_user_info_add_pair(user_info, "User ID",
+			g_strdup_printf("%d", purple_blist_node_get_int(&buddy->node, "UserID")));
+
+	purple_notify_user_info_add_pair(user_info, "Display Name",
+			purple_blist_node_get_string(&buddy->node, "DisplayName")); 
+
+
+	/* a/s/l...the vitals */	
+	purple_notify_user_info_add_pair(user_info, "Age",
+			g_strdup_printf("%d", purple_blist_node_get_int(&buddy->node, "Age")));
+
+	purple_notify_user_info_add_pair(user_info, "Gender",
+			 purple_blist_node_get_string(&buddy->node, "Gender"));
+
+	purple_notify_user_info_add_pair(user_info, "Location",
+			purple_blist_node_get_string(&buddy->node, "Location"));
+
+	/* Other information */
+	if (purple_blist_node_get_string(&buddy->node, "Headline"))
+		purple_notify_user_info_add_pair(user_info, "Headline",
+				purple_blist_node_get_string(&buddy->node, "Headline")); 
+
+	purple_notify_user_info_add_pair(user_info, "Song", 
+			g_strdup_printf("%s - %s",
+				purple_blist_node_get_string(&buddy->node, "BandName"),
+				purple_blist_node_get_string(&buddy->node, "SongName")));
+
+	purple_notify_user_info_add_pair(user_info, "Total Friends",
+			g_strdup_printf("%d", purple_blist_node_get_int(&buddy->node, "TotalFriends")));
+
+
+	purple_notify_userinfo(gc, name, user_info, NULL, NULL);
+	purple_notify_user_info_destroy(user_info);
+}
+
+/** After a uid is resolved to username, tag it with the username and submit for processing. 
+ * 
+ * @param session
+ * @param userinfo Response messsage to resolving request.
+ * @param data MsimMessage *, the message to attach information to. 
+ */
+static void msim_incoming_resolved(MsimSession *session, MsimMessage *userinfo, gpointer data)
+{
+	gchar *body_str;
+	GHashTable *body;
+	gchar *username;
+	MsimMessage *msg;
+
+	body_str = msim_msg_get_string(userinfo, "body");
+	g_return_if_fail(body_str != NULL);
+	body = msim_parse_body(body_str);
+	g_return_if_fail(body != NULL);
+	g_free(body_str);
+
+	username = g_hash_table_lookup(body, "UserName");
+	g_return_if_fail(username != NULL);
+
+	msg = (MsimMessage *)data;
+	/* Special elements name beginning with '_', we'll use internally within the
+	 * program (did not come from the wire). */
+	msg = msim_msg_append(msg, "_username", MSIM_TYPE_STRING, g_strdup(username));
+
+	msim_process(session, msg);
+
+	/* TODO: Free copy cloned from  msim_preprocess_incoming(). */
+	//XXX msim_msg_free(msg);
+	g_hash_table_destroy(body);
+}
+
+#ifdef _MSIM_UID2USERNAME_WORKS
+/* Lookup a username by userid, from buddy list. 
+ *
+ * @param wanted_uid
+ *
+ * @return Username of wanted_uid, if on blist, or NULL. Static string. 
+ *
+ * XXX WARNING: UNKNOWN MEMORY CORRUPTION HERE! 
+ */
+static const gchar *msim_uid2username_from_blist(MsimSession *session, guint wanted_uid)
+{
+	GSList *buddies, *buddies_head;
+
+	for (buddies = buddies_head = purple_find_buddies(session->account, NULL); 
+			buddies; 
+			buddies = g_slist_next(buddies))
+	{
+		PurpleBuddy *buddy;
+		guint uid;
+		gchar *name;
+
+		buddy = buddies->data;
+
+		uid = purple_blist_node_get_int(&buddy->node, "UserID");
+
+		/* name = buddy->name; */								/* crash */
+		/* name = PURPLE_BLIST_NODE_NAME(&buddy->node);  */		/* crash */
+
+		/* XXX Is this right? Memory corruption here somehow. Happens only
+		 * when return one of these values. */
+		name = purple_buddy_get_name(buddy); 					/* crash */
+		/* return name; */										/* crash (with above) */
+
+		/* name = NULL; */										/* no crash */
+		/* return NULL; */										/* no crash (with anything) */
+
+		/* crash =
+*** glibc detected *** pidgin: realloc(): invalid pointer: 0x0000000000d2aec0 ***
+======= Backtrace: =========
+/lib/libc.so.6(__libc_realloc+0x323)[0x2b7bfc012e03]
+/usr/lib/libglib-2.0.so.0(g_realloc+0x31)[0x2b7bfba79a41]
+/usr/lib/libgtk-x11-2.0.so.0(gtk_tree_path_append_index+0x3a)[0x2b7bfa110d5a]
+/usr/lib/libgtk-x11-2.0.so.0[0x2b7bfa1287dc]
+/usr/lib/libgtk-x11-2.0.so.0[0x2b7bfa128e56]
+/usr/lib/libgtk-x11-2.0.so.0[0x2b7bfa128efd]
+/usr/lib/libglib-2.0.so.0(g_main_context_dispatch+0x1b4)[0x2b7bfba72c84]
+/usr/lib/libglib-2.0.so.0[0x2b7bfba75acd]
+/usr/lib/libglib-2.0.so.0(g_main_loop_run+0x1ca)[0x2b7bfba75dda]
+/usr/lib/libgtk-x11-2.0.so.0(gtk_main+0xa3)[0x2b7bfa0475f3]
+pidgin(main+0x8be)[0x46b45e]
+/lib/libc.so.6(__libc_start_main+0xf4)[0x2b7bfbfbf0c4]
+pidgin(gtk_widget_grab_focus+0x39)[0x429ab9]
+
+or:
+ *** glibc detected *** /usr/local/bin/pidgin: malloc(): memory corruption (fast): 0x0000000000c10076 ***
+ (gdb) bt
+#0  0x00002b4074ecd47b in raise () from /lib/libc.so.6
+#1  0x00002b4074eceda0 in abort () from /lib/libc.so.6
+#2  0x00002b4074f0453b in __fsetlocking () from /lib/libc.so.6
+#3  0x00002b4074f0c810 in free () from /lib/libc.so.6
+#4  0x00002b4074f0d6dd in malloc () from /lib/libc.so.6
+#5  0x00002b4074974b5b in g_malloc () from /usr/lib/libglib-2.0.so.0
+#6  0x00002b40749868bf in g_strdup () from /usr/lib/libglib-2.0.so.0
+#7  0x00002b407810969f in msim_parse (
+    raw=0xd2a910 "\\bm\\100\\f\\3656574\\msg\\|s|0|ss|Offline")
+	    at message.c:648
+#8  0x00002b407810889c in msim_input_cb (gc_uncasted=0xcf92c0, 
+    source=<value optimized out>, cond=<value optimized out>) at myspace.c:1478
+
+
+	Why is it crashing in msim_parse()'s g_strdup()?
+*/
+
+
+		purple_debug_info("msim", "msim_uid2username_from_blist: %s's uid=%d (want %d)\n",
+				name, uid, wanted_uid);
+
+		if (uid == wanted_uid)
+		{
+			g_slist_free(buddies_head);
+
+			return name;
+		}
+	}
+
+	g_slist_free(buddies_head);
+	return NULL;
+}
+
+#endif
+
+/** Preprocess incoming messages, resolving as needed, calling msim_process() when ready to process.
+ *
+ * @param session
+ * @param msg MsimMessage *, freed by caller.
+ */
+gboolean msim_preprocess_incoming(MsimSession *session, MsimMessage *msg)
+{
+	if (msim_msg_get(msg, "bm") && msim_msg_get(msg, "f"))
+	{
+		guint uid;
+		const gchar *username;
+
+		/* 'f' = userid message is from, in buddy messages */
+		uid = msim_msg_get_integer(msg, "f");
+
+		/* TODO: Make caching work. Currently it is commented out because
+		 * it crashes for unknown reasons, memory realloc error. */
+//#define _MSIM_UID2USERNAME_WORKS
+#ifdef _MSIM_UID2USERNAME_WORKS
+		username = msim_uid2username_from_blist(session, uid); 
+#else
+		username = NULL;
+#endif
+
+		if (username)
+		{
+			/* Know username already, use it. */
+			purple_debug_info("msim", "msim_preprocess_incoming: tagging with _username=%s\n",
+					username);
+			msg = msim_msg_append(msg, "_username", MSIM_TYPE_STRING, g_strdup(username));
+			return msim_process(session, msg);
+
+		} else {
+			/* Send lookup request. */
+			/* XXX: where is msim_msg_get_string() freed? make _strdup and _nonstrdup. */
+			purple_debug_info("msim", "msim_incoming: sending lookup, setting up callback\n");
+			msim_lookup_user(session, msim_msg_get_string(msg, "f"), msim_incoming_resolved, msim_msg_clone(msg)); 
+
+			/* indeterminate */
+			return TRUE;
+		}
+	} else {
+		/* Nothing to resolve - send directly to processing. */
+		return msim_process(session, msg);
+	}
+}
+
+/**
+ * Process a message. 
+ *
+ * @param session
+ * @param msg A message from the server, ready for processing (possibly with resolved username information attached). Caller frees.
+ *
+ * @return TRUE if successful. FALSE if processing failed.
+ */
+gboolean msim_process(MsimSession *session, MsimMessage *msg)
+{
+    g_return_val_if_fail(session != NULL, -1);
+    g_return_val_if_fail(msg != NULL, -1);
+
+#ifdef MSIM_DEBUG_MSG
+	{
+		msim_msg_dump("ready to process: %s\n", msg);
+	}
+#endif
+
+    if (msim_msg_get(msg, "nc"))
+    {
+        return msim_login_challenge(session, msg);
+    } else if (msim_msg_get(msg, "sesskey")) {
+
+        purple_connection_update_progress(session->gc, _("Connected"), 3, 4);
+
+        session->sesskey = msim_msg_get_integer(msg, "sesskey");
+        purple_debug_info("msim", "SESSKEY=<%d>\n", session->sesskey);
+
+        /* Comes with: proof,profileid,userid,uniquenick -- all same values
+		 * some of the time, but can vary. This is our own user ID. */
+        session->userid = msim_msg_get_integer(msg, "userid");
+
+		/* TODO: fake our own userid being online */
+
+        purple_connection_set_state(session->gc, PURPLE_CONNECTED);
+
+        return TRUE;
+    } else if (msim_msg_get(msg, "bm"))  {
+        guint bm;
+       
+        bm = msim_msg_get_integer(msg, "bm");
+        switch (bm)
+        {
+            case MSIM_BM_STATUS:
+                return msim_status(session, msg);
+            case MSIM_BM_INSTANT:
+                return msim_incoming_im(session, msg);
+			case MSIM_BM_ACTION:
+				return msim_incoming_action(session, msg);
+            default:
+                /* Not really an IM, but show it for informational 
+                 * purposes during development. */
+                return msim_incoming_im(session, msg);
+        }
+    } else if (msim_msg_get(msg, "rid")) {
+        return msim_process_reply(session, msg);
+    } else if (msim_msg_get(msg, "error")) {
+        return msim_error(session, msg);
+    } else if (msim_msg_get(msg, "ka")) {
+        purple_debug_info("msim", "msim_process: got keep alive\n");
+        return TRUE;
+    } else {
+		/* TODO: dump unknown msgs to file, so user can send them to me
+		 * if they wish, to help add support for new messages (inspired
+		 * by Alexandr Shutko, who maintains OSCAR protocol documentation). */
+        purple_debug_info("msim", "msim_process: unhandled message\n");
+        return FALSE;
+    }
+}
+
+/** Store an field of information about a buddy. */
+void msim_store_buddy_info_each(gpointer key, gpointer value, gpointer user_data)
+{
+	PurpleBuddy *buddy;
+	gchar *key_str, *value_str;
+
+	buddy = (PurpleBuddy *)user_data;
+	key_str = (gchar *)key;
+	value_str = (gchar *)value;
+
+	if (strcmp(key_str, "UserID") == 0 ||
+			strcmp(key_str, "Age") == 0 ||
+			strcmp(key_str, "TotalFriends") == 0)
+	{
+		/* Certain fields get set as integers, instead of strings, for
+		 * convenience. May not be the best way to do it, but having at least
+		 * UserID as an integer is convenient...until it overflows! */
+		purple_blist_node_set_int(&buddy->node, key_str, atol(value_str));
+	} else {
+		purple_blist_node_set_string(&buddy->node, key_str, value_str);
+	}
+}
+
+/** Save buddy information to the buddy list from a user info reply message.
+ *
+ * @param session
+ * @param msg The user information reply, with any amount of information.
+ *
+ * The information is saved to the buddy's blist node, which ends up in blist.xml.
+ */
+gboolean msim_store_buddy_info(MsimSession *session, MsimMessage *msg)
+{
+	GHashTable *body;
+	gchar *username, *body_str, *uid;
+	PurpleBuddy *buddy;
+	guint rid;
+
+	rid = msim_msg_get_integer(msg, "rid");
+	
+	g_return_val_if_fail(rid != 0, FALSE);
+
+	body_str = msim_msg_get_string(msg, "body");
+	g_return_val_if_fail(body_str != NULL, FALSE);
+	body = msim_parse_body(body_str);
+	g_free(body_str);
+
+	/* TODO: implement a better hash-like interface, and use it. */
+	username = g_hash_table_lookup(body, "UserName");
+
+	if (!username)
+	{
+		purple_debug_info("msim", 
+			"msim_process_reply: not caching body, no UserName\n");
+		return FALSE;
+	}
+
+	uid = g_hash_table_lookup(body, "UserID");
+	g_return_val_if_fail(uid, FALSE);
+
+	purple_debug_info("msim", "associating uid %d with username %s\n", uid, username);
+
+	buddy = purple_find_buddy(session->account, username);
+	if (buddy)
+	{
+		g_hash_table_foreach(body, msim_store_buddy_info_each, buddy);
+	}
+
+	return TRUE;
+}
+
+/**
+ * Process a persistance message reply from the server.
+ *
+ * @param session 
+ * @param msg Message reply from server.
+ *
+ * @return TRUE if successful.
+ */
+gboolean msim_process_reply(MsimSession *session, MsimMessage *msg)
+{
+    g_return_val_if_fail(MSIM_SESSION_VALID(session), FALSE);
+    g_return_val_if_fail(msg != NULL, FALSE);
+    
+    if (msim_msg_get(msg, "rid"))  /* msim_lookup_user sets callback for here */
+    {
+        MSIM_USER_LOOKUP_CB cb;
+        gpointer data;
+        guint rid;
+
+		msim_store_buddy_info(session, msg);		
+
+		rid = msim_msg_get_integer(msg, "rid");
+
+        /* If a callback is registered for this userid lookup, call it. */
+        cb = g_hash_table_lookup(session->user_lookup_cb, GUINT_TO_POINTER(rid));
+        data = g_hash_table_lookup(session->user_lookup_cb_data, GUINT_TO_POINTER(rid));
+
+        if (cb)
+        {
+            purple_debug_info("msim", 
+					"msim_process_body: calling callback now\n");
+			/* Clone message, so that the callback 'cb' can use it (needs to free it also). */
+            cb(session, msim_msg_clone(msg), data);
+            g_hash_table_remove(session->user_lookup_cb, GUINT_TO_POINTER(rid));
+            g_hash_table_remove(session->user_lookup_cb_data, GUINT_TO_POINTER(rid));
+        } else {
+            purple_debug_info("msim", 
+					"msim_process_body: no callback for rid %d\n", rid);
+        }
+    }
+
+	return TRUE;
+}
+
+/**
+ * Handle an error from the server.
+ *
+ * @param session 
+ * @param msg The message.
+ *
+ * @return TRUE if successfully reported error.
+ */
+gboolean msim_error(MsimSession *session, MsimMessage *msg)
+{
+    gchar *errmsg, *full_errmsg;
+	guint err;
+
+    g_return_val_if_fail(MSIM_SESSION_VALID(session), FALSE);
+    g_return_val_if_fail(msg != NULL, FALSE);
+
+    err = msim_msg_get_integer(msg, "err");
+    errmsg = msim_msg_get_string(msg, "errmsg");
+
+    full_errmsg = g_strdup_printf(_("Protocol error, code %d: %s"), err, errmsg);
+
+	g_free(errmsg);
+
+    purple_debug_info("msim", "msim_error: %s\n", full_errmsg);
+
+    /* TODO: do something with the error # (localization of errmsg?)  */
+    purple_notify_error(session->account, g_strdup(_("MySpaceIM Error")), 
+            full_errmsg, NULL);
+
+	/* Destroy session if fatal. */
+    if (msim_msg_get(msg, "fatal"))
+    {
+        purple_debug_info("msim", "fatal error, closing\n");
+        purple_connection_error(session->gc, full_errmsg);
+
+		msim_close(session->gc);
+    }
+
+    return TRUE;
+}
+
+/**
+ * Process incoming status messages.
+ *
+ * @param session
+ * @param msg Status update message. Caller frees.
+ *
+ * @return TRUE if successful.
+ */
+gboolean msim_status(MsimSession *session, MsimMessage *msg)
+{
+    PurpleBuddyList *blist;
+    PurpleBuddy *buddy;
+    //PurpleStatus *status;
+    gchar **status_array;
+    GList *list;
+    gchar *status_headline;
+    gchar *status_str;
+    gint i, status_code, purple_status_code;
+    gchar *username;
+
+    g_return_val_if_fail(MSIM_SESSION_VALID(session), FALSE);
+    g_return_val_if_fail(msg != NULL, FALSE);
+
+    status_str = msim_msg_get_string(msg, "msg");
+	g_return_val_if_fail(status_str != NULL, FALSE);
+
+	msim_msg_dump("msim_status msg=%s\n", msg);
+
+	/* Helpfully looked up by msim_incoming_resolve() for us. */
+    username = msim_msg_get_string(msg, "_username");
+    /* Note: DisplayName doesn't seem to be resolvable. It could be displayed on
+     * the buddy list, if the UserID was stored along with it. */
+
+	if (username == NULL)
+	{
+		g_free(status_str);
+		g_return_val_if_fail(NULL, FALSE);
+	}
+
+    purple_debug_info("msim", 
+			"msim_status_cb: updating status for <%s> to <%s>\n", 
+			username, status_str);
+
+    /* TODO: generic functions to split into a GList, part of MsimMessage */
+    status_array = g_strsplit(status_str, "|", 0);
+    for (list = NULL, i = 0;
+            status_array[i];
+            i++)
+    {
+		/* Note: this adds the 0th ordinal too, which might not be a value
+		 * at all (the 0 in the 0|1|2|3... status fields, but 0 always appears blank).
+		 */
+        list = g_list_append(list, status_array[i]);
+    }
+
+    /* Example fields: 
+	 *  |s|0|ss|Offline 
+	 *  |s|1|ss|:-)|ls||ip|0|p|0 
+	 *
+	 * TODO: write list support in MsimMessage, and use it here.
+	 */
+
+    status_code = atoi(g_list_nth_data(list, MSIM_STATUS_ORDINAL_ONLINE));
+	purple_debug_info("msim", "msim_status_cb: %s's status code = %d\n", username, status_code);
+    status_headline = g_list_nth_data(list, MSIM_STATUS_ORDINAL_HEADLINE);
+
+    blist = purple_get_blist();
+
+    /* Add buddy if not found */
+    buddy = purple_find_buddy(session->account, username);
+    if (!buddy)
+    {
+        /* TODO: purple aliases, userids and usernames */
+        purple_debug_info("msim", 
+				"msim_status: making new buddy for %s\n", username);
+        buddy = purple_buddy_new(session->account, username, NULL);
+
+        purple_blist_add_buddy(buddy, NULL, NULL, NULL);
+
+		/* All buddies on list should have 'uid' integer associated with them. */
+		purple_blist_node_set_int(&buddy->node, "UserID", msim_msg_get_integer(msg, "f"));
+		
+		msim_store_buddy_info(session, msg);
+    } else {
+        purple_debug_info("msim", "msim_status: found buddy %s\n", username);
+    }
+
+	purple_blist_node_set_string(&buddy->node, "Headline", status_headline);
+  
+    /* Set user status */	
+    switch (status_code)
+	{
+		case 1: purple_status_code = PURPLE_STATUS_AVAILABLE;
+				break;
+		case 0: purple_status_code = PURPLE_STATUS_OFFLINE;	
+				break;
+		default:
+				purple_debug_info("msim", "msim_status_cb for %s, unknown status code %d\n",
+						username, status_code);
+				purple_status_code = PURPLE_STATUS_AVAILABLE;
+	}
+	purple_prpl_got_user_status(session->account, username, purple_primitive_get_id_from_type(purple_status_code), NULL);
+
+    g_strfreev(status_array);
+	g_free(status_str);
+	g_free(username);
+    g_list_free(list);
+
+    return TRUE;
+}
+
+/** Add a buddy to user's buddy list. */
+void msim_add_buddy(PurpleConnection *gc, PurpleBuddy *buddy, PurpleGroup *group)
+{
+	MsimSession *session;
+	MsimMessage *msg;
+
+	session = (MsimSession *)gc->proto_data;
+	purple_debug_info("msim", "msim_add_buddy: want to add %s to %s\n", buddy->name,
+			group ? group->name : "(no group)");
+
+	msg = msim_msg_new(TRUE,
+			"addbuddy", MSIM_TYPE_BOOLEAN, TRUE,
+			"sesskey", MSIM_TYPE_INTEGER, session->sesskey,
+			/* "newprofileid" will be inserted here with uid. */
+			"reason", MSIM_TYPE_STRING, g_strdup(""),
+			NULL);
+
+	if (!msim_postprocess_outgoing(session, msg, buddy->name, "newprofileid", "reason"))
+	{
+		purple_notify_error(NULL, NULL, _("Failed to add buddy"), _("'addbuddy' command failed."));
+		msim_msg_free(msg);
+		return;
+	}
+	msim_msg_free(msg);
+
+	/* TODO: update blocklist */
+#if 0
+	/* TODO */
+	if (!msim_postprocess_outgoing(session,
+			"persist", MSIM_TYPE_INTEGER, 1,
+			"sesskey", MSIM_TYPE_INTEGER, session->sesskey,
+			"cmd", MSIM_TYPE_INTEGER, MSIM_CMD_BIT_ACTION | MSIM_CMD_PUT,
+			"dsn", MSIM_TYPE_INTEGER, MC_CONTACT_INFO_DSN,
+			"lid", MSIM_TYPE_INTEGER, MC_CONTACT_INFO_LID,
+			/* TODO: Use msim_new_reply_callback to get rid. */
+			"rid", MSIM_TYPE_INTEGER, session->next_rid++,
+			"body", MSIM_TYPE_STRING,
+				g_strdup_printf("ContactID=%s\034"
+				"GroupName=%s\034"
+				"Position=1000\034"
+				"Visibility=1\034"
+				"NickName=\034"
+				"NameSelect=0",
+				buddy->name, group->name),
+			NULL))
+	{
+		purple_notify_error(NULL, NULL, _("Failed to add buddy"), _("persist command failed"));
+		return;
+	}
+#endif
+}
+
+/** Perform actual postprocessing on a message, adding userid as specified.
+ *
+ * @param msg The message to postprocess.
+ * @param uid_before Name of field where to insert new field before, or NULL for end.
+ * @param uid_field_name Name of field to add uid to.
+ * @param uid The userid to insert.
+ *
+ * If the field named by uid_field_name already exists, then its string contents will
+ * be used for the field, except "<uid>" will be replaced by the userid.
+ *
+ * If the field named by uid_field_name does not exist, it will be added before the
+ * field named by uid_before, as an integer, with the userid.
+ *
+ * Does not handle sending, or scheduling userid lookup. For that, see msim_postprocess_outgoing().
+ */ 
+MsimMessage *msim_do_postprocessing(MsimMessage *msg, const gchar *uid_before, const gchar *uid_field_name, guint uid)
+{	
+	purple_debug_info("msim", "msim_do_postprocessing called with ufn=%s, ub=%s, uid=%d\n",
+			uid_field_name, uid_before, uid);
+	msim_msg_dump("msim_do_postprocessing msg: %s\n", msg);
+
+	/* First, check - if the field already exists, treat it as a format string. */
+	if (msim_msg_get(msg, uid_field_name))
+	{
+		MsimMessageElement *elem;
+		gchar *fmt_string;
+		gchar *uid_str;
+
+		/* Warning: this probably violates the encapsulation of MsimMessage */
+
+		elem = msim_msg_get(msg, uid_field_name);
+		g_return_val_if_fail(elem->type == MSIM_TYPE_STRING, NULL);
+
+		/* Get the raw string, not with msim_msg_get_string() since that copies it. 
+		 * Want the original string so can free it. */
+		fmt_string = (gchar *)(elem->data);
+
+		uid_str = g_strdup_printf("%d", uid);
+		elem->data = str_replace(fmt_string, "<uid>", uid_str);
+		g_free(uid_str);
+		g_free(fmt_string);
+
+		purple_debug_info("msim", "msim_postprocess_outgoing_cb: formatted new string, %s\n",
+				elem->data);
+
+	} else {
+		/* Otherwise, insert new field into outgoing message. */
+		msg = msim_msg_insert_before(msg, uid_before, uid_field_name, MSIM_TYPE_INTEGER, GUINT_TO_POINTER(uid));
+	}
+
+	return msg;
+}	
+
+/** Callback for msim_postprocess_outgoing() to add a userid to a message, and send it (once receiving userid).
+ *
+ * @param session
+ * @param userinfo The user information reply message, containing the user ID
+ * @param data The message to postprocess and send.
+ *
+ * The data message should contain these fields:
+ *
+ *  _uid_field_name: string, name of field to add with userid from userinfo message
+ *  _uid_before: string, name of field before field to insert, or NULL for end
+ *
+ *
+*/
+void msim_postprocess_outgoing_cb(MsimSession *session, MsimMessage *userinfo, gpointer data)
+{
+	gchar *body_str;
+	GHashTable *body;
+	gchar *uid, *uid_field_name, *uid_before;
+	MsimMessage *msg;
+
+	msg = (MsimMessage *)data;
+
+	msim_msg_dump("msim_postprocess_outgoing_cb() got msg=%s\n", msg);
+
+	/* Obtain userid from userinfo message. */
+	body_str = msim_msg_get_string(userinfo, "body");
+	g_return_if_fail(body_str != NULL);
+	body = msim_parse_body(body_str);
+	g_free(body_str);
+
+	uid = g_strdup(g_hash_table_lookup(body, "UserID"));
+	g_hash_table_destroy(body);
+
+	uid_field_name = msim_msg_get_string(msg, "_uid_field_name");
+	uid_before = msim_msg_get_string(msg, "_uid_before");
+
+	msg = msim_do_postprocessing(msg, uid_before, uid_field_name, atol(uid));
+
+	/* Send */
+	if (!msim_msg_send(session, msg))
+	{
+		purple_debug_info("msim", "msim_postprocess_outgoing_cb: sending failed for message: %s\n", msg);
+	}
+
+
+	/* Free field names AFTER sending message, because MsimMessage does NOT copy
+	 * field names - instead, treats them as static strings (which they usually are).
+	 */
+	g_free(uid_field_name);
+	g_free(uid_before);
+
+	//msim_msg_free(msg);
+}
+
+/** Postprocess and send a message.
+ *
+ * @param session
+ * @param msg Message to postprocess. Will NOT be freed.
+ * @param username Username to resolve. Assumed to be a static string (will not be freed or copied).
+ * @param uid_field_name Name of new field to add, containing uid of username. Static string.
+ * @param uid_before Name of existing field to insert username field before. Static string.
+ *
+ * @return Postprocessed message.
+ */
+gboolean msim_postprocess_outgoing(MsimSession *session, MsimMessage *msg, const gchar *username, 
+	const gchar *uid_field_name, const gchar *uid_before)
+{
+    PurpleBuddy *buddy;
+	guint uid;
+	gboolean rc;
+
+	/* Store information for msim_postprocess_outgoing_cb(). */
+	purple_debug_info("msim", "msim_postprocess_outgoing(u=%s,ufn=%s,ub=%s)\n",
+			username, uid_field_name, uid_before);
+	msim_msg_dump("msim_postprocess_outgoing: msg before=%s\n", msg);
+	msg = msim_msg_append(msg, "_username", MSIM_TYPE_STRING, g_strdup(username));
+	msg = msim_msg_append(msg, "_uid_field_name", MSIM_TYPE_STRING, g_strdup(uid_field_name));
+	msg = msim_msg_append(msg, "_uid_before", MSIM_TYPE_STRING, g_strdup(uid_before));
+
+	/* First, try the most obvious. If numeric userid is given, use that directly. */
+    if (msim_is_userid(username))
+    {
+		uid = atol(username);
+    } else {
+		/* Next, see if on buddy list and know uid. */
+		buddy = purple_find_buddy(session->account, username);
+		if (buddy)
+		{
+			uid = purple_blist_node_get_int(&buddy->node, "UserID");
+		} else {
+			uid = 0;
+		}
+
+		if (!buddy || !uid)
+		{
+			/* Don't have uid offhand - need to ask for it, and wait until hear back before sending. */
+			purple_debug_info("msim", ">>> msim_postprocess_outgoing: couldn't find username %s in blist\n",
+					username);
+			msim_msg_dump("msim_postprocess_outgoing - scheduling lookup, msg=%s\n", msg);
+			/* TODO: where is cloned message freed? Should be in _cb. */
+			msim_lookup_user(session, username, msim_postprocess_outgoing_cb, msim_msg_clone(msg));
+			return TRUE;		/* not sure of status yet - haven't sent! */
+		}
+	}
+	
+	/* Already have uid, postprocess and send msg immediately. */
+	purple_debug_info("msim", "msim_postprocess_outgoing: found username %s has uid %d\n",
+			username, uid);
+
+	msg = msim_do_postprocessing(msg, uid_before, uid_field_name, uid);
+
+	msim_msg_dump("msim_postprocess_outgoing: msg after (uid immediate)=%s\n", msg);
+	
+	rc = msim_msg_send(session, msg);
+
+	//msim_msg_free(msg);
+
+	return rc;
+}
+
+/** Remove a buddy from the user's buddy list. */
+void msim_remove_buddy(PurpleConnection *gc, PurpleBuddy *buddy, PurpleGroup *group)
+{
+	MsimSession *session;
+	MsimMessage *delbuddy_msg;
+	MsimMessage *persist_msg;
+	MsimMessage *blocklist_msg;
+
+	session = (MsimSession *)gc->proto_data;
+
+	delbuddy_msg = msim_msg_new(TRUE,
+				"delbuddy", MSIM_TYPE_BOOLEAN, TRUE,
+				"sesskey", MSIM_TYPE_INTEGER, session->sesskey,
+				/* 'delprofileid' with uid will be inserted here. */
+				NULL);
+	/* TODO: free msg */
+	if (!msim_postprocess_outgoing(session, delbuddy_msg, buddy->name, "delprofileid", NULL))
+	{
+		purple_notify_error(NULL, NULL, _("Failed to remove buddy"), _("'delbuddy' command failed"));
+		return;
+	}
+
+	persist_msg = msim_msg_new(TRUE, 
+			"persist", MSIM_TYPE_INTEGER, 1,
+			"sesskey", MSIM_TYPE_INTEGER, session->sesskey,
+			"cmd", MSIM_TYPE_INTEGER, MSIM_CMD_BIT_ACTION | MSIM_CMD_DELETE,
+			"dsn", MSIM_TYPE_INTEGER, MD_DELETE_BUDDY_DSN,
+			"lid", MSIM_TYPE_INTEGER, MD_DELETE_BUDDY_LID,
+			"uid", MSIM_TYPE_INTEGER, session->userid,
+			"rid", MSIM_TYPE_INTEGER, session->next_rid++,
+			/* <uid> will be replaced by postprocessing */
+			"body", MSIM_TYPE_STRING, g_strdup("ContactID=<uid>"),
+			NULL);
+
+	/* TODO: free msg */
+	if (!msim_postprocess_outgoing(session, persist_msg, buddy->name, "body", NULL))
+	{
+		purple_notify_error(NULL, NULL, _("Failed to remove buddy"), _("persist command failed"));	
+		return;
+	}
+
+	blocklist_msg = msim_msg_new(TRUE,
+			"blocklist", MSIM_TYPE_BOOLEAN, TRUE,
+			"sesskey", MSIM_TYPE_INTEGER, session->sesskey,
+			/* TODO: MsimMessage lists */
+			"idlist", MSIM_TYPE_STRING, g_strdup("a-|<uid>|b-|<uid>"),
+			NULL);
+
+	if (!msim_postprocess_outgoing(session, blocklist_msg, buddy->name, "idlist", NULL))
+	{
+		purple_notify_error(NULL, NULL, _("Failed to remove buddy"), _("blocklist command failed"));
+		return;
+	}
+
+	/* TODO: update blocklist */
+}
+
+/** Return whether the buddy can be messaged while offline.
+ *
+ * I always return TRUE, to allow sending to buddies whose status has not yet
+ * been received. The protocol _does_ support offline messages, but not this plugin.
+ * TODO: Real offline message support.
+ */
+gboolean msim_offline_message(const PurpleBuddy *buddy)
+{
+	return TRUE;
+}
+
+
+/**
+ * Callback when input available.
+ *
+ * @param gc_uncasted A PurpleConnection pointer.
+ * @param source File descriptor.
+ * @param cond PURPLE_INPUT_READ
+ *
+ * Reads the input, and calls msim_preprocess_incoming() to handle it.
+ */
+void msim_input_cb(gpointer gc_uncasted, gint source, PurpleInputCondition cond)
+{
+    PurpleConnection *gc;
+    PurpleAccount *account;
+    MsimSession *session;
+    gchar *end;
+    int n;
+
+    g_return_if_fail(gc_uncasted != NULL);
+    g_return_if_fail(source >= 0);  /* Note: 0 is a valid fd */
+
+    gc = (PurpleConnection *)(gc_uncasted);
+    account = purple_connection_get_account(gc);
+    session = gc->proto_data;
+
+    g_return_if_fail(cond == PURPLE_INPUT_READ);
+	g_return_if_fail(MSIM_SESSION_VALID(session));
+
+    /* Only can handle so much data at once... 
+     * If this happens, try recompiling with a higher MSIM_READ_BUF_SIZE.
+     * Should be large enough to hold the largest protocol message.
+     */
+    if (session->rxoff == MSIM_READ_BUF_SIZE)
+    {
+        purple_debug_error("msim", "msim_input_cb: %d-byte read buffer full!\n",
+                MSIM_READ_BUF_SIZE);
+        purple_connection_error(gc, _("Read buffer full"));
+
+		msim_close(session->gc);
+        return;
+    }
+
+    purple_debug_info("msim", "buffer at %d (max %d), reading up to %d\n",
+            session->rxoff, MSIM_READ_BUF_SIZE, 
+			MSIM_READ_BUF_SIZE - session->rxoff);
+
+    /* Read into buffer. On Win32, need recv() not read(). session->fd also holds
+     * the file descriptor, but it sometimes differs from the 'source' parameter.
+     */
+    n = recv(session->fd, session->rxbuf + session->rxoff, MSIM_READ_BUF_SIZE - session->rxoff, 0);
+
+    if (n < 0 && errno == EAGAIN)
+    {
+        return;
+    }
+    else if (n < 0)
+    {
+        purple_connection_error(gc, _("Read error"));
+        purple_debug_error("msim", "msim_input_cb: read error, ret=%d, "
+			"error=%s, source=%d, fd=%d (%X))\n", 
+			n, strerror(errno), source, session->fd, session->fd);
+
+		msim_close(session->gc);
+        return;
+    } 
+    else if (n == 0)
+    {
+        purple_debug_info("msim", "msim_input_cb: server disconnected\n");
+        purple_connection_error(gc, _("Server has disconnected"));
+        return;
+    }
+
+    /* Null terminate */
+    session->rxbuf[session->rxoff + n] = 0;
+
+    /* Check for embedded NULs. I don't handle them, and they shouldn't occur. */
+    if (strlen(session->rxbuf + session->rxoff) != n)
+    {
+        /* Occurs after login, but it is not a null byte. */
+        purple_debug_info("msim", "msim_input_cb: strlen=%d, but read %d bytes"
+                "--null byte encountered?\n", 
+				strlen(session->rxbuf + session->rxoff), n);
+        //purple_connection_error(gc, "Invalid message - null byte on input");
+        return;
+    }
+
+    session->rxoff += n;
+    purple_debug_info("msim", "msim_input_cb: read=%d\n", n);
+
+#ifdef MSIM_DEBUG_RXBUF
+    purple_debug_info("msim", "buf=<%s>\n", session->rxbuf);
+#endif
+
+    /* Look for \\final\\ end markers. If found, process message. */
+    while((end = strstr(session->rxbuf, MSIM_FINAL_STRING)))
+    {
+        MsimMessage *msg;
+
+#ifdef MSIM_DEBUG_RXBUF
+        purple_debug_info("msim", "in loop: buf=<%s>\n", session->rxbuf);
+#endif
+        *end = 0;
+        msg = msim_parse(g_strdup(session->rxbuf));
+        if (!msg)
+        {
+            purple_debug_info("msim", "msim_input_cb: couldn't parse <%s>\n", 
+					session->rxbuf);
+            purple_connection_error(gc, _("Unparseable message"));
+        }
+        else
+        {
+            /* Process message and then free it (processing function should
+			 * clone message if it wants to keep it afterwards.) */
+            if (!msim_preprocess_incoming(session, msg))
+			{
+				msim_msg_dump("msim_input_cb: preprocessing message failed on msg: %s\n", msg);
+			}
+			msim_msg_free(msg);
+        }
+
+        /* Move remaining part of buffer to beginning. */
+        session->rxoff -= strlen(session->rxbuf) + strlen(MSIM_FINAL_STRING);
+        memmove(session->rxbuf, end + strlen(MSIM_FINAL_STRING), 
+                MSIM_READ_BUF_SIZE - (end + strlen(MSIM_FINAL_STRING) - session->rxbuf));
+
+        /* Clear end of buffer */
+        //memset(end, 0, MSIM_READ_BUF_SIZE - (end - session->rxbuf));
+    }
+}
+
+/* Setup a callback, to be called when a reply is received with the returned rid.
+ *
+ * @param cb The callback, an MSIM_USER_LOOKUP_CB.
+ * @param data Arbitrary user data to be passed to callback (probably an MsimMessage *).
+ *
+ * @return The request/reply ID, used to link replies with requests. Put the rid in your request.
+ *
+ * TODO: Make more generic and more specific:
+ * 1) MSIM_USER_LOOKUP_CB - make it for PERSIST_REPLY, not just user lookup
+ * 2) data - make it an MsimMessage?
+ */
+guint msim_new_reply_callback(MsimSession *session, MSIM_USER_LOOKUP_CB cb, gpointer data)
+{
+	guint rid;
+
+	rid = session->next_rid++;
+
+    g_hash_table_insert(session->user_lookup_cb, GUINT_TO_POINTER(rid), cb);
+    g_hash_table_insert(session->user_lookup_cb_data, GUINT_TO_POINTER(rid), data);
+
+	return rid;
+}
+
+/**
+ * Callback when connected. Sets up input handlers.
+ *
+ * @param data A PurpleConnection pointer.
+ * @param source File descriptor.
+ * @param error_message
+ */
+void msim_connect_cb(gpointer data, gint source, const gchar *error_message)
+{
+    PurpleConnection *gc;
+    MsimSession *session;
+
+    g_return_if_fail(data != NULL);
+
+    gc = (PurpleConnection *)data;
+    session = (MsimSession *)gc->proto_data;
+
+    if (source < 0)
+    {
+        purple_connection_error(gc, _("Couldn't connect to host"));
+        purple_connection_error(gc, g_strdup_printf(_("Couldn't connect to host: %s (%d)"), 
+                    error_message, source));
+        return;
+    }
+
+    session->fd = source; 
+
+    gc->inpa = purple_input_add(source, PURPLE_INPUT_READ, msim_input_cb, gc);
+}
+
+/* Session methods */
+
+/**
+ * Create a new MSIM session.
+ *
+ * @param acct The account to create the session from.
+ *
+ * @return Pointer to a new session. Free with msim_session_destroy.
+ */
+MsimSession *msim_session_new(PurpleAccount *acct)
+{
+    MsimSession *session;
+
+    g_return_val_if_fail(acct != NULL, NULL);
+
+    session = g_new0(MsimSession, 1);
+
+    session->magic = MSIM_SESSION_STRUCT_MAGIC;
+    session->account = acct;
+    session->gc = purple_account_get_connection(acct);
+    session->fd = -1;
+
+	/* TODO: Remove. */
+    session->user_lookup_cb = g_hash_table_new_full(g_direct_hash, 
+			g_direct_equal, NULL, NULL);  /* do NOT free function pointers! (values) */
+    session->user_lookup_cb_data = g_hash_table_new_full(g_direct_hash, 
+			g_direct_equal, NULL, NULL);/* TODO: we don't know what the values are,
+											 they could be integers inside gpointers
+											 or strings, so I don't freed them.
+											 Figure this out, once free cache. */
+    session->rxoff = 0;
+    session->rxbuf = g_new0(gchar, MSIM_READ_BUF_SIZE);
+	session->next_rid = 1;
+    
+    return session;
+}
+
+/**
+ * Free a session.
+ *
+ * @param session The session to destroy.
+ */
+void msim_session_destroy(MsimSession *session)
+{
+    g_return_if_fail(MSIM_SESSION_VALID(session));
+
+    session->magic = -1;
+
+    g_free(session->rxbuf);
+
+	/* TODO: Remove. */
+	g_hash_table_destroy(session->user_lookup_cb);
+	g_hash_table_destroy(session->user_lookup_cb_data);
+	
+    g_free(session);
+}
+                 
+
+
+/** 
+ * Close the connection.
+ * 
+ * @param gc The connection.
+ */
+void msim_close(PurpleConnection *gc)
+{
+	MsimSession *session;
+
+	purple_debug_info("msim", "msim_close: destroying session\n");
+
+	session = (MsimSession *)gc->proto_data;
+
+    g_return_if_fail(gc != NULL);
+	g_return_if_fail(session != NULL);
+	g_return_if_fail(MSIM_SESSION_VALID(session));
+
+    purple_input_remove(session->gc->inpa);
+    msim_session_destroy(session);
+}
+
+
+/**
+ * Check if a string is a userid (all numeric).
+ *
+ * @param user The user id, email, or name.
+ *
+ * @return TRUE if is userid, FALSE if not.
+ */
+gboolean msim_is_userid(const gchar *user)
+{
+    g_return_val_if_fail(user != NULL, FALSE);
+
+    return strspn(user, "0123456789") == strlen(user);
+}
+
+/**
+ * Check if a string is an email address (contains an @).
+ *
+ * @param user The user id, email, or name.
+ *
+ * @return TRUE if is an email, FALSE if not.
+ *
+ * This function is not intended to be used as a generic
+ * means of validating email addresses, but to distinguish
+ * between a user represented by an email address from
+ * other forms of identification.
+ */ 
+gboolean msim_is_email(const gchar *user)
+{
+    g_return_val_if_fail(user != NULL, FALSE);
+
+    return strchr(user, '@') != NULL;
+}
+
+
+/**
+ * Asynchronously lookup user information, calling callback when receive result.
+ *
+ * @param session
+ * @param user The user id, email address, or username.
+ * @param cb Callback, called with user information when available.
+ * @param data An arbitray data pointer passed to the callback.
+ */
+/* TODO: change to not use callbacks */
+void msim_lookup_user(MsimSession *session, const gchar *user, MSIM_USER_LOOKUP_CB cb, gpointer data)
+{
+    gchar *field_name;
+    guint rid, cmd, dsn, lid;
+
+    g_return_if_fail(MSIM_SESSION_VALID(session));
+    g_return_if_fail(user != NULL);
+    g_return_if_fail(cb != NULL);
+
+    purple_debug_info("msim", "msim_lookup_userid: "
+			"asynchronously looking up <%s>\n", user);
+
+	msim_msg_dump("msim_lookup_user: data=%s\n", (MsimMessage *)data);
+
+    /* TODO: check if this user's info was cached and fresh; if so return immediately */
+#if 0
+    /* If already know userid, then call callback immediately */
+    cached_userid = g_hash_table_lookup(session->userid_cache, who);
+    if (cached_userid && !by_userid)
+    {
+        cb(cached_userid, NULL, NULL, data);
+        return;
+    }
+#endif
+
+    /* Setup callback. Response will be associated with request using 'rid'. */
+    rid = msim_new_reply_callback(session, cb, data);
+
+    /* Send request */
+
+    cmd = MSIM_CMD_GET;
+
+    if (msim_is_userid(user))
+    {
+        field_name = "UserID";
+        dsn = MG_MYSPACE_INFO_BY_ID_DSN; 
+        lid = MG_MYSPACE_INFO_BY_ID_LID; 
+    } else if (msim_is_email(user)) {
+        field_name = "Email";
+        dsn = MG_MYSPACE_INFO_BY_STRING_DSN;
+        lid = MG_MYSPACE_INFO_BY_STRING_LID;
+    } else {
+        field_name = "UserName";
+        dsn = MG_MYSPACE_INFO_BY_STRING_DSN;
+        lid = MG_MYSPACE_INFO_BY_STRING_LID;
+    }
+
+
+	g_return_if_fail(msim_send(session,
+			"persist", MSIM_TYPE_INTEGER, 1,
+			"sesskey", MSIM_TYPE_INTEGER, session->sesskey,
+			"cmd", MSIM_TYPE_INTEGER, 1,
+			"dsn", MSIM_TYPE_INTEGER, dsn,
+			"uid", MSIM_TYPE_INTEGER, session->userid,
+			"lid", MSIM_TYPE_INTEGER, lid,
+			"rid", MSIM_TYPE_INTEGER, rid,
+			/* TODO: dictionary field type */
+			"body", MSIM_TYPE_STRING, g_strdup_printf("%s=%s", field_name, user),
+			NULL));
+} 
+
+
+/**
+ * Obtain the status text for a buddy.
+ *
+ * @param buddy The buddy to obtain status text for.
+ *
+ * @return Status text, or NULL if error. Caller g_free()'s.
+ *
+ */
+char *msim_status_text(PurpleBuddy *buddy)
+{
+    MsimSession *session;
+	const gchar *display_name, *headline;
+
+    g_return_val_if_fail(buddy != NULL, NULL);
+
+    session = (MsimSession *)buddy->account->gc->proto_data;
+    g_return_val_if_fail(MSIM_SESSION_VALID(session), NULL);
+
+	display_name = headline = NULL;
+
+	/* Retrieve display name and/or headline, depending on user preference. */
+    if (purple_account_get_bool(session->account, "show_display_name", TRUE))
+	{
+		display_name = purple_blist_node_get_string(&buddy->node, "DisplayName");
+	} 
+
+    if (purple_account_get_bool(session->account, "show_headline", FALSE))
+	{
+		headline = purple_blist_node_get_string(&buddy->node, "Headline");
+	}
+
+	/* Return appropriate combination of display name and/or headline, or neither. */
+
+	if (display_name && headline)
+		return g_strconcat(display_name, " ", headline, NULL);
+
+	if (display_name)
+		return g_strdup(display_name);
+
+	if (headline)
+		return g_strdup(headline);
+
+	return NULL;
+}
+
+/**
+ * Obtain the tooltip text for a buddy.
+ *
+ * @param buddy Buddy to obtain tooltip text on.
+ * @param user_info Variable modified to have the tooltip text.
+ * @param full TRUE if should obtain full tooltip text.
+ *
+ */
+void msim_tooltip_text(PurpleBuddy *buddy, PurpleNotifyUserInfo *user_info, gboolean full)
+{
+    g_return_if_fail(buddy != NULL);
+    g_return_if_fail(user_info != NULL);
+
+    if (PURPLE_BUDDY_IS_ONLINE(buddy))
+    {
+        MsimSession *session;
+
+        session = (MsimSession *)buddy->account->gc->proto_data;
+
+        g_return_if_fail(MSIM_SESSION_VALID(session));
+
+        /* TODO: if (full), do something different */
+		
+		/* TODO: move to buddy profile 
+		purple_notify_user_info_add_pair(user_info, "User ID",
+				g_strdup_printf("%d", purple_blist_node_get_int(&buddy->node, "UserID")));
+				*/
+
+		/* 	Already shown in status text. 
+		purple_notify_user_info_add_pair(user_info, "Display Name",
+				purple_blist_node_get_string(&buddy->node, "DisplayName")); */
+
+		/* Useful to identify the account the tooltip refers to. Other prpls show this. */
+		purple_notify_user_info_add_pair(user_info, "Account",
+				purple_blist_node_get_string(&buddy->node, "UserName")); 
+
+
+		/* a/s/l...the vitals */	
+		purple_notify_user_info_add_pair(user_info, "Age",
+				g_strdup_printf("%d", purple_blist_node_get_int(&buddy->node, "Age")));
+
+		purple_notify_user_info_add_pair(user_info, "Gender",
+				 purple_blist_node_get_string(&buddy->node, "Gender"));
+
+		purple_notify_user_info_add_pair(user_info, "Location",
+				purple_blist_node_get_string(&buddy->node, "Location"));
+
+		/* Other information */
+ 		if (purple_blist_node_get_string(&buddy->node, "Headline"))
+			purple_notify_user_info_add_pair(user_info, "Headline",
+					purple_blist_node_get_string(&buddy->node, "Headline")); 
+
+	    purple_notify_user_info_add_pair(user_info, "Song", 
+                g_strdup_printf("%s - %s",
+					purple_blist_node_get_string(&buddy->node, "BandName"),
+					purple_blist_node_get_string(&buddy->node, "SongName")));
+
+		purple_notify_user_info_add_pair(user_info, "Total Friends",
+				g_strdup_printf("%d", purple_blist_node_get_int(&buddy->node, "TotalFriends")));
+
+    }
+}
+
+/** Callbacks called by Purple, to access this plugin. */
+PurplePluginProtocolInfo prpl_info =
+{
+    OPT_PROTO_MAIL_CHECK,/* options - TODO: myspace will notify of mail */
+    NULL,              /* user_splits */
+    NULL,              /* protocol_options */
+    NO_BUDDY_ICONS,    /* icon_spec - TODO: eventually should add this */
+    msim_list_icon,    /* list_icon */
+    NULL,              /* list_emblems */
+    msim_status_text,  /* status_text */
+    msim_tooltip_text, /* tooltip_text */
+    msim_status_types, /* status_types */
+    NULL,              /* blist_node_menu */
+    NULL,              /* chat_info */
+    NULL,              /* chat_info_defaults */
+    msim_login,        /* login */
+    msim_close,        /* close */
+    msim_send_im,      /* send_im */
+    NULL,              /* set_info */
+    msim_send_typing,  /* send_typing */
+	msim_get_info, 	   /* get_info */
+    NULL,              /* set_away */
+    NULL,              /* set_idle */
+    NULL,              /* change_passwd */
+    msim_add_buddy,    /* add_buddy */
+    NULL,              /* add_buddies */
+    msim_remove_buddy, /* remove_buddy */
+    NULL,              /* remove_buddies */
+    NULL,              /* add_permit */
+    NULL,              /* add_deny */
+    NULL,              /* rem_permit */
+    NULL,              /* rem_deny */
+    NULL,              /* set_permit_deny */
+    NULL,              /* join_chat */
+    NULL,              /* reject chat invite */
+    NULL,              /* get_chat_name */
+    NULL,              /* chat_invite */
+    NULL,              /* chat_leave */
+    NULL,              /* chat_whisper */
+    NULL,              /* chat_send */
+    NULL,              /* keepalive */
+    NULL,              /* register_user */
+    NULL,              /* get_cb_info */
+    NULL,              /* get_cb_away */
+    NULL,              /* alias_buddy */
+    NULL,              /* group_buddy */
+    NULL,              /* rename_group */
+    NULL,              /* buddy_free */
+    NULL,              /* convo_closed */
+    NULL,              /* normalize */
+    NULL,              /* set_buddy_icon */
+    NULL,              /* remove_group */
+    NULL,              /* get_cb_real_name */
+    NULL,              /* set_chat_topic */
+    NULL,              /* find_blist_chat */
+    NULL,              /* roomlist_get_list */
+    NULL,              /* roomlist_cancel */
+    NULL,              /* roomlist_expand_category */
+    NULL,              /* can_receive_file */
+    NULL,              /* send_file */
+    NULL,              /* new_xfer */
+    msim_offline_message, /* offline_message */
+    NULL,              /* whiteboard_prpl_ops */
+    NULL,              /* send_raw */
+    NULL,              /* roomlist_room_serialize */
+	NULL,			   /* _purple_reserved1 */
+	NULL,			   /* _purple_reserved2 */
+	NULL,			   /* _purple_reserved3 */
+	NULL 			   /* _purple_reserved4 */
+};
+
+
+
+/** Based on MSN's plugin info comments. */
+PurplePluginInfo info =
+{
+    PURPLE_PLUGIN_MAGIC,                                
+    PURPLE_MAJOR_VERSION,
+    PURPLE_MINOR_VERSION,
+    PURPLE_PLUGIN_PROTOCOL,                            /**< type           */
+    NULL,                                              /**< ui_requirement */
+    0,                                                 /**< flags          */
+    NULL,                                              /**< dependencies   */
+    PURPLE_PRIORITY_DEFAULT,                           /**< priority       */
+
+    "prpl-myspace",                                   /**< id             */
+    "MySpaceIM",                                      /**< name           */
+    "0.7",                                            /**< version        */
+                                                      /**  summary        */
+    "MySpaceIM Protocol Plugin",
+                                                      /**  description    */
+    "MySpaceIM Protocol Plugin",
+    "Jeff Connelly <myspaceim@xyzzy.cjb.net>",        /**< author         */
+    "http://developer.pidgin.im/wiki/MySpaceIM/",     /**< homepage       */
+
+    msim_load,                                        /**< load           */
+    NULL,                                             /**< unload         */
+    NULL,                                             /**< destroy        */
+    NULL,                                             /**< ui_info        */
+    &prpl_info,                                       /**< extra_info     */
+    NULL,                                             /**< prefs_info     */
+
+    /* msim_actions */
+    NULL,
+
+	NULL,											  /**< reserved1      */
+	NULL,											  /**< reserved2      */
+	NULL,											  /**< reserved3      */
+	NULL 											  /**< reserved4      */
+};
+
+void init_plugin(PurplePlugin *plugin) 
+{
+	PurpleAccountOption *option;
+#ifdef  _TEST_MSIM_MSG
+	{
+		MsimMessage *msg;
+
+		purple_debug_info("msim", "testing MsimMessage\n");
+		msg = msim_msg_new(FALSE);
+		msg = msim_msg_append(msg, "bx", MSIM_TYPE_BINARY, g_string_new_len(g_strdup("XXX"), 3));
+		msg = msim_msg_append(msg, "k1", MSIM_TYPE_STRING, g_strdup("v1"));
+		msg = msim_msg_append(msg, "k1", MSIM_TYPE_INTEGER, GUINT_TO_POINTER(42));
+		msg = msim_msg_append(msg, "k1", MSIM_TYPE_STRING, g_strdup("v43"));
+		msg = msim_msg_append(msg, "k1", MSIM_TYPE_STRING, g_strdup("v52/xxx\\yyy"));
+		msg = msim_msg_append(msg, "k1", MSIM_TYPE_STRING, g_strdup("v7"));
+		purple_debug_info("msim", "msg debug str=%s\n", msim_msg_debug_string(msg));
+		msim_msg_debug_dump("msg debug str=%s\n", msg);
+		purple_debug_info("msim", "msg packed=%s\n", msim_msg_pack(msg));
+		purple_debug_info("msim", "msg cloned=%s\n", msim_msg_pack(msim_msg_clone(msg)));
+		msim_msg_free(msg);
+		exit(0);
+	}
+#endif
+
+	/* TODO: default to automatically try different ports. Make the user be
+	 * able to set the first port to try (like LastConnectedPort in Windows client).  */
+	option = purple_account_option_string_new(_("Connect server"), "server", MSIM_SERVER);
+	prpl_info.protocol_options = g_list_append(prpl_info.protocol_options, option);
+
+	option = purple_account_option_int_new(_("Connect port"), "port", MSIM_PORT);
+	prpl_info.protocol_options = g_list_append(prpl_info.protocol_options, option);
+
+	option = purple_account_option_bool_new(_("Show display name in status text"), "show_display_name", TRUE);
+	prpl_info.protocol_options = g_list_append(prpl_info.protocol_options, option);
+
+	option = purple_account_option_bool_new(_("Show headline in status text"), "show_headline", TRUE);
+	prpl_info.protocol_options = g_list_append(prpl_info.protocol_options, option);
+}
+
+PURPLE_INIT_PLUGIN(myspace, init_plugin, info);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libpurple/protocols/myspace/myspace.h	Mon Jun 18 01:48:35 2007 +0000
@@ -0,0 +1,253 @@
+/* MySpaceIM Protocol Plugin, header file
+ *
+ * Copyright (C) 2007, Jeff Connelly <jeff2@homing.pidgin.im>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+#ifndef _MYSPACE_MYSPACE_H
+#define _MYSPACE_MYSPACE_H
+
+/* Other includes */
+#include <string.h>
+#include <errno.h>	/* for EAGAIN */
+#include <stdarg.h>
+
+#include <glib.h>
+
+#ifdef _WIN32
+#include "win32dep.h"
+#else
+/* For recv() and send(); needed to match Win32 */
+#include <sys/types.h>
+#include <sys/socket.h>
+#endif
+
+#include "internal.h"
+
+#include "notify.h"
+#include "plugin.h"
+#include "accountopt.h"
+#include "version.h"
+#include "cipher.h"     /* for SHA-1 */
+#include "util.h"       /* for base64 */
+#include "debug.h"      /* for purple_debug_info */
+
+
+/* MySpaceIM includes */
+#include "message.h"
+
+/* Conditional compilation options */
+
+/* Debugging options */
+#define MSIM_DEBUG_MSG					
+/* Low-level and rarely needed */
+/*#define MSIM_DEBUG_PARSE 				*/
+/*#define MSIM_DEBUG_LOGIN_CHALLENGE	*/
+/*#define MSIM_DEBUG_RXBUF				*/
+
+/* RC4 didn't make it into Libpurple 2.0.0's cipher suite, so we have
+ * to use our own RC4 code (from Samba) by not defining this. */
+/* RC4 is in Libpurple 2.0.1, so define this. */
+#define MSIM_USE_PURPLE_RC4			
+
+/* TODO: when RC4 makes it into libpurple, use the PURPLE_VERSION_CHECK 
+ * macro to conditionally compile. And then later, get rid of our own
+ * RC4 code and only support libpurple with RC4. */
+
+/* Constants */
+
+/* Build version of MySpaceIM to report to servers (1.0.xxx.0) */
+#define MSIM_CLIENT_VERSION     673
+
+/* Server */
+#define MSIM_SERVER         "im.myspace.akadns.net"
+//#define MSIM_SERVER         "localhost"
+#define MSIM_PORT           1863        /* TODO: alternate ports and automatic */
+
+/* Constants */
+#define HASH_SIZE           0x14        /**< Size of SHA-1 hash for login */
+#define NONCE_SIZE          0x20        /**< Half of decoded 'nc' field */
+#define MSIM_READ_BUF_SIZE  (5 * 1024)  /**< Receive buffer size */
+#define MSIM_FINAL_STRING   "\\final\\" /**< Message end marker */
+
+/* Messages */
+#define MSIM_BM_INSTANT     1
+#define MSIM_BM_STATUS      100
+#define MSIM_BM_ACTION      121
+/* #define MSIM_BM_UNKNOWN1    122 */
+
+/* Authentication algorithm for login2 */
+#define MSIM_AUTH_ALGORITHM	196610
+
+/* Indexes into status string (0|1|2|3|..., but 0 always empty) */
+#define MSIM_STATUS_ORDINAL_EMPTY		0
+#define MSIM_STATUS_ORDINAL_UNKNOWNs	1
+#define MSIM_STATUS_ORDINAL_ONLINE		2
+#define MSIM_STATUS_ORDINAL_UNKNOWNss	3
+#define MSIM_STATUS_ORDINAL_HEADLINE	4
+#define MSIM_STATUS_ORDINAL_UNKNOWNls	5
+#define MSIM_STATUS_ORDINAL_UNKNOWN		6
+#define MSIM_STATUS_ORDINAL_UNKNOWN1	7
+#define MSIM_STATUS_ORDINAL_UNKNOWNp	8
+#define MSIM_STATUS_ORDINAL_UNKNOWN2	9
+
+/* Random number in every MsimSession, to ensure it is valid. */
+#define MSIM_SESSION_STRUCT_MAGIC       0xe4a6752b
+
+/* Everything needed to keep track of a session. */
+typedef struct _MsimSession
+{
+    guint magic;                        /**< MSIM_SESSION_STRUCT_MAGIC */
+    PurpleAccount *account;
+    PurpleConnection *gc;
+    guint sesskey;                      /**< Session key from server */
+    guint userid;                       /**< This user's numeric user ID */
+    gint fd;                            /**< File descriptor to/from server */
+
+	/* TODO: Remove. */
+    GHashTable *user_lookup_cb;         /**< Username -> userid lookup callback */
+    GHashTable *user_lookup_cb_data;    /**< Username -> userid lookup callback data */
+
+    gchar *rxbuf;                       /**< Receive buffer */
+    guint rxoff;                        /**< Receive buffer offset */
+	guint next_rid;						/**< Next request/response ID */
+} MsimSession;
+
+/* Check if an MsimSession is valid */
+#define MSIM_SESSION_VALID(s) (session != NULL && \
+		session->magic == MSIM_SESSION_STRUCT_MAGIC)
+
+/* Callback function pointer type for when a user's information is received, 
+ * initiated from a user lookup. */
+typedef void (*MSIM_USER_LOOKUP_CB)(MsimSession *session, MsimMessage *userinfo,
+          gpointer data);
+
+/* Functions */
+gboolean msim_load(PurplePlugin *plugin);
+GList *msim_status_types(PurpleAccount *acct);
+const gchar *msim_list_icon(PurpleAccount *acct, PurpleBuddy *buddy);
+
+/* TODO: move these three functions to message.c/h */
+gchar *msim_unescape(const gchar *msg);
+gchar *msim_escape(const gchar *msg);
+gchar *str_replace(const gchar *str, const gchar *old, const gchar *new);
+
+void print_hash_item(gpointer key, gpointer value, gpointer user_data);
+gboolean msim_send_raw(MsimSession *session, const gchar *msg);
+
+void msim_login(PurpleAccount *acct);
+gboolean msim_login_challenge(MsimSession *session, MsimMessage *msg);
+const gchar *msim_compute_login_response(const gchar nonce[2 * NONCE_SIZE],
+		        const gchar *email, const gchar *password, guint *response_len);
+
+
+int msim_send_im(PurpleConnection *gc, const gchar *who, const gchar *message, 
+	PurpleMessageFlags flags);
+gboolean msim_send_bm(MsimSession *session, const gchar *who, const gchar *text, int type);
+void msim_send_im_cb(MsimSession *session, MsimMessage *userinfo, gpointer data);
+
+int msim_incoming_im(MsimSession *session, MsimMessage *msg);
+int msim_incoming_action(MsimSession *session, MsimMessage *msg);
+
+unsigned int msim_send_typing(PurpleConnection *gc, const gchar *name, PurpleTypingState state);
+void msim_get_info(PurpleConnection *gc, const gchar *name);
+
+void msim_store_buddy_info_each(gpointer key, gpointer value, gpointer user_data);
+gboolean msim_store_buddy_info(MsimSession *session, MsimMessage *msg);
+gboolean msim_process_reply(MsimSession *session, MsimMessage *msg);
+
+gboolean msim_preprocess_incoming(MsimSession *session, MsimMessage *msg);
+
+gboolean msim_process(MsimSession *session, MsimMessage *msg);
+
+MsimMessage *msim_do_postprocessing(MsimMessage *msg, const gchar *uid_field_name, const gchar *uid_before, guint uid);
+void msim_postprocess_outgoing_cb(MsimSession *session, MsimMessage *userinfo, gpointer data);
+gboolean msim_postprocess_outgoing(MsimSession *session, MsimMessage *msg, const gchar *username, 
+	const gchar *uid_field_name, const gchar *uid_before);
+
+
+gboolean msim_error(MsimSession *session, MsimMessage *msg);
+gboolean msim_status(MsimSession *session, MsimMessage *msg);
+
+void msim_add_buddy(PurpleConnection *gc, PurpleBuddy *buddy, PurpleGroup *group);
+void msim_remove_buddy(PurpleConnection *gc, PurpleBuddy *buddy, PurpleGroup *group);
+
+gboolean msim_offline_message(const PurpleBuddy *buddy);
+
+void msim_input_cb(gpointer gc_uncasted, gint source, 
+		PurpleInputCondition cond);
+
+guint msim_new_reply_callback(MsimSession *session, MSIM_USER_LOOKUP_CB cb, gpointer data);
+
+void msim_connect_cb(gpointer data, gint source, 
+		const gchar *error_message);
+
+MsimSession *msim_session_new(PurpleAccount *acct);
+void msim_session_destroy(MsimSession *session);
+
+void msim_close(PurpleConnection *gc);
+
+gboolean msim_is_userid(const gchar *user);
+gboolean msim_is_email(const gchar *user);
+
+void msim_lookup_user(MsimSession *session, const gchar *user, 
+		MSIM_USER_LOOKUP_CB cb, gpointer data);
+
+char *msim_status_text(PurpleBuddy *buddy);
+void msim_tooltip_text(PurpleBuddy *buddy, 
+		PurpleNotifyUserInfo *user_info, gboolean full);
+
+void init_plugin(PurplePlugin *plugin);
+
+#ifndef MSIM_USE_PURPLE_RC4
+/* 
+   Unix SMB/CIFS implementation.
+
+   a partial implementation of RC4 designed for use in the 
+   SMB authentication protocol
+
+   Copyright (C) Andrew Tridgell 1998
+
+   $Id: crypt-rc4.h 12116 2004-09-27 23:29:22Z guy $
+   
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 2 of the License, or
+   (at your option) any later version.
+   
+   This program is distributed in the hope that it will be useful,
+   but WITHOUT ANY WARRANTY; without even the implied warranty of
+   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+   GNU General Public License for more details.
+   
+   You should have received a copy of the GNU General Public License
+   along with this program; if not, write to the Free Software
+   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+*/
+
+typedef struct _rc4_state_struct {
+  guchar s_box[256];
+  guchar index_i;
+  guchar index_j;
+} rc4_state_struct;
+
+void crypt_rc4_init(rc4_state_struct *rc4_state,
+            const guchar *key, int key_len);
+
+void crypt_rc4(rc4_state_struct *rc4_state, guchar *data, int data_len);
+#endif	/* !MSIM_USE_PURPLE_RC4 */
+
+#endif /* !_MYSPACE_MYSPACE_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/libpurple/protocols/myspace/persist.h	Mon Jun 18 01:48:35 2007 +0000
@@ -0,0 +1,88 @@
+/* MySpaceIM Protocol Plugin, persist commands
+ *
+ * Copyright (C) 2007, Jeff Connelly <jeff2@homing.pidgin.im>
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
+ */
+
+#ifndef _MYSPACE_PERSIST_H
+#define _MYSPACE_PERSIST_H
+
+/** Command codes */
+#define MSIM_CMD_GET			1
+#define MSIM_CMD_PUT			2
+#define MSIM_CMD_DELETE			3
+
+/** Command bit fields */
+#define MSIM_CMD_BIT_CODE		255			/*< Bits specifying command code */
+#define MSIM_CMD_BIT_REPLY		256			/**< 1=reply, 0=request */
+#define MSIM_CMD_BIT_ACTION		512			/**< 1=action, 0=information */
+#define MSIM_CMD_BIT_ERROR		1024		/**< 1=error, 0=normal */
+
+/** Macros to read cmd bitfield. */
+#define MSIM_CMD_GET_CODE(x)	 (x & MSIM_CMD_BIT_CODE)
+#define MSIM_CMD_IS_REPLY(x)	 (x & MSIM_CMD_BIT_REPLY)
+#define MSIM_CMD_IS_REQUEST(x)	!(x & MSIM_CMD_BIT_REPLY)
+#define MSIM_CMD_IS_ACTION(x)	 (x & MSIM_CMD_BIT_ACTION)
+#define MSIM_CMD_IS_INFO(x)		!(x & MSIM_CMD_BIT_ACTION)
+#define MSIM_CMD_IS_ERROR(x)	 (x & MSIM_CMD_BIT_ERROR)
+#define MSIM_CMD_IS_NORMAL(x)	!(x & MSIM_CMD_BIT_ERROR)
+
+/** Define a set of _DSN and _LID constants for a persistance request. */
+#define MSIM_PERSIST_DSN_LID(name,dsn,lid) 			\
+	const int name##_DSN = dsn;						\
+	const int name##_LID = lid;						
+
+/* Can't do this, errors:
+ * 	persist.h:51:3: error: '#' is not followed by a macro parameter
+ *  In file included from myspace.c:37:
+ *  persist.h:56: error: expected ')' before numeric constant
+ * So instead, I define const ints above.
+#define MSIM_PERSIST_DSN_LID(name,dsn,lid) 			\
+	#define name##_DSN		dsn						\
+	#define name##_LID		lid
+#endif
+*/
+
+/** Messages to Get information */
+MSIM_PERSIST_DSN_LID(MG_LIST_ALL_CONTACTS, 		0, 1)
+MSIM_PERSIST_DSN_LID(MG_USER_INFO_BY_ID, 		0, 2)
+MSIM_PERSIST_DSN_LID(MG_IM_INFO_BY_ID, 			1, 17)
+MSIM_PERSIST_DSN_LID(MG_LIST_ALL_GROUPS,		2, 6)
+MSIM_PERSIST_DSN_LID(MG_MYSPACE_INFO_BY_ID, 	4, 3)
+MSIM_PERSIST_DSN_LID(MG_OWN_MYSPACE_INFO,  	    4, 5)
+MSIM_PERSIST_DSN_LID(MG_MYSPACE_INFO_BY_STRING, 5, 7)
+MSIM_PERSIST_DSN_LID(MG_CHECK_MAIL,				7, 18)
+MSIM_PERSIST_DSN_LID(MG_WEB_CHALLENGE,			17, 26)
+MSIM_PERSIST_DSN_LID(MG_USER_SONG,				21, 28)
+MSIM_PERSIST_DSN_LID(MG_SERVER_INFO,			101, 20)
+
+/** Messages to Change/send information */
+MSIM_PERSIST_DSN_LID(MC_USER_PREFERENCES,		1, 10)
+MSIM_PERSIST_DSN_LID(MC_CONTACT_INFO,			0, 9)
+MSIM_PERSIST_DSN_LID(MC_INVITE,					16, 25)
+
+/** Messages to Delete information */
+MSIM_PERSIST_DSN_LID(MD_DELETE_BUDDY,			0, 8)
+
+/** Error codes */
+#define MERR_PARSE					1
+#define MERR_NOT_LOGGED_IN			2
+#define MERR_ANOTHER_LOGIN			6
+#define MERR_BAD_EMAIL				259
+#define MERR_BAD_PASSWORD			260
+#define MERR_BAD_UID_IN_PERSISTR	4352
+
+#endif /* !_MYSPACE_PERSIST_H */
--- a/libpurple/purple-url-handler	Fri Jun 15 02:57:13 2007 +0000
+++ b/libpurple/purple-url-handler	Mon Jun 18 01:48:35 2007 +0000
@@ -44,6 +44,12 @@
     else:
         return list
 
+def convert(value):
+    try:
+        return int(value)
+    except:
+        return value
+
 def findaccount(protocolname, accountname=""):
     # prefer connected accounts
     account = cpurple.PurpleAccountsFindConnected(accountname, protocolname)
@@ -84,6 +90,32 @@
     cpurple.PurpleBlistRequestAddBuddy(account, screenname, group, alias)
 
 
+def aim(uri):
+    protocol = "prpl-aim"
+    match = re.match(r"^aim:([^?]*)(\?(.*))", uri)
+    if not match:
+        print "Invalid aim URI: %s" % uri
+        return
+
+    command = urllib.unquote_plus(match.group(1))
+    paramstring = match.group(3)
+    params = {}
+    if paramstring:
+        for param in paramstring.split("&"):
+            key, value = extendlist(param.split("=", 1), 2, "")
+            params[key] = urllib.unquote_plus(value)
+    accountname = params.get("account", "")
+    screenname = params.get("screenname", "")
+
+    account = findaccount(protocol, accountname)
+
+    if command.lower() == "goim":
+        goim(account, screenname, params.get("message"))
+    elif command.lower() == "gochat":
+        gochat(account, params)
+    elif command.lower() == "addbuddy":
+        addbuddy(account, screenname, params.get("group", ""))
+
 def gg(uri):
     protocol = "prpl-gg"
     match = re.match(r"^gg:(.*)", uri)
@@ -95,6 +127,32 @@
     account = findaccount(protocol)
     goim(account, screenname)
 
+def icq(uri):
+    protocol = "prpl-icq"
+    match = re.match(r"^icq:([^?]*)(\?(.*))", uri)
+    if not match:
+        print "Invalid icq URI: %s" % uri
+        return
+
+    command = urllib.unquote_plus(match.group(1))
+    paramstring = match.group(3)
+    params = {}
+    if paramstring:
+        for param in paramstring.split("&"):
+            key, value = extendlist(param.split("=", 1), 2, "")
+            params[key] = urllib.unquote_plus(value)
+    accountname = params.get("account", "")
+    screenname = params.get("screenname", "")
+
+    account = findaccount(protocol, accountname)
+
+    if command.lower() == "goim":
+        goim(account, screenname, params.get("message"))
+    elif command.lower() == "gochat":
+        gochat(account, params)
+    elif command.lower() == "addbuddy":
+        addbuddy(account, screenname, params.get("group", ""))
+
 def irc(uri):
     protocol = "prpl-irc"
     match = re.match(r"^irc:(//([^/]*)/)?([^?]*)(\?(.*))?", uri)
@@ -131,6 +189,34 @@
                 channel = "#" + channel
             gochat(account, {"server": server, "channel": channel, "password": params.get("key", "")}, params.get("msg"))
 
+def msnim(uri):
+    protocol = "prpl-msn"
+    match = re.match(r"^msnim:([^?]*)(\?(.*))", uri)
+    if not match:
+        print "Invalid msnim URI: %s" % uri
+        return
+
+    command = urllib.unquote_plus(match.group(1))
+    paramstring = match.group(3)
+    params = {}
+    if paramstring:
+        for param in paramstring.split("&"):
+            key, value = extendlist(param.split("=", 1), 2, "")
+            params[key] = urllib.unquote_plus(value)
+    screenname = params.get("contact", "")
+
+    account = findaccount(protocol)
+
+    if command.lower() == "chat":
+        goim(account, screenname)
+    elif command.lower() == "add":
+        addbuddy(account, screenname)
+
+def myim(uri):
+	protocol = "prpl-myspace"
+	print "TODO: send uri: ", uri
+	assert False, "Not implemented"
+
 def sip(uri):
     protocol = "prpl-simple"
     match = re.match(r"^sip:(.*)", uri)
@@ -182,6 +268,32 @@
     else:
         goim(account, screenname)
 
+def ymsgr(uri):
+    protocol = "prpl-yahoo"
+    match = re.match(r"^ymsgr:([^?]*)(\?([^&]*)(&(.*))?)", uri)
+    if not match:
+        print "Invalid ymsgr URI: %s" % uri
+        return
+
+    command = urllib.unquote_plus(match.group(1))
+    screenname = urllib.unquote_plus(match.group(3))
+    paramstring = match.group(5)
+    params = {}
+    if paramstring:
+        for param in paramstring.split("&"):
+            key, value = extendlist(param.split("=", 1), 2, "")
+            params[key] = urllib.unquote_plus(value)
+
+    account = findaccount(protocol)
+
+    if command.lower() == "sendim":
+        goim(account, screenname, params.get("m"))
+    elif command.lower() == "chat":
+        gochat(account, {"room": screenname})
+    elif command.lower() == "addfriend":
+        addbuddy(account, screenname)
+
+
 def main(argv=sys.argv):
     if len(argv) != 2:
         print "Usage: %s URI" % argv[0]
@@ -192,16 +304,26 @@
     type = uri.split(":")[0]
 
     try:
-        if type == "gg":
+        if type == "aim":
+            aim(uri)
+        elif type == "gg":
             gg(uri)
+        elif type == "icq":
+            icq(uri)
         elif type == "irc":
             irc(uri)
+        elif type == "msnim":
+            msnim(uri)
+        elif type == "myim":
+            myim(uri)
         elif type == "sip":
             sip(uri)
         elif type == "xmpp":
             xmpp(uri)
+        elif type == "ymsgr":
+            ymsgr(uri)
         else:
-            cpurple.PurpleGotProtocolHandlerUri(uri)
+            print "Unknown protocol: %s" % type
     except dbus.dbus_bindings.DBusException:
         print "ERROR: Is there a libpurple-powered client (e.g. Pidgin or Finch) running?"
 
--- a/pidgin/pixmaps/protocols/16/Makefile.am	Fri Jun 15 02:57:13 2007 +0000
+++ b/pidgin/pixmaps/protocols/16/Makefile.am	Mon Jun 18 01:48:35 2007 +0000
@@ -10,6 +10,7 @@
 		jabber.png \
 		meanwhile.png \
 		msn.png \
+		myspace.png \
 		qq.png \
 		silc.png \
 		simple.png \
Binary file pidgin/pixmaps/protocols/16/myspace.png has changed
--- a/pidgin/pixmaps/protocols/22/Makefile.am	Fri Jun 15 02:57:13 2007 +0000
+++ b/pidgin/pixmaps/protocols/22/Makefile.am	Mon Jun 18 01:48:35 2007 +0000
@@ -10,6 +10,7 @@
 		jabber.png \
 		meanwhile.png \
 		msn.png \
+		myspace.png \
 		qq.png \
 		silc.png \
 		simple.png \
Binary file pidgin/pixmaps/protocols/22/myspace.png has changed
--- a/pidgin/pixmaps/protocols/48/Makefile.am	Fri Jun 15 02:57:13 2007 +0000
+++ b/pidgin/pixmaps/protocols/48/Makefile.am	Mon Jun 18 01:48:35 2007 +0000
@@ -9,6 +9,7 @@
 		jabber.png \
 		meanwhile.png \
 		msn.png \
+		myspace.png \
 		qq.png \
 		silc.png \
 		simple.png \
Binary file pidgin/pixmaps/protocols/48/myspace.png has changed
--- a/po/POTFILES.in	Fri Jun 15 02:57:13 2007 +0000
+++ b/po/POTFILES.in	Mon Jun 18 01:48:35 2007 +0000
@@ -95,6 +95,7 @@
 libpurple/protocols/msn/state.c
 libpurple/protocols/msn/switchboard.c
 libpurple/protocols/msn/userlist.c
+libpurple/protocols/myspace/myspace.c
 libpurple/protocols/novell/nmuser.c
 libpurple/protocols/novell/novell.c
 libpurple/protocols/oscar/flap_connection.c