goget-ubuntu-touch-0.34/ 0000775 0001750 0001750 00000000000 12700710721 015106 5 ustar egon egon 0000000 0000000 goget-ubuntu-touch-0.34/dependencies.tsv 0000664 0001750 0001750 00000001024 12700666314 020277 0 ustar egon egon 0000000 0000000 github.com/blakesmith/ar git 8bd4349a67f2533b078dbc524689d15dba0f4659 2015-03-11T14:59:44Z
github.com/cheggaaa/pb git da1f27ad1d9509b16f65f52fd9d8138b0f2dc7b2 2015-08-13T11:06:09Z
github.com/gosexy/gettext git 98b7b91596d20b96909e6b60d57411547dd9959c 2013-02-21T11:21:43Z
github.com/jessevdk/go-flags git 4047bd797dd935ae2b557a79cc43f223066c9659 2015-10-18T21:15:10Z
gopkg.in/yaml.v2 git 7ad95dd0798a40da1ccdff6dff35fd177b5edf40 2015-06-24T10:29:02Z
launchpad.net/gocheck bzr gustavo@niemeyer.net-20140225173054-xu9zlkf9kxhvow02 87
goget-ubuntu-touch-0.34/COPYING 0000664 0001750 0001750 00000077246 12621156354 016171 0 ustar egon egon 0000000 0000000 GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. 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
them 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 prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. 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.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey 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;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If 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 convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU 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 that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
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.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
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.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
goget-ubuntu-touch-0.34/README 0000664 0001750 0001750 00000000171 12621156354 015775 0 ustar egon egon 0000000 0000000 To build run:
$ sudo apt-get build-dep goget-ubuntu-touch
?!?! there is surely a better way
$ debian/rules clean build
goget-ubuntu-touch-0.34/run-checks 0000775 0001750 0001750 00000001515 12621156354 017110 0 ustar egon egon 0000000 0000000 #!/bin/sh
set -e
if which goctest >/dev/null; then
goctest="goctest"
else
goctest="go test"
fi
echo Checking formatting
fmt=$(gofmt -l .)
if [ -n "$fmt" ]; then
echo "Formatting wrong in following files"
echo $fmt
exit 1
fi
echo Installing godeps
go get launchpad.net/godeps
export PATH=$PATH:$GOPATH/bin
echo Install golint
go get github.com/golang/lint/golint
export PATH=$PATH:$GOPATH/bin
echo Obtaining dependencies
godeps -u dependencies.tsv
echo Building
go build -v launchpad.net/goget-ubuntu-touch/...
# tests
echo Running tests from $(pwd)
$goctest -v -cover ./...
# go vet
echo Running vet
go vet ./...
# golint
# TODO enable!
#echo Running lint
#lint=$(golint ./...)
#if [ -n "$lint" ]; then
# echo "Lint complains:"
# echo $lint
# exit 1
#fi
echo "All good, what could possibly go wrong"
goget-ubuntu-touch-0.34/ubuntuimage/ 0000775 0001750 0001750 00000000000 12700710721 017433 5 ustar egon egon 0000000 0000000 goget-ubuntu-touch-0.34/ubuntuimage/channels_test.go 0000664 0001750 0001750 00000035634 12621156354 022637 0 ustar egon egon 0000000 0000000 //
// Helpers to work with an Ubuntu image based Upgrade implementation
//
// Copyright (c) 2014 Canonical Ltd.
//
// Written by Sergio Schvezov
//
package ubuntuimage
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License version 3, as published
// by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranties of
// MERCHANTABILITY, SATISFACTORY QUALITY, 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, see .
import (
"errors"
"fmt"
. "launchpad.net/gocheck"
"net/http"
"net/http/httptest"
"testing"
)
const develChannelMako = `{
"global": {
"generated_at": "Thu Feb 20 10:10:47 UTC 2014"
},
"images": [
{
"description": "ubuntu=20140206,device=20140115.1,version=166",
"files": [
{
"checksum": "36deae060a01dea39bb6a42b4be963c19b88e1c600b405061d74cca7d241e34a",
"order": 0,
"path": "/pool/ubuntu-7b59094905d81305ee88d22f6468fd1ce74b515a3be8098848a90c8062a0e192.tar.xz",
"signature": "/pool/ubuntu-7b59094905d81305ee88d22f6468fd1ce74b515a3be8098848a90c8062a0e192.tar.xz.asc",
"size": 329233668
},
{
"checksum": "cd5e1da151e815f37539c0900f0b5635cb97d7632acfc793bb29c5b490f6d735",
"order": 1,
"path": "/pool/device-9d396bed22b036d92241420d70b4656ea3ef895a3b43274f936d764081b0d1e2.tar.xz",
"signature": "/pool/device-9d396bed22b036d92241420d70b4656ea3ef895a3b43274f936d764081b0d1e2.tar.xz.asc",
"size": 37135880
},
{
"checksum": "9ac8890b6b64ee8c0af24723976cabef16c57c89db262a559ca79af77091e720",
"order": 2,
"path": "/devel/mako/version-166.tar.xz",
"signature": "/devel/mako/version-166.tar.xz.asc",
"size": 344
}
],
"type": "full",
"version": 150
},
{
"description": "ubuntu=20140206,device=20140115.1,version=166",
"files": [
{
"checksum": "36deae060a01dea39bb6a42b4be963c19b88e1c600b405061d74cca7d241e34a",
"order": 0,
"path": "/pool/ubuntu-7b59094905d81305ee88d22f6468fd1ce74b515a3be8098848a90c8062a0e192.tar.xz",
"signature": "/pool/ubuntu-7b59094905d81305ee88d22f6468fd1ce74b515a3be8098848a90c8062a0e192.tar.xz.asc",
"size": 329233668
},
{
"checksum": "cd5e1da151e815f37539c0900f0b5635cb97d7632acfc793bb29c5b490f6d735",
"order": 1,
"path": "/pool/device-9d396bed22b036d92241420d70b4656ea3ef895a3b43274f936d764081b0d1e2.tar.xz",
"signature": "/pool/device-9d396bed22b036d92241420d70b4656ea3ef895a3b43274f936d764081b0d1e2.tar.xz.asc",
"size": 37135880
},
{
"checksum": "9ac8890b6b64ee8c0af24723976cabef16c57c89db262a559ca79af77091e720",
"order": 2,
"path": "/devel/mako/version-166.tar.xz",
"signature": "/devel/mako/version-166.tar.xz.asc",
"size": 344
}
],
"type": "full",
"version": 166
},
{
"base": 161,
"description": "ubuntu=20140206,device=20140115.1,version=166",
"files": [
{
"checksum": "621b201190c3a5ee0b2a4adc7f9823dbca6168374d03646d774e2044f43410f9",
"order": 0,
"path": "/pool/ubuntu-7b59094905d81305ee88d22f6468fd1ce74b515a3be8098848a90c8062a0e192.delta-ubuntu-d204c93d737253aa07088ffd7e5d060ad28e205c32d008379b4d70ec5f7c3ca4.tar.xz",
"signature": "/pool/ubuntu-7b59094905d81305ee88d22f6468fd1ce74b515a3be8098848a90c8062a0e192.delta-ubuntu-d204c93d737253aa07088ffd7e5d060ad28e205c32d008379b4d70ec5f7c3ca4.tar.xz.asc",
"size": 23963072
},
{
"checksum": "9ac8890b6b64ee8c0af24723976cabef16c57c89db262a559ca79af77091e720",
"order": 1,
"path": "/devel/mako/version-166.tar.xz",
"signature": "/devel/mako/version-166.tar.xz.asc",
"size": 344
}
],
"type": "delta",
"version": 166
}
]
}
`
const develChannelMakoOnlyDelta = `{
"global": {
"generated_at": "Thu Feb 20 10:10:47 UTC 2014"
},
"images": [
{
"base": 161,
"description": "ubuntu=20140206,device=20140115.1,version=166",
"files": [
{
"checksum": "621b201190c3a5ee0b2a4adc7f9823dbca6168374d03646d774e2044f43410f9",
"order": 0,
"path": "/pool/ubuntu-7b59094905d81305ee88d22f6468fd1ce74b515a3be8098848a90c8062a0e192.delta-ubuntu-d204c93d737253aa07088ffd7e5d060ad28e205c32d008379b4d70ec5f7c3ca4.tar.xz",
"signature": "/pool/ubuntu-7b59094905d81305ee88d22f6468fd1ce74b515a3be8098848a90c8062a0e192.delta-ubuntu-d204c93d737253aa07088ffd7e5d060ad28e205c32d008379b4d70ec5f7c3ca4.tar.xz.asc",
"size": 23963072
},
{
"checksum": "9ac8890b6b64ee8c0af24723976cabef16c57c89db262a559ca79af77091e720",
"order": 1,
"path": "/devel/mako/version-166.tar.xz",
"signature": "/devel/mako/version-166.tar.xz.asc",
"size": 344
}
],
"type": "delta",
"version": 166
}
]
}
`
const channels = `{
"devel": {
"alias": "trusty",
"devices": {
"flo": {
"index": "/devel/flo/index.json"
},
"generic": {
"index": "/devel/generic/index.json"
},
"goldfish": {
"index": "/devel/goldfish/index.json"
},
"grouper": {
"index": "/devel/grouper/index.json"
},
"maguro": {
"index": "/devel/maguro/index.json"
},
"mako": {
"index": "/devel/mako/index.json"
},
"manta": {
"index": "/devel/manta/index.json"
}
}
},
"devel-customized": {
"alias": "trusty-customized",
"devices": {
"flo": {
"index": "/devel-customized/flo/index.json"
},
"generic": {
"index": "/devel-customized/generic/index.json"
},
"goldfish": {
"index": "/devel-customized/goldfish/index.json"
},
"grouper": {
"index": "/devel-customized/grouper/index.json"
},
"maguro": {
"index": "/devel-customized/maguro/index.json"
},
"mako": {
"index": "/devel-customized/mako/index.json"
},
"manta": {
"index": "/devel-customized/manta/index.json"
}
}
}
}`
// Hook up gocheck into the "go test" runner.
func Test(t *testing.T) { TestingT(t) }
type DeviceChannelsSuite struct {
channels Channels
devices map[string]Device
ts *httptest.Server
}
var _ = Suite(&DeviceChannelsSuite{})
func (s *DeviceChannelsSuite) SetUpTest(c *C) {
s.devices = make(map[string]Device)
s.channels = make(map[string]Channel)
s.channels["trusty"] = Channel{
Devices: map[string]Device{"mako": Device{"/" + "trusty/mako/index.json"}}}
s.channels["touch/trusty"] = Channel{
Devices: map[string]Device{"mako": Device{"/" + "touch/trusty/mako/index.json"}}}
s.channels["touch/devel"] = Channel{
Devices: map[string]Device{"mako": Device{"/" + "touch/devel/mako/index.json"}},
Alias: "touch/trusty"}
s.ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, develChannelMako)
}))
}
func (s *DeviceChannelsSuite) TearDownTest(c *C) {
s.ts.Close()
}
func (s *DeviceChannelsSuite) TestChannelNotFoundWithNoChannels(c *C) {
s.channels = make(map[string]Channel)
channel := "trusty"
device := "mako"
expectedErr := fmt.Errorf("Channel %s not found on server %s", channel, s.ts.URL)
_, err := s.channels.GetDeviceChannel(s.ts.URL, channel, device)
c.Assert(err, DeepEquals, expectedErr)
}
func (s *DeviceChannelsSuite) TestChannelDeviceNotFoundInChannel(c *C) {
device := "hammerhead"
channel := "trusty"
expectedErr := fmt.Errorf("Device %s not found on server %s channel %s",
device, s.ts.URL, channel)
_, err := s.channels.GetDeviceChannel(s.ts.URL, channel, device)
c.Assert(err, DeepEquals, expectedErr)
}
func (s *DeviceChannelsSuite) TestChannelDeviceNotFoundInChannelWithSlash(c *C) {
device := "hammerhead"
channel := "touch/trusty"
expectedErr := fmt.Errorf("Device %s not found on server %s channel %s",
device, s.ts.URL, channel)
_, err := s.channels.GetDeviceChannel(s.ts.URL, channel, device)
c.Assert(err, DeepEquals, expectedErr)
}
func (s *DeviceChannelsSuite) TestChannelInvalidDataForDevice(c *C) {
s.ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Invalid data")
}))
device := "mako"
channel := "touch/trusty"
expectedErr := fmt.Errorf("Cannot parse channel information for device on %s",
s.ts.URL+"/"+channel+"/"+device+"/index.json")
_, err := s.channels.GetDeviceChannel(s.ts.URL, channel, device)
c.Assert(err, DeepEquals, expectedErr)
}
func (s *DeviceChannelsSuite) TestChannelValidDataForDevice(c *C) {
device := "mako"
channel := "touch/trusty"
images, err := s.channels.GetDeviceChannel(s.ts.URL, channel, device)
c.Assert(err, IsNil)
c.Assert(images, NotNil)
}
func (s *DeviceChannelsSuite) TestChannelValidDataForDeviceFromAlias(c *C) {
device := "mako"
channel := "touch/devel"
channelData, err := s.channels.GetDeviceChannel(s.ts.URL, channel, device)
c.Assert(err, IsNil)
c.Assert(channelData, NotNil)
c.Assert(channelData.Alias, Equals, "touch/trusty")
c.Assert(channelData.Images, NotNil)
}
func (s *DeviceChannelsSuite) TestGetLatestImageForChannel(c *C) {
device := "mako"
channel := "touch/devel"
channelData, err := s.channels.GetDeviceChannel(s.ts.URL, channel, device)
c.Assert(err, IsNil)
c.Assert(channelData, NotNil)
c.Assert(channelData.Alias, Equals, "touch/trusty")
c.Assert(channelData.Images, NotNil)
image, err := channelData.GetRelativeImage(0)
c.Assert(err, IsNil)
c.Check(image.Version, Equals, 166)
c.Check(image.Type, Equals, FULL_IMAGE)
c.Check(len(image.Files), Equals, 3)
}
func (s *DeviceChannelsSuite) TestFailsGetLatestImageForChannelWithOnlyDeltas(c *C) {
device := "mako"
channel := "touch/devel"
s.ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, develChannelMakoOnlyDelta)
}))
channelData, err := s.channels.GetDeviceChannel(s.ts.URL, channel, device)
c.Assert(err, IsNil)
c.Assert(channelData, NotNil)
c.Assert(channelData.Alias, Equals, "touch/trusty")
c.Assert(channelData.Images, NotNil)
expectedErr := errors.New("Failed to locate latest image information")
_, err = channelData.GetRelativeImage(0)
c.Assert(err, DeepEquals, expectedErr)
}
func (s *DeviceChannelsSuite) TestGetSpecificImageForChannel(c *C) {
device := "mako"
channel := "touch/devel"
channelData, err := s.channels.GetDeviceChannel(s.ts.URL, channel, device)
c.Assert(err, IsNil)
c.Assert(channelData, NotNil)
c.Assert(channelData.Alias, Equals, "touch/trusty")
c.Assert(channelData.Images, NotNil)
image, err := channelData.GetImage(166)
c.Assert(err, IsNil)
c.Check(image.Version, Equals, 166)
c.Check(image.Type, Equals, FULL_IMAGE)
c.Check(len(image.Files), Equals, 3)
}
func (s *DeviceChannelsSuite) TestGetSpecificRelativeImageForChannel(c *C) {
device := "mako"
channel := "touch/devel"
channelData, err := s.channels.GetDeviceChannel(s.ts.URL, channel, device)
c.Assert(err, IsNil)
c.Assert(channelData, NotNil)
c.Assert(channelData.Alias, Equals, "touch/trusty")
c.Assert(channelData.Images, NotNil)
image, err := channelData.GetRelativeImage(-1)
c.Assert(err, IsNil)
c.Check(image.Version, Equals, 150)
c.Check(image.Type, Equals, FULL_IMAGE)
c.Check(len(image.Files), Equals, 3)
}
func (s *DeviceChannelsSuite) TestFailGetRelativeImageForChannel(c *C) {
device := "mako"
channel := "touch/devel"
channelData, err := s.channels.GetDeviceChannel(s.ts.URL, channel, device)
c.Assert(err, IsNil)
c.Assert(channelData, NotNil)
c.Assert(channelData.Alias, Equals, "touch/trusty")
c.Assert(channelData.Images, NotNil)
rev := -5
_, err = channelData.GetRelativeImage(rev)
expectedErr := fmt.Errorf("Failed to locate relative image to latest - %d", -rev)
_, err = channelData.GetRelativeImage(rev)
c.Assert(err, DeepEquals, expectedErr)
}
func (s *DeviceChannelsSuite) TestFailGetSpecificImageForChannel(c *C) {
device := "mako"
channel := "touch/devel"
channelData, err := s.channels.GetDeviceChannel(s.ts.URL, channel, device)
c.Assert(err, IsNil)
c.Assert(channelData, NotNil)
c.Assert(channelData.Alias, Equals, "touch/trusty")
c.Assert(channelData.Images, NotNil)
rev := 162
expectedErr := fmt.Errorf("Failed to locate image %d", rev)
_, err = channelData.GetImage(rev)
c.Assert(err, DeepEquals, expectedErr)
}
type ChannelsSuite struct {
ts *httptest.Server
}
var _ = Suite(&ChannelsSuite{})
func (s *ChannelsSuite) SetUpTest(c *C) {
s.ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, channels)
}))
}
func (s *ChannelsSuite) TearDownTest(c *C) {
s.ts.Close()
}
func (s *ChannelsSuite) TestGetChannelsFromServer(c *C) {
channels, err := NewChannels(s.ts.URL)
c.Assert(err, IsNil)
c.Assert(channels, NotNil)
devel, develOk := channels["devel"]
c.Assert(develOk, Equals, true)
c.Check(devel.Alias, Equals, "trusty")
c.Check(len(devel.Devices), Equals, 7)
device, deviceOk := devel.Devices["flo"]
c.Assert(deviceOk, Equals, true)
c.Check(device.Index, Equals, "/devel/flo/index.json")
}
func (s *ChannelsSuite) TestInvalidDataWhenGetChannelsFromServer(c *C) {
s.ts = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Invalid data")
}))
expectedErr := fmt.Errorf("Unable to parse channel information from %s", s.ts.URL)
_, err := NewChannels(s.ts.URL)
c.Assert(err, DeepEquals, expectedErr)
}
goget-ubuntu-touch-0.34/ubuntuimage/channels.go 0000664 0001750 0001750 00000011000 12621156354 021555 0 ustar egon egon 0000000 0000000 //
// Helpers to work with an Ubuntu image based Upgrade implementation
//
// Copyright (c) 2013 Canonical Ltd.
//
// Written by Sergio Schvezov
//
package ubuntuimage
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License version 3, as published
// by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranties of
// MERCHANTABILITY, SATISFACTORY QUALITY, 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, see .
import (
_ "crypto/sha512"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
)
const (
channelsPath = "/channels.json"
indexName = "index.json"
FULL_IMAGE = "full"
)
var client = &http.Client{}
// TLSSkipVerify turns off validation of server TLS certificates. It allows connecting
// to HTTPS servers that use self-signed certificates.
func TLSSkipVerify() {
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
client = &http.Client{Transport: tr}
}
func NewChannels(server string) (channels Channels, err error) {
resp, err := client.Get(server + channelsPath)
if err != nil {
return channels, err
}
defer resp.Body.Close()
dec := json.NewDecoder(resp.Body)
if err := dec.Decode(&channels); err != nil {
return channels, fmt.Errorf("Unable to parse channel information from %s", server)
}
return channels, nil
}
func (channels Channels) GetDeviceChannel(server, channel, device string) (deviceChannel DeviceChannel, err error) {
if _, found := channels[channel]; !found {
return deviceChannel, fmt.Errorf("Channel %s not found on server %s", channel, server)
} else if _, found := channels[channel].Devices[device]; !found {
return deviceChannel, fmt.Errorf("Device %s not found on server %s channel %s",
device, server, channel)
}
channelUri := server + channels[channel].Devices[device].Index
resp, err := client.Get(channelUri)
if err != nil {
return deviceChannel, err
}
defer resp.Body.Close()
dec := json.NewDecoder(resp.Body)
err = dec.Decode(&deviceChannel)
if err != nil {
return deviceChannel, fmt.Errorf("Cannot parse channel information for device on %s", channelUri)
}
deviceChannel.Alias = channels[channel].Alias
order := func(i1, i2 *Image) bool {
return i1.Version > i2.Version
}
ImageBy(order).ImageSort(deviceChannel.Images)
deviceChannel.Url = channelUri
return deviceChannel, err
}
func (deviceChannel *DeviceChannel) GetImage(revision int) (image Image, err error) {
for _, image := range deviceChannel.Images {
if image.Type == FULL_IMAGE && image.Version == revision {
return image, nil
}
}
//If we reached this point, that means we haven't found the image we were looking for.
return image, fmt.Errorf("Failed to locate image %d", revision)
}
func (deviceChannel *DeviceChannel) ListImageVersions() (err error) {
jsonData := map[string]interface{}{}
resp, err := client.Get(deviceChannel.Url)
if err != nil {
return err
}
if resp.StatusCode != 200 {
statusErr := errors.New(fmt.Sprintf("Invalid HTTP response: %d", resp.StatusCode))
return statusErr
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
err = json.Unmarshal(body, &jsonData)
if err != nil {
return err
}
images := jsonData["images"].([]interface{})
for i := range images {
entry := images[i].(map[string]interface{})
imageType := entry["type"]
if imageType != FULL_IMAGE {
// ignore delta images as they cannot be used to
// perform an initial device flash
continue
}
fmt.Printf("%d: description='%s'\n",
int(entry["version"].(float64)),
entry["description"])
}
return nil
}
func (deviceChannel *DeviceChannel) GetRelativeImage(revision int) (image Image, err error) {
var steps int
if revision < 0 {
revision = -revision
}
for _, image := range deviceChannel.Images {
if image.Type != FULL_IMAGE {
continue
}
if steps == revision {
return image, nil
}
steps++
}
//If we reached this point, that means we haven't found the image we were looking for.
if revision == 0 {
err = errors.New("Failed to locate latest image information")
} else {
err = fmt.Errorf("Failed to locate relative image to latest - %d", revision)
}
return Image{}, err
}
goget-ubuntu-touch-0.34/ubuntuimage/sort.go 0000664 0001750 0001750 00000005155 12621156354 020767 0 ustar egon egon 0000000 0000000 //
// Helpers to work with an Ubuntu image based Upgrade implementation
//
// Copyright (c) 2013 Canonical Ltd.
//
// Written by Sergio Schvezov
//
package ubuntuimage
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License version 3, as published
// by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranties of
// MERCHANTABILITY, SATISFACTORY QUALITY, 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, see .
import (
"sort"
)
// By is the type of a "less" function that defines the ordering of its File arguments.
type By func(p1, p2 *File) bool
// Sort is a method on the function type, By, that sorts the argument slice according to the function.
func (by By) Sort(files []File) {
fs := &fileSorter{
files: files,
by: by,
}
sort.Sort(fs)
}
// fileSorter joins a By function and a slice of File to be sorted.
type fileSorter struct {
files []File
by func(p1, p2 *File) bool // Closure used in the Less method.
}
// Len is part of sort.Interface.
func (s *fileSorter) Len() int {
return len(s.files)
}
// Swap is part of sort.Interface.
func (s *fileSorter) Swap(i, j int) {
s.files[i], s.files[j] = s.files[j], s.files[i]
}
// Less is part of sort.Interface. It is implemented by calling the "by" closure in the sorter.
func (s *fileSorter) Less(i, j int) bool {
return s.by(&s.files[i], &s.files[j])
}
// By is the type of a "less" function that defines the ordering of its File arguments.
type ImageBy func(p1, p2 *Image) bool
// Sort is a method on the function type, By, that sorts the argument slice according to the function.
func (by ImageBy) ImageSort(images []Image) {
is := &imageSorter{
images: images,
by: by,
}
sort.Sort(is)
}
// fileSorter joins a By function and a slice of File to be sorted.
type imageSorter struct {
images []Image
by func(p1, p2 *Image) bool // Closure used in the Less method.
}
// Len is part of sort.Interface.
func (s *imageSorter) Len() int {
return len(s.images)
}
// Swap is part of sort.Interface.
func (s *imageSorter) Swap(i, j int) {
s.images[i], s.images[j] = s.images[j], s.images[i]
}
// Less is part of sort.Interface. It is implemented by calling the "by" closure in the sorter.
func (s *imageSorter) Less(i, j int) bool {
return s.by(&s.images[i], &s.images[j])
}
goget-ubuntu-touch-0.34/ubuntuimage/images.go 0000664 0001750 0001750 00000012212 12621156354 021235 0 ustar egon egon 0000000 0000000 //
// Helpers to work with an Ubuntu image based Upgrade implementation
//
// Copyright (c) 2013 Canonical Ltd.
//
// Written by Sergio Schvezov
//
package ubuntuimage
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License version 3, as published
// by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranties of
// MERCHANTABILITY, SATISFACTORY QUALITY, 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, see .
import (
"bufio"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"io"
"io/ioutil"
"net/url"
"os"
"path/filepath"
"syscall"
"github.com/cheggaaa/pb"
)
func hashMatches(filePath, hash string) bool {
h := sha256.New()
var err error
fileBytes, err := ioutil.ReadFile(filePath)
if err != nil {
return false
}
h.Write(fileBytes)
hashString := hex.EncodeToString(h.Sum(nil))
if hashString == hash {
return true
}
return false
}
const commandsStart = `format system
load_keyring image-master.tar.xz image-master.tar.xz.asc
load_keyring image-signing.tar.xz image-signing.tar.xz.asc
mount system
`
func GetUbuntuCommands(files []File, downloadDir string, wipe bool, enable []string) (commandsFile string, err error) {
tmpFile, err := ioutil.TempFile(downloadDir, "ubuntu_commands")
if err != nil {
return commandsFile, err
}
writer := bufio.NewWriter(tmpFile)
defer func() {
if err == nil {
writer.Flush()
}
}()
if wipe {
writer.WriteString("format data\n")
}
if files != nil {
writer.WriteString(commandsStart)
order := func(f1, f2 *File) bool {
return f1.Order < f2.Order
}
By(order).Sort(files)
for _, file := range files {
writer.WriteString(
fmt.Sprintf("update %s %s\n", filepath.Base(file.Path), filepath.Base(file.Signature)))
}
}
//we cannot enable "things" outside of userdata
for i := range enable {
writer.WriteString(fmt.Sprintf("enable %s\n", enable[i]))
}
writer.WriteString("unmount system\n")
return tmpFile.Name(), err
}
func GetGPGFiles() []File {
return []File{{Path: "/gpg/image-master.tar.xz", Signature: "/gpg/image-master.tar.xz.asc"},
{Path: "/gpg/image-signing.tar.xz", Signature: "/gpg/image-signing.tar.xz.asc"}}
}
func getLockFd(file string) (fileLock *os.File, err error) {
err = os.MkdirAll(filepath.Dir(file), 0700)
if err != nil {
return nil, err
}
fileLock, err = os.Create(file + "_lock")
if err != nil {
return nil, err
}
return fileLock, nil
}
//MakeRelativeToServer changes absolute paths in Path into a relative path and adds the host
//part to Server, if the Path is already relative it uses defaultServer
func (file *File) MakeRelativeToServer(defaultServer string) error {
file.Server = defaultServer
u, err := url.Parse(file.Path)
if err != nil {
return err
}
if u.IsAbs() {
file.Server = u.Scheme + "://" + u.Host
file.Path = u.Path
file.Signature = file.Path + ".asc"
}
return nil
}
func (file File) Download(downloadDir string) (err error) {
//TODO Verify downloaded gpg agains image
path := filepath.Join(downloadDir, file.Path)
// Create file lock to avoid multiple processes downloading the same file
lock, err := getLockFd(path)
if err != nil {
return err
}
err = syscall.Flock(int(lock.Fd()), syscall.LOCK_EX)
if err != nil {
return err
}
defer func() {
os.Remove(lock.Name())
syscall.Flock(int(lock.Fd()), syscall.LOCK_UN)
}()
if hashMatches(path, file.Checksum) {
return nil
}
for _, f := range []string{file.Signature, file.Path} {
uri := file.Server + f
path := filepath.Join(downloadDir, f)
err := os.MkdirAll(filepath.Dir(path), 0700)
if err != nil {
return err
}
target, err := os.Create(path + "_")
if err != nil {
return err
}
defer func() {
target.Close()
if err == nil {
os.Rename(path+"_", path)
}
}()
err = download(uri, target)
if err != nil {
return err
}
}
return err
}
func download(uri string, writer io.Writer) (err error) {
resp, err := client.Get(uri)
if err != nil {
return err
}
if resp.StatusCode != 200 {
return errors.New(fmt.Sprintf("Got status code %d for %s", resp.StatusCode, uri))
}
defer resp.Body.Close()
// Only display a progress bar for files > 2K in size
// nb, ContentLength is -1 for *.asc files
if resp.ContentLength > 2048 {
pbar := pb.New(int(resp.ContentLength))
pbar.ShowSpeed = true
pbar.Units = pb.U_BYTES
pbar.Start()
mw := io.MultiWriter(writer, pbar)
_, err = io.Copy(mw, resp.Body)
pbar.Finish()
} else {
bufReader := bufio.NewReader(resp.Body)
bufWriter := bufio.NewWriter(writer)
defer func() {
if err == nil {
err = bufWriter.Flush()
}
}()
_, err = bufReader.WriteTo(bufWriter)
}
return err
}
func GetCacheDir() (cacheDir string) {
cacheDir = os.Getenv("XDG_CACHE_HOME")
if cacheDir == "" {
cacheDir = "$HOME/.cache/"
}
cacheDir = os.ExpandEnv(cacheDir)
return filepath.Join(cacheDir, "ubuntuimages")
}
goget-ubuntu-touch-0.34/ubuntuimage/types.go 0000664 0001750 0001750 00000002627 12621156354 021145 0 ustar egon egon 0000000 0000000 //
// Helpers to work with an Ubuntu image based Upgrade implementation
//
// Copyright (c) 2013 Canonical Ltd.
//
// Written by Sergio Schvezov
//
package ubuntuimage
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License version 3, as published
// by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranties of
// MERCHANTABILITY, SATISFACTORY QUALITY, 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, see .
type Device struct {
Index string
}
type Channel struct {
Devices map[string]Device `json:"devices"`
Alias string `json:"alias"`
Hidden bool `json:"hidden,omitempty"`
}
type Channels map[string]Channel
type ImageVersion struct {
Description string
}
type ImageVersions map[int]ImageVersion
type File struct {
Server string
Checksum, Path, Signature string
Size, Order int
}
type Image struct {
Description, Type string
Version int
Files []File
}
type DeviceChannel struct {
Url string
Alias string
Images []Image
}
goget-ubuntu-touch-0.34/ubuntu-device-do/ 0000775 0001750 0001750 00000000000 12700710721 020265 5 ustar egon egon 0000000 0000000 goget-ubuntu-touch-0.34/ubuntu-device-do/factory_reset.go 0000664 0001750 0001750 00000004133 12621156354 023476 0 ustar egon egon 0000000 0000000 //
// ubuntu-device-do - Tool to send commands to an Ubuntu device
//
// Copyright (c) 2013 Canonical Ltd.
//
// Written by Sergio Schvezov
//
package main
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License version 3, as published
// by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranties of
// MERCHANTABILITY, SATISFACTORY QUALITY, 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, see .
import (
"fmt"
"log"
"launchpad.net/goget-ubuntu-touch/devices"
"launchpad.net/goget-ubuntu-touch/ubuntuimage"
)
type FactoryResetCmd struct {
DeveloperMode bool `long:"developer-mode" description:"Enables developer mode after the factory reset"`
Serial string `long:"serial" description:"Serial of the device to operate"`
}
var factoryResetCmd FactoryResetCmd
func init() {
parser.AddCommand("factory-reset",
"Resets to stock install",
"Resets a device to its stock install with the possibility to enable developer mode by default",
&factoryResetCmd)
}
func (factoryResetCmd *FactoryResetCmd) Execute(args []string) error {
var enableList []string
if factoryResetCmd.DeveloperMode {
enableList = append(enableList, "developer_mode")
}
//files: nil, files location: "", wipe: true, enable: enableList
ubuntuCommands, err := ubuntuimage.GetUbuntuCommands(nil, "", true, enableList)
if err != nil {
return fmt.Errorf("cannot create commands file: %s", err)
}
adb, err := devices.NewUbuntuDebugBridge()
if err != nil {
log.Fatal(err)
}
if factoryResetCmd.Serial != "" {
adb.SetSerial(factoryResetCmd.Serial)
}
if err := adb.Push(ubuntuCommands, "/cache/recovery/ubuntu_command"); err != nil {
return err
}
fmt.Println("Rebooting to finish factory reset")
adb.RebootRecovery()
return nil
}
goget-ubuntu-touch-0.34/ubuntu-device-do/main.go 0000664 0001750 0001750 00000001745 12621156354 021557 0 ustar egon egon 0000000 0000000 //
// ubuntu-device-do - Tool to send commands to an Ubuntu device
//
// Copyright (c) 2013 Canonical Ltd.
//
// Written by Sergio Schvezov
//
package main
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License version 3, as published
// by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranties of
// MERCHANTABILITY, SATISFACTORY QUALITY, 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, see .
import (
"os"
flags "github.com/jessevdk/go-flags"
)
var parser = flags.NewParser(nil, flags.Default)
func init() {
}
func main() {
if _, err := parser.Parse(); err != nil {
os.Exit(1)
}
}
goget-ubuntu-touch-0.34/sysutils/ 0000775 0001750 0001750 00000000000 12700710721 017005 5 ustar egon egon 0000000 0000000 goget-ubuntu-touch-0.34/sysutils/utils_test.go 0000664 0001750 0001750 00000001753 12621156354 021551 0 ustar egon egon 0000000 0000000 package sysutils
import (
"os"
"path/filepath"
"testing"
. "launchpad.net/gocheck"
)
// Hook up gocheck into the "go test" runner.
func Test(t *testing.T) { TestingT(t) }
type UtilsTestSuite struct {
tmpdir string
}
var _ = Suite(&UtilsTestSuite{})
func (s *UtilsTestSuite) SetUpTest(c *C) {
s.tmpdir = c.MkDir()
}
func (s *UtilsTestSuite) TestCreateEmptyFileGiB(c *C) {
f := filepath.Join(s.tmpdir, "gib")
c.Assert(CreateEmptyFile(f, 1, GiB), IsNil)
fStat, err := os.Stat(f)
c.Assert(err, IsNil)
c.Assert(fStat.Size(), Equals, int64(1024*1024*1024))
}
func (s *UtilsTestSuite) TestCreateEmptyFileGB(c *C) {
f1 := filepath.Join(s.tmpdir, "gb")
c.Assert(CreateEmptyFile(f1, 1, GB), IsNil)
fStat1, err := os.Stat(f1)
c.Assert(err, IsNil)
c.Assert(fStat1.Size(), Equals, int64(974999552))
f2 := filepath.Join(s.tmpdir, "gb")
c.Assert(CreateEmptyFile(f2, 2, GB), IsNil)
fStat2, err := os.Stat(f2)
c.Assert(err, IsNil)
c.Assert(fStat2.Size(), Equals, int64(1949999616))
}
goget-ubuntu-touch-0.34/sysutils/fileops_test.go 0000664 0001750 0001750 00000002171 12621156354 022045 0 ustar egon egon 0000000 0000000 package sysutils
import (
"io/ioutil"
"os"
"path/filepath"
. "launchpad.net/gocheck"
)
type FileOpsTestSuite struct {
tmpdir string
srcPath string
dstPath string
}
var _ = Suite(&FileOpsTestSuite{})
func (s *FileOpsTestSuite) SetUpTest(c *C) {
s.tmpdir = c.MkDir()
s.srcPath = filepath.Join(s.tmpdir, "src")
s.dstPath = filepath.Join(s.tmpdir, "dst")
}
func (s *FileOpsTestSuite) TestCopyModes(c *C) {
c.Assert(ioutil.WriteFile(s.srcPath, []byte("src"), 0755), IsNil)
c.Assert(CopyFile(s.srcPath, s.dstPath), IsNil)
stat, err := os.Stat(s.dstPath)
c.Assert(err, IsNil)
mode := stat.Mode()
c.Assert(mode.IsRegular(), Equals, true)
c.Assert(mode.String(), Equals, "-rwxr-xr-x")
contents, err := ioutil.ReadFile(s.dstPath)
c.Assert(err, IsNil)
c.Assert(string(contents), Equals, "src")
}
func (s *FileOpsTestSuite) TestCopyNoSourceFails(c *C) {
err := CopyFile(s.srcPath, s.dstPath)
c.Assert(err, NotNil)
c.Assert(os.IsNotExist(err), Equals, true)
}
func (s *FileOpsTestSuite) TestCopyDirFails(c *C) {
c.Assert(os.MkdirAll(s.srcPath, 0755), IsNil)
err := CopyFile(s.srcPath, s.dstPath)
c.Assert(err, NotNil)
}
goget-ubuntu-touch-0.34/sysutils/fileops.go 0000664 0001750 0001750 00000001133 12621156354 021003 0 ustar egon egon 0000000 0000000 package sysutils
import (
"bufio"
"io"
"os"
)
func CopyFile(src, dst string) error {
srcStat, err := os.Stat(src)
if err != nil {
return err
}
dstFile, err := os.OpenFile(dst, os.O_CREATE|os.O_WRONLY, srcStat.Mode())
if err != nil {
return err
}
defer dstFile.Close()
srcFile, err := os.Open(src)
if err != nil {
return err
}
defer srcFile.Close()
reader := bufio.NewReader(srcFile)
writer := bufio.NewWriter(dstFile)
defer func() {
if err != nil {
writer.Flush()
}
}()
if _, err = io.Copy(writer, reader); err != nil {
return err
}
writer.Flush()
return nil
}
goget-ubuntu-touch-0.34/sysutils/utils.go 0000664 0001750 0001750 00000005241 12621156354 020506 0 ustar egon egon 0000000 0000000 //
// sysutils - Tool to download and run Ubuntu Touch emulator instances
//
// Copyright (c) 2013 Canonical Ltd.
//
// Written by Sergio Schvezov
//
package sysutils
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License version 3, as published
// by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranties of
// MERCHANTABILITY, SATISFACTORY QUALITY, 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, see .
import (
"errors"
"fmt"
"os"
"strconv"
"syscall"
)
type unit int64
const (
GiB unit = 1024
GB unit = 1000
)
func CreateEmptyFile(path string, size int64, u unit) (err error) {
file, err := os.Create(path)
if err != nil {
return err
}
defer func() {
file.Close()
if err != nil {
os.Remove(path)
}
}()
switch u {
case GiB:
size = size * 1024 * 1024 * 1024
case GB:
// The image size will be reduced to fit commercial drives that are
// smaller than what they claim, 975 comes from 97.5% of the total size
// but we want to be a multiple of 512 (and size is an int) we divide by
// 512 and multiply it again
size = size * 1000 * 1000 * 975 / 512 * 512
default:
panic("improper sizing unit used")
}
if err := file.Truncate(size); err != nil {
return errors.New(fmt.Sprintf("Error creating %s of size %d to stage image onto", path, size))
}
return nil
}
func DropPrivs() error {
uid, gid := GetUserEnvInt()
if err := syscall.Setregid(-1, gid); err != nil {
return errors.New(fmt.Sprintf("Can't drop gid: %s", err))
}
if err := syscall.Setreuid(-1, uid); err != nil {
return errors.New(fmt.Sprintf("Can't drop uid: %s", err))
}
return nil
}
func EscalatePrivs() error {
err := syscall.Setreuid(-1, 0)
return err
}
// GetUserEnv checks if the process can drop priviledges by checking if either
// SUDO_UID and SUDO_GID or PKEXEC_UID are set, it returns the corresponding
// uid and gid set in these or 0 otherwise.
func GetUserEnv() (uid, gid string) {
if v := os.Getenv("SUDO_UID"); v != "" {
uid = v
} else if v := os.Getenv("PKEXEC_UID"); v != "" {
uid = v
} else {
uid = "0"
}
if v := os.Getenv("SUDO_GID"); v != "" {
gid = v
} else {
gid = "0"
}
return uid, gid
}
func GetUserEnvInt() (uid, gid int) {
uidString, gidString := GetUserEnv()
uid, _ = strconv.Atoi(uidString)
gid, _ = strconv.Atoi(gidString)
return uid, gid
}
goget-ubuntu-touch-0.34/sysutils/chroot.go 0000664 0001750 0001750 00000005212 12621156354 020642 0 ustar egon egon 0000000 0000000 //
// sysutils - Tool to download and run Ubuntu Touch emulator instances
//
// Copyright (c) 2015 Canonical Ltd.
//
// Written by Sergio Schvezov
//
package sysutils
import (
"fmt"
"os"
"os/exec"
"path/filepath"
)
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License version 3, as published
// by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranties of
// MERCHANTABILITY, SATISFACTORY QUALITY, 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, see .
const (
binQemuArmStatic = "/usr/bin/qemu-arm-static"
pkgQemuUserStatic = "qemu-user-static"
)
var mountpoints = []string{"dev", "proc", "sys", filepath.Join("sys", "firmware")}
func AddQemuStatic(chroot string) error {
dst := filepath.Join(chroot, binQemuArmStatic)
if out, err := exec.Command("cp", binQemuArmStatic, dst).CombinedOutput(); err != nil {
return fmt.Errorf("issues while setting up password: %s", out)
}
return nil
}
func RemoveQemuStatic(chroot string) error {
dst := filepath.Join(chroot, binQemuArmStatic)
return os.Remove(dst)
}
func VerifyDependencies(arch string) error {
switch arch {
case "armhf":
if _, err := os.Stat(binQemuArmStatic); err != nil {
return fmt.Errorf("missing dependency %s (apt install %s)", binQemuArmStatic, pkgQemuUserStatic)
}
}
return nil
}
func ChrootBindMount(chroot string) error {
for _, mnt := range mountpoints {
src := filepath.Join("/", mnt)
dst := filepath.Join(chroot, mnt)
if err := bindMount(src, dst); err != nil {
return err
}
}
return nil
}
func ChrootBindUnmount(chroot string) error {
for i := len(mountpoints) - 1; i >= 0; i-- {
if err := unmount(filepath.Join(chroot, mountpoints[i])); err != nil {
return err
}
}
return nil
}
func ChrootRun(cmd ...string) error {
if out, err := exec.Command("chroot", cmd...).CombinedOutput(); err != nil {
return fmt.Errorf("unable to run chroot command: %s", out)
}
return nil
}
func bindMount(src, dst string) error {
if out, err := exec.Command("mount", "--bind", src, dst).CombinedOutput(); err != nil {
return fmt.Errorf("issues while bind mounting: %s", out)
}
return nil
}
func unmount(dst string) error {
if out, err := exec.Command("umount", dst).CombinedOutput(); err != nil {
return fmt.Errorf("issues while unmounting: %s", out)
}
return nil
}
goget-ubuntu-touch-0.34/.tarmac.sh 0000775 0001750 0001750 00000000530 12621156354 017000 0 ustar egon egon 0000000 0000000 #!/bin/sh
set -ev
# we always run in a fresh dir in tarmac
export GOPATH=$(mktemp -d)
trap 'rm -rf "$GOPATH"' EXIT
# this is a hack, but not sure tarmac is golang friendly
mkdir -p $GOPATH/src/launchpad.net/goget-ubuntu-touch
cp -a . $GOPATH/src/launchpad.net/goget-ubuntu-touch
cd $GOPATH/src/launchpad.net/goget-ubuntu-touch
./run-checks
goget-ubuntu-touch-0.34/diskimage/ 0000775 0001750 0001750 00000000000 12700710721 017043 5 ustar egon egon 0000000 0000000 goget-ubuntu-touch-0.34/diskimage/bootloader_test.go 0000664 0001750 0001750 00000015155 12621156354 022602 0 ustar egon egon 0000000 0000000 //
// diskimage - handles ubuntu disk images
//
// Copyright (c) 2015 Canonical Ltd.
//
// Written by Sergio Schvezov
//
package diskimage
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License version 3, as published
// by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranties of
// MERCHANTABILITY, SATISFACTORY QUALITY, 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, see .
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"testing"
. "launchpad.net/gocheck"
"launchpad.net/goget-ubuntu-touch/sysutils"
)
// Hook up gocheck into the "go test" runner.
func Test(t *testing.T) { TestingT(t) }
type BootAssetFilesTestSuite struct {
bootMountDir string
bootPathDir string
oemRootPathDir string
files []BootAssetFiles
}
var _ = Suite(&BootAssetFilesTestSuite{})
const fileName = "files-%d"
func (s *BootAssetFilesTestSuite) createTestFiles(c *C) {
for i := 0; i < 3; i++ {
f := fmt.Sprintf(fileName, i)
fAbsolutePath := filepath.Join(s.oemRootPathDir, f)
c.Assert(ioutil.WriteFile(fAbsolutePath, []byte(f), 0644), IsNil)
s.files = append(s.files, BootAssetFiles{Path: f})
}
}
func (s *BootAssetFilesTestSuite) verifyTestFiles(c *C) {
for i := range s.files {
f := fmt.Sprintf(fileName, i)
fAbsolutePath := filepath.Join(s.bootPathDir, f)
if s.files[i].Dst != "" {
fAbsolutePath = filepath.Join(s.bootMountDir, s.files[i].Dst)
} else if s.files[i].Target != "" {
fAbsolutePath = filepath.Join(s.bootPathDir, s.files[i].Target)
}
content, err := ioutil.ReadFile(fAbsolutePath)
c.Assert(err, IsNil)
c.Assert(string(content), Equals, fmt.Sprintf("files-%d", i))
}
}
func (s *BootAssetFilesTestSuite) SetUpTest(c *C) {
s.bootMountDir = c.MkDir()
s.bootPathDir = c.MkDir()
s.oemRootPathDir = c.MkDir()
s.createTestFiles(c)
}
func (s *BootAssetFilesTestSuite) TearDownTest(c *C) {
s.files = nil
}
func (s *BootAssetFilesTestSuite) TestCopyFiles(c *C) {
c.Assert(setupBootAssetFiles(s.bootMountDir, s.bootPathDir, s.oemRootPathDir, s.files), IsNil)
s.verifyTestFiles(c)
}
func (s *BootAssetFilesTestSuite) TestCopyFilesWithTarget(c *C) {
f := fmt.Sprintf(fileName, len(s.files))
fAbsolutePath := filepath.Join(s.oemRootPathDir, f)
c.Assert(ioutil.WriteFile(fAbsolutePath, []byte(f), 0644), IsNil)
s.files = append(s.files, BootAssetFiles{Path: f, Target: "otherpath"})
c.Assert(setupBootAssetFiles(s.bootMountDir, s.bootPathDir, s.oemRootPathDir, s.files), IsNil)
s.verifyTestFiles(c)
}
func (s *BootAssetFilesTestSuite) TestCopyFilesWithTargetInDir(c *C) {
f := fmt.Sprintf(fileName, len(s.files))
fAbsolutePath := filepath.Join(s.oemRootPathDir, f)
c.Assert(ioutil.WriteFile(fAbsolutePath, []byte(f), 0644), IsNil)
s.files = append(s.files, BootAssetFiles{Path: f, Target: filepath.Join("subpath", "otherpath")})
c.Assert(setupBootAssetFiles(s.bootMountDir, s.bootPathDir, s.oemRootPathDir, s.files), IsNil)
s.verifyTestFiles(c)
}
func (s *BootAssetFilesTestSuite) TestCopyFilesWithDst(c *C) {
f := fmt.Sprintf(fileName, len(s.files))
fAbsolutePath := filepath.Join(s.oemRootPathDir, f)
c.Assert(ioutil.WriteFile(fAbsolutePath, []byte(f), 0644), IsNil)
s.files = append(s.files, BootAssetFiles{Path: f, Dst: "otherpath"})
c.Assert(setupBootAssetFiles(s.bootMountDir, s.bootPathDir, s.oemRootPathDir, s.files), IsNil)
s.verifyTestFiles(c)
}
func (s *BootAssetFilesTestSuite) TestCopyFilesWithDstAndSubdir(c *C) {
f := fmt.Sprintf(fileName, len(s.files))
fAbsolutePath := filepath.Join(s.oemRootPathDir, f)
c.Assert(ioutil.WriteFile(fAbsolutePath, []byte(f), 0644), IsNil)
s.files = append(s.files, BootAssetFiles{Path: f, Dst: filepath.Join("path", "more-path", "otherpath")})
c.Assert(setupBootAssetFiles(s.bootMountDir, s.bootPathDir, s.oemRootPathDir, s.files), IsNil)
s.verifyTestFiles(c)
}
type BootAssetRawFilesTestSuite struct {
oemRootPathDir string
imagePath string
files []BootAssetRawFiles
}
var _ = Suite(&BootAssetRawFilesTestSuite{})
const baseOffset = 60
func (s *BootAssetRawFilesTestSuite) createTestFiles(c *C) {
for i := 0; i < 2; i++ {
f := fmt.Sprintf(fileName, i)
fAbsolutePath := filepath.Join(s.oemRootPathDir, f)
c.Assert(ioutil.WriteFile(fAbsolutePath, []byte(f), 0644), IsNil)
offset := fmt.Sprintf("%d", baseOffset+i*20)
s.files = append(s.files, BootAssetRawFiles{Path: f, Offset: offset})
}
}
func (s *BootAssetRawFilesTestSuite) verifyTestFiles(c *C) {
img, err := os.Open(s.imagePath)
c.Assert(err, IsNil)
for i := range s.files {
content := fmt.Sprintf(fileName, i)
readContent := make([]byte, len(content))
n, err := img.ReadAt(readContent, int64(baseOffset+i*20))
c.Assert(err, IsNil)
c.Assert(n, Equals, len(content))
c.Assert(string(readContent), Equals, content)
// check for zeros before and after
zero := make([]byte, 1)
_, err = img.ReadAt(zero, int64(baseOffset+i*20-1))
c.Assert(err, IsNil)
c.Assert(zero[0], Equals, uint8(0x0))
_, err = img.ReadAt(zero, int64(baseOffset+i*20+len(content)))
c.Assert(err, IsNil)
c.Assert(zero[0], Equals, uint8(0x0))
}
}
func (s *BootAssetRawFilesTestSuite) SetUpTest(c *C) {
s.oemRootPathDir = c.MkDir()
s.imagePath = filepath.Join(c.MkDir(), "image.img")
c.Assert(sysutils.CreateEmptyFile(s.imagePath, 1, sysutils.GB), IsNil)
s.createTestFiles(c)
}
func (s *BootAssetRawFilesTestSuite) TearDownTest(c *C) {
s.files = nil
}
func (s *BootAssetRawFilesTestSuite) TestRawWrite(c *C) {
c.Assert(setupBootAssetRawFiles(s.imagePath, s.oemRootPathDir, s.files), IsNil)
s.verifyTestFiles(c)
}
func (s *BootAssetRawFilesTestSuite) TestRawWriteNoValidOffset(c *C) {
f := fileName
fAbsolutePath := filepath.Join(s.oemRootPathDir, f)
c.Assert(ioutil.WriteFile(fAbsolutePath, []byte(f), 0644), IsNil)
offset := "NaN"
s.files = []BootAssetRawFiles{BootAssetRawFiles{Path: f, Offset: offset}}
c.Assert(setupBootAssetRawFiles(s.imagePath, s.oemRootPathDir, s.files), NotNil)
}
func (s *BootAssetRawFilesTestSuite) TestRawWriteNoValidFile(c *C) {
f := fileName
offset := "10"
s.files = []BootAssetRawFiles{BootAssetRawFiles{Path: f, Offset: offset}}
c.Assert(setupBootAssetRawFiles(s.imagePath, s.oemRootPathDir, s.files), NotNil)
}
func (s *BootAssetRawFilesTestSuite) TestRawWriteNoValidImage(c *C) {
c.Assert(setupBootAssetRawFiles("where_does_this_ref", s.oemRootPathDir, s.files), NotNil)
}
goget-ubuntu-touch-0.34/diskimage/errors.go 0000664 0001750 0001750 00000001733 12621156354 020722 0 ustar egon egon 0000000 0000000 //
// diskimage - handles ubuntu disk images
//
// Copyright (c) 2015 Canonical Ltd.
//
// Written by Sergio Schvezov
//
package diskimage
import (
"fmt"
"strings"
)
// ErrMount represents a mount error
type ErrMount struct {
dev string
mountpoint string
fs fsType
out []byte
}
func (e ErrMount) Error() string {
return fmt.Sprintf("cannot mount %s(%s) on %s: %s", e.dev, e.fs, e.mountpoint, e.out)
}
// ErrMapCount represents an error on the expected amount of partitions
type ErrMapCount struct {
foundParts int
expectedParts int
}
func (e ErrMapCount) Error() string {
return fmt.Sprintf("expected %d partitons but found %d", e.expectedParts, e.foundParts)
}
// ErrExec is an error from an external command
type ErrExec struct {
output []byte
command []string
}
func (e ErrExec) Error() string {
return fmt.Sprintf("error while executing external command %s: %s", strings.Join(e.command, " "), e.output)
}
goget-ubuntu-touch-0.34/diskimage/partition.go 0000664 0001750 0001750 00000011435 12700665201 021411 0 ustar egon egon 0000000 0000000 //
// diskimage - handles ubuntu disk images
//
// Copyright (c) 2013 Canonical Ltd.
//
// Written by Sergio Schvezov
//
package diskimage
import (
"errors"
"fmt"
"io"
"os"
"os/exec"
)
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License version 3, as published
// by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranties of
// MERCHANTABILITY, SATISFACTORY QUALITY, 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, see .
type imageLabel string
type directory string
type mklabelType string
type fsType string
const (
grubLabel imageLabel = "grub"
bootLabel imageLabel = "system-boot"
systemALabel imageLabel = "system-a"
systemBLabel imageLabel = "system-b"
writableLabel imageLabel = "writable"
)
const (
grubDir directory = "system/boot/grub-gpt"
bootDir directory = "boot"
systemADir directory = "system"
systemBDir directory = "system-b"
writableDir directory = "writable"
)
const (
mkLabelGpt mklabelType = "gpt"
mkLabelMsdos mklabelType = "msdos"
)
const (
fsFat32 fsType = "fat32"
fsExt4 fsType = "ext4"
fsNone fsType = ""
)
var errUnsupportedPartitioning = errors.New("unsupported partitioning")
type parted struct {
mklabel mklabelType
parts []partition
bootPartition int
biosGrub int
}
type partition struct {
begin int
end int
fs fsType
label imageLabel
dir directory
loop string
}
func newParted(mklabel mklabelType) (*parted, error) {
if mklabel != mkLabelGpt && mklabel != mkLabelMsdos {
return nil, errUnsupportedPartitioning
}
return &parted{
mklabel: mklabel,
}, nil
}
// size in MiB
func (p *parted) addPart(label imageLabel, mountDir directory, fs fsType, size int) {
var begin int
if len(p.parts) == 0 {
begin = 8192
} else {
begin = p.parts[len(p.parts)-1].end + 1
}
end := size
if size != -1 {
end = mib2Blocks(size) + begin - 1
}
part := partition{
begin: begin,
end: end,
label: label,
fs: fs,
dir: mountDir,
}
p.parts = append(p.parts, part)
}
func (p *parted) create(target string) error {
partedCmd := exec.Command("parted", target)
stdin, err := partedCmd.StdinPipe()
if err != nil {
return err
}
stdout, err := partedCmd.StdoutPipe()
if err != nil {
return err
}
stderr, err := partedCmd.StderrPipe()
if err != nil {
return err
}
if err := partedCmd.Start(); err != nil {
return err
}
stdin.Write([]byte(fmt.Sprintf("mklabel %s\n", p.mklabel)))
if p.mklabel == mkLabelGpt {
for _, parts := range p.parts {
if parts.end != -1 {
stdin.Write([]byte(fmt.Sprintf("mkpart %s %s %ds %ds\n", parts.label, parts.fs, parts.begin, parts.end)))
} else {
stdin.Write([]byte(fmt.Sprintf("mkpart %s %s %ds %dM\n", parts.label, parts.fs, parts.begin, parts.end)))
}
}
} else if p.mklabel == mkLabelMsdos {
if len(p.parts) > 4 {
panic("invalid amount of partitions for msdos")
}
for _, parts := range p.parts {
if parts.end != -1 {
stdin.Write([]byte(fmt.Sprintf("mkpart primary %s %ds %ds\n", parts.fs, parts.begin, parts.end)))
} else {
stdin.Write([]byte(fmt.Sprintf("mkpart primary %s %ds %dM\n", parts.fs, parts.begin, parts.end)))
}
}
} else {
panic("unsupported mklabel for partitioning")
}
if p.bootPartition != 0 {
stdin.Write([]byte(fmt.Sprintf("set %d boot on\n", p.bootPartition)))
}
if p.biosGrub != 0 {
stdin.Write([]byte(fmt.Sprintf("set %d bios_grub on\n", p.biosGrub)))
}
stdin.Write([]byte("quit\n"))
if debugPrint {
go io.Copy(os.Stdout, stdout)
go io.Copy(os.Stderr, stderr)
}
if err := partedCmd.Wait(); err != nil {
return errors.New("issues while partitioning")
}
return nil
}
func (p *parted) setBiosGrub(partNumber int) {
if partNumber-1 > len(p.parts) {
panic("cannot set part number to inexistent partition")
}
p.biosGrub = partNumber
}
func (p *parted) setBoot(partNumber int) {
if partNumber-1 > len(p.parts) {
panic("cannot set part number to inexistent partition")
}
p.bootPartition = partNumber
}
func mib2Blocks(size int) int {
s := size * 1024 * 1024 / 512
if s%4 != 0 {
panic(fmt.Sprintf("invalid partition size: %d", s))
}
return s
}
func isMapped(parts []partition) bool {
for i := range parts {
if parts[i].loop != "" {
return true
}
}
return false
}
func mapPartitions(parts []partition, loops []string) {
for i := range parts {
parts[i].loop = loops[i]
}
}
func unmapPartitions(parts []partition) {
for i := range parts {
parts[i].loop = ""
}
}
goget-ubuntu-touch-0.34/diskimage/core_grub.go 0000664 0001750 0001750 00000015360 12700703017 021346 0 ustar egon egon 0000000 0000000 //
// diskimage - handles ubuntu disk images
//
// Copyright (c) 2013-2015 Canonical Ltd.
//
// Written by Sergio Schvezov
//
package diskimage
import (
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"time"
"launchpad.net/goget-ubuntu-touch/sysutils"
)
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License version 3, as published
// by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranties of
// MERCHANTABILITY, SATISFACTORY QUALITY, 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, see .
type CoreGrubImage struct {
BaseImage
legacyGrub bool
}
func NewCoreGrubImage(location string, size int64, rootSize int, hw HardwareDescription, oem OemDescription, updateGrub bool, label string) *CoreGrubImage {
return &CoreGrubImage{
BaseImage: BaseImage{
location: location,
size: size,
rootSize: rootSize,
hardware: hw,
oem: oem,
partCount: 5,
label: label,
},
legacyGrub: updateGrub,
}
}
const grubCfgContent = `# console only, no graphics/vga
GRUB_CMDLINE_LINUX_DEFAULT="console=tty1 console=ttyS0 panic=-1"
GRUB_TERMINAL=console
# LP: #1035279
GRUB_RECORDFAIL_TIMEOUT=0
`
const grubStubContent = `set prefix=($root)'/EFI/ubuntu/grub'
configfile $prefix/grub.cfg
`
//Partition creates a partitioned image from an img
func (img *CoreGrubImage) Partition() error {
if err := sysutils.CreateEmptyFile(img.location, img.size, sysutils.GB); err != nil {
return err
}
parted, err := newParted(mkLabelGpt)
if err != nil {
return err
}
parted.addPart(grubLabel, "", fsNone, 4)
parted.addPart(bootLabel, bootDir, fsFat32, 128)
parted.addPart(systemALabel, systemADir, fsExt4, img.rootSize)
parted.addPart(systemBLabel, systemBDir, fsExt4, img.rootSize)
parted.addPart(writableLabel, writableDir, fsExt4, -1)
parted.setBoot(2)
parted.setBiosGrub(1)
img.parts = parted.parts
return parted.create(img.location)
}
func (img *CoreGrubImage) SetupBoot() error {
if !img.legacyGrub {
// destinations
bootPath := filepath.Join(img.baseMount, string(bootDir), "EFI", "ubuntu", "grub")
if err := img.GenericBootSetup(bootPath); err != nil {
return err
}
}
return img.setupGrub()
}
func (img *CoreGrubImage) setupGrub() error {
for _, dev := range []string{"dev", "proc", "sys"} {
src := filepath.Join("/", dev)
dst := filepath.Join(img.System(), dev)
if err := bindMount(src, dst); err != nil {
return err
}
defer unmount(dst)
}
firmwarePath := filepath.Join(img.System(), "sys", "firmware")
if err := bindMount(filepath.Join(img.System(), "mnt"), firmwarePath); err != nil {
return err
}
defer unmount(firmwarePath)
outputPath, err := filepath.Abs(img.location)
if err != nil {
return errors.New("cannot determined absolute path for output image")
}
rootDevPath := filepath.Join(img.System(), "root_dev")
if f, err := os.Create(rootDevPath); err != nil {
return err
} else {
f.Close()
defer os.Remove(rootDevPath)
}
if err := bindMount(outputPath, rootDevPath); err != nil {
return err
}
defer unmount(rootDevPath)
efiDir := filepath.Join(img.System(), "boot", "efi")
if err := os.MkdirAll(efiDir, 0755); err != nil {
return fmt.Errorf("unable to create %s dir: %s", efiDir, err)
}
if err := bindMount(img.Boot(), efiDir); err != nil {
return err
}
defer unmount(efiDir)
// create efi layout
efiGrubDir := filepath.Join(img.System(), "boot", "efi", "EFI", "ubuntu", "grub")
if err := os.MkdirAll(efiGrubDir, 0755); err != nil {
return fmt.Errorf("unable to create %s dir: %s", efiGrubDir, err)
}
// create fw update directory
fwDir := filepath.Join(img.System(), "boot", "efi", "EFI", "ubuntu", "fw")
if err := os.MkdirAll(fwDir, 0755); err != nil {
return fmt.Errorf("unable to create %s dir: %s", fwDir, err)
}
bootGrubDir := filepath.Join(img.System(), "boot", "grub")
if err := bindMount(efiGrubDir, bootGrubDir); err != nil {
return err
}
defer unmount(bootGrubDir)
var grubTarget string
arch := img.oem.Architecture()
switch arch {
case "armhf":
grubTarget = "arm-efi"
case "amd64":
grubTarget = "x86_64-efi"
case "i386":
grubTarget = "i386-efi"
default:
return fmt.Errorf("unsupported architecture for GRUB on EFI: %s", arch)
}
if arch == "amd64" || arch == "i386" {
// install grub BIOS support
if out, err := exec.Command("chroot", img.System(), "grub-install", "/root_dev").CombinedOutput(); err != nil {
return fmt.Errorf("unable to install grub (BIOS): %s", out)
}
}
// install grub EFI
if out, err := exec.Command("chroot", img.System(), "grub-install", fmt.Sprint("--target="+grubTarget), "--no-nvram", "--removable", "--efi-directory=/boot/efi").CombinedOutput(); err != nil {
return fmt.Errorf("unable to install grub (EFI): %s", out)
}
// tell our EFI grub where to find its full config
efiBootDir := filepath.Join(img.System(), "boot", "efi", "EFI", "BOOT")
grubStub, err := os.Create(filepath.Join(efiBootDir, "grub.cfg"))
if err != nil {
return fmt.Errorf("unable to create %s file: %s", grubStub.Name(), err)
}
defer grubStub.Close()
if _, err := io.WriteString(grubStub, grubStubContent); err != nil {
return err
}
if img.legacyGrub {
if err := img.updateGrub(); err != nil {
return err
}
}
return nil
}
func (img *CoreGrubImage) updateGrub() error {
// ensure we run not into recordfail issue
grubDir := filepath.Join(img.System(), "etc", "default", "grub.d")
if err := os.MkdirAll(grubDir, 0755); err != nil {
return fmt.Errorf("unable to create %s dir: %s", grubDir, err)
}
grubFile, err := os.Create(filepath.Join(grubDir, "50-system-image.cfg"))
if err != nil {
return fmt.Errorf("unable to create %s file: %s", grubFile.Name(), err)
}
defer grubFile.Close()
if _, err := io.WriteString(grubFile, grubCfgContent); err != nil {
return err
}
// I don't know why this is needed, I just picked it up from the original implementation
time.Sleep(3 * time.Second)
if out, err := exec.Command("chroot", img.System(), "update-grub").CombinedOutput(); err != nil {
return fmt.Errorf("unable to update grub: %s", out)
}
return nil
}
func bindMount(src, dst string) error {
if out, err := exec.Command("mount", "--bind", src, dst).CombinedOutput(); err != nil {
return fmt.Errorf("issues while bind mounting: %s", out)
}
return nil
}
func unmount(dst string) error {
if out, err := exec.Command("umount", dst).CombinedOutput(); err != nil {
return fmt.Errorf("issues while unmounting: %s", out)
}
return nil
}
goget-ubuntu-touch-0.34/diskimage/bootloader.go 0000664 0001750 0001750 00000007003 12700703017 021524 0 ustar egon egon 0000000 0000000 //
// diskimage - handles ubuntu disk images
//
// Copyright (c) 2015 Canonical Ltd.
//
// Written by Sergio Schvezov
//
package diskimage
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License version 3, as published
// by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranties of
// MERCHANTABILITY, SATISFACTORY QUALITY, 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, see .
import (
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strconv"
"launchpad.net/goget-ubuntu-touch/sysutils"
)
func setupBootAssetFiles(bootMount, bootPath, oemRootPath string, files []BootAssetFiles) error {
printOut("Setting up boot asset files from", oemRootPath, "...")
for _, file := range files {
dst := filepath.Join(bootPath, filepath.Base(file.Path))
if file.Dst != "" {
dst = filepath.Join(bootMount, file.Dst)
} else if file.Target != "" {
dst = filepath.Join(bootPath, file.Target)
}
dstDir := filepath.Dir(dst)
if _, err := os.Stat(dstDir); os.IsNotExist(err) {
if err := os.MkdirAll(dstDir, 0755); err != nil {
return err
}
}
src := filepath.Join(oemRootPath, file.Path)
printOut("Copying", src, "to", dst)
if err := sysutils.CopyFile(src, dst); err != nil {
return err
}
}
return nil
}
func setupBootAssetRawFiles(imagePath, oemRootPath string, rawFiles []BootAssetRawFiles) error {
printOut("Setting up raw boot assets from", oemRootPath, "...")
img, err := os.OpenFile(imagePath, os.O_WRONLY, 0644)
if err != nil {
return err
}
defer img.Close()
for _, asset := range rawFiles {
offsetBytes, err := offsetBytes(asset.Offset)
if err != nil {
return err
}
src := filepath.Join(oemRootPath, asset.Path)
printOut("Writing", src)
assetFile, err := os.Open(src)
if err != nil {
return err
}
if err := rawwrite(img, assetFile, offsetBytes); err != nil {
return err
}
}
return nil
}
func setupBootAssetRawPartitions(imagePath string, partCount int, rawPartitions []BootAssetRawPartitions) error {
printOut("Setting up raw boot asset partitions for", imagePath, "...")
var part int = partCount
for _, asset := range rawPartitions {
part += 1
size, err := strconv.Atoi(asset.Size)
if err != nil {
return err
}
size = size * 2
printOut("creating partition:", asset.Name)
opts := fmt.Sprintf("0:0:+%d", size)
if err := exec.Command("sgdisk", "-a", "1", "-n", opts, imagePath).Run(); err != nil {
return err
}
opts = fmt.Sprintf("%d:%s", part, asset.Name)
if err := exec.Command("sgdisk", "-c", opts, imagePath).Run(); err != nil {
return err
}
opts = fmt.Sprintf("%d:%s", part, asset.Type)
if err := exec.Command("sgdisk", "-t", opts, imagePath).Run(); err != nil {
return err
}
}
printOut("sorting partitions")
if err := exec.Command("sgdisk", "-s", imagePath).Run(); err != nil {
return err
}
return nil
}
func offsetBytes(offset string) (int64, error) {
// TODO add support for units
return strconv.ParseInt(offset, 10, 64)
}
func rawwrite(img *os.File, asset io.Reader, offset int64) error {
if _, err := img.Seek(offset, 0); err != nil {
return err
}
if _, err := io.Copy(img, asset); err != nil {
return err
}
return nil
}
goget-ubuntu-touch-0.34/diskimage/snapshot.go 0000664 0001750 0001750 00000004361 12621156354 021245 0 ustar egon egon 0000000 0000000 //
// ubuntu-emu - Tool to download and run Ubuntu Touch emulator instances
//
// Copyright (c) 2013 Canonical Ltd.
//
// Written by Sergio Schvezov
//
package diskimage
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License version 3, as published
// by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranties of
// MERCHANTABILITY, SATISFACTORY QUALITY, 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, see .
import (
"errors"
"fmt"
"os"
"os/exec"
)
const BaseSnapshot = "pristine"
//ConvertQcow2 converts an image from raw to qcow2
func (img *DiskImage) ConvertQcow2() error {
var cmd *exec.Cmd
// convert
cmd = exec.Command("qemu-img", "convert", "-f", "raw", img.path,
"-O", "qcow2", "-o", "compat=0.10", img.path+".qcow2")
if out, err := cmd.CombinedOutput(); err != nil {
return errors.New(fmt.Sprintf("Error while converting %s: %s", img.path, out))
}
// check
cmd = exec.Command("qemu-img", "check", img.path+".qcow2")
if out, err := cmd.CombinedOutput(); err != nil {
return errors.New(fmt.Sprintf("Error while converting %s: %s", img.path, out))
}
os.Rename(img.path+".qcow2", img.path)
return img.Snapshot(BaseSnapshot)
}
//Snapshot creates a DiskImage's snapshot with the specified snapshot in label
func (img *DiskImage) Snapshot(label string) error {
// snap
cmd := exec.Command("qemu-img", "snapshot", "-c", label, img.path)
if out, err := cmd.CombinedOutput(); err != nil {
return errors.New(fmt.Sprintf("Error while converting %s: %s", img.path, out))
}
return nil
}
//RevertSnapshot reverts a DiskImage's snapshot to the specified snapshot in label
func (img *DiskImage) RevertSnapshot(label string) error {
// unsnap
cmd := exec.Command("qemu-img", "snapshot", "-c", label, img.path)
if out, err := cmd.CombinedOutput(); err != nil {
return errors.New(fmt.Sprintf("Error while converting %s: %s", img.path, out))
}
return nil
}
goget-ubuntu-touch-0.34/diskimage/image.go 0000664 0001750 0001750 00000014230 12621156354 020464 0 ustar egon egon 0000000 0000000 //
// diskimage - handles ubuntu disk images
//
// Copyright (c) 2013 Canonical Ltd.
//
// Written by Sergio Schvezov
//
package diskimage
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License version 3, as published
// by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranties of
// MERCHANTABILITY, SATISFACTORY QUALITY, 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, see .
import (
"bufio"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"launchpad.net/goget-ubuntu-touch/sysutils"
)
type DiskImage struct {
Mountpoint string
label string
path string
size int64
parts []partition
}
//New creates a new DiskImage
func New(path, label string, size int64) *DiskImage {
var img DiskImage
img.path = path
img.label = label
img.size = size
return &img
}
//New creates a new DiskImage
func NewExisting(path string) *DiskImage {
var img DiskImage
img.path = path
return &img
}
func (img *DiskImage) Move(dst string) error {
if err := img.Copy(dst); err != nil {
return err
}
if err := os.Remove(img.path); err != nil {
return errors.New(fmt.Sprintf("Unable to remove %s when moving to %s", img.path, dst))
}
img.path = dst
return nil
}
func (img *DiskImage) Copy(dst string) (err error) {
dstFile, err := os.Create(dst)
if err != nil {
return err
}
defer dstFile.Close()
srcFile, err := os.Open(img.path)
if err != nil {
return err
}
defer srcFile.Close()
reader := bufio.NewReader(srcFile)
writer := bufio.NewWriter(dstFile)
defer func() {
if err != nil {
writer.Flush()
}
}()
if _, err = io.Copy(writer, reader); err != nil {
return err
}
writer.Flush()
return nil
}
//Mount the DiskImage
func (img *DiskImage) Mount() (err error) {
img.Mountpoint, err = ioutil.TempDir(os.TempDir(), "ubuntu-system")
if err != nil {
return errors.New(fmt.Sprintf("Unable to create temp dir to create system image: %s", err))
}
//Remove Mountpoint if we fail along the way
defer func() {
if err != nil {
os.Remove(img.Mountpoint)
}
}()
if out, err := exec.Command("mount", img.path, img.Mountpoint).CombinedOutput(); err != nil {
return fmt.Errorf("unable to mount temp dir to create system image: %s", out)
}
return nil
}
//Unmount the DiskImage
func (img *DiskImage) Unmount() error {
if img.Mountpoint == "" {
return nil
}
defer os.Remove(img.Mountpoint)
if out, err := exec.Command("sync").CombinedOutput(); err != nil {
return errors.New(fmt.Sprintf("Failed to sync filesystems before unmounting: %s", out))
}
if err := exec.Command("umount", img.Mountpoint).Run(); err != nil {
return errors.New("Failed to unmount temp dir where system image was created")
}
return nil
}
//Provision unpacks the tarList into the given DiskImage
func (img *DiskImage) Provision(tarList []string) error {
//TODO use archive/tar
for _, tar := range tarList {
if out, err := exec.Command("tar", "--numeric-owner", "--exclude", "partitions*",
"-xf", tar, "-C", img.Mountpoint).CombinedOutput(); err != nil {
return errors.New(fmt.Sprintf("Unable to extract rootfs %s to %s: %s", tar, img.Mountpoint, out))
}
}
if err := img.unpackSystem(); err != nil {
return err
}
for _, file := range setupFiles {
if err := img.writeFile(file); err != nil {
return err
}
}
return nil
}
//CreateExt4 returns a ext4 partition for a given file
func (img DiskImage) CreateExt4() error {
if img.parts != nil {
panic("creating ext4 on images with multiple parts not supported")
}
if err := sysutils.CreateEmptyFile(img.path, img.size, sysutils.GiB); err != nil {
return err
}
return exec.Command("mkfs.ext4", "-F", "-L", img.label, img.path).Run()
}
//CreateVFat returns a vfat partition for a given file
func (img DiskImage) CreateVFat() error {
if err := sysutils.CreateEmptyFile(img.path, img.size, sysutils.GiB); err != nil {
return err
}
return exec.Command("mkfs.vfat", "-n", img.label, img.path).Run()
}
//unpackSystem moves the system partition up one level
func (img DiskImage) unpackSystem() error {
os.Rename(filepath.Join(img.Mountpoint, "system"),
filepath.Join(img.Mountpoint, "system-unpack"))
defer os.Remove(filepath.Join(img.Mountpoint, "system-unpack"))
dir, err := os.Open(filepath.Join(img.Mountpoint, "system-unpack"))
if err != nil {
return err
}
defer dir.Close()
fileInfos, err := dir.Readdir(-1)
if err != nil {
return err
}
for _, fileInfo := range fileInfos {
name := fileInfo.Name()
err := os.Rename(filepath.Join(img.Mountpoint, "system-unpack", name),
filepath.Join(img.Mountpoint, name))
if err != nil {
return err
}
}
return nil
}
//ExtractFile extracts a filePath relative to it's mountpoint and copies it to dir.
//This function takes care of mounting and unmounting the img
func (img DiskImage) ExtractFile(filePath string, dir string) error {
if err := sysutils.EscalatePrivs(); err != nil {
return err
}
if err := img.Mount(); err != nil {
return err
}
if err := sysutils.DropPrivs(); err != nil {
return err
}
defer func() (err error) {
if err := sysutils.EscalatePrivs(); err != nil {
return err
}
if err := img.Unmount(); err != nil {
return err
}
return sysutils.DropPrivs()
}()
if fi, err := os.Stat(dir); err != nil {
if err := os.MkdirAll(dir, 0755); err != nil {
return err
}
} else if !fi.IsDir() {
return fmt.Errorf("extract dir %s is not a directory", fi.Name())
}
dstFile, err := os.Create(filepath.Join(dir, filePath))
if err != nil {
return err
}
defer dstFile.Close()
srcFile, err := os.Open(filepath.Join(img.Mountpoint, filePath))
if err != nil {
return err
}
defer srcFile.Close()
reader := bufio.NewReader(srcFile)
writer := bufio.NewWriter(dstFile)
defer func() {
if err != nil {
writer.Flush()
}
}()
if _, err = io.Copy(writer, reader); err != nil {
return err
}
writer.Flush()
return nil
}
goget-ubuntu-touch-0.34/diskimage/common.go 0000664 0001750 0001750 00000030316 12700703017 020665 0 ustar egon egon 0000000 0000000 //
// diskimage - handles ubuntu disk images
//
// Copyright (c) 2013 Canonical Ltd.
//
// Written by Sergio Schvezov
//
package diskimage
import (
"bufio"
"errors"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"
"syscall"
"launchpad.net/goget-ubuntu-touch/sysutils"
)
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License version 3, as published
// by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranties of
// MERCHANTABILITY, SATISFACTORY QUALITY, 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, see .
var debugPrint bool
func init() {
if debug := os.Getenv("DEBUG_DISK"); debug != "" {
debugPrint = true
}
}
const (
hardwareFileName = "hardware.yaml"
kernelFileName = "vmlinuz"
initrdFileName = "initrd.img"
)
const (
partLayoutSystemAB = "system-AB"
)
var (
syscallSync = syscall.Sync
)
type Image interface {
Mount() error
Unmount() error
Format() error
Partition() error
BaseMount() string
}
type SystemImage interface {
Boot() string
System() string
Writable() string
}
type CoreImage interface {
Image
SystemImage
SetupBoot() error
FlashExtra() error
}
type HardwareDescription struct {
Kernel string `yaml:"kernel"`
Dtbs string `yaml:"dtbs"`
Initrd string `yaml:"initrd"`
}
type BootAssetRawFiles struct {
Path string `yaml:"path"`
Offset string `yaml:"offset"`
}
type BootAssetRawPartitions struct {
Name string `yaml:"name"`
Size string `yaml:"size"`
Type string `yaml:"type"`
}
type BootAssetFiles struct {
Path string `yaml:"path"`
// Target is the deprecated target relative to $bootloader dir
Target string `yaml:"target,omitempty"`
// Dst is the destination relative to the actual boot partition
Dst string `yaml:"dst,omitempty"`
}
type BootAssets struct {
Files []BootAssetFiles `yaml:"files,omitempty"`
RawFiles []BootAssetRawFiles `yaml:"raw-files,omitempty"`
RawPartitions []BootAssetRawPartitions `yaml:"raw-partitions,omitempty"`
}
type OemDescription struct {
Name string `yaml:"name"`
Version string `yaml:"version"`
OEM struct {
Hardware struct {
Bootloader string `yaml:"bootloader"`
PartitionLayout string `yaml:"partition-layout"`
Dtb string `yaml:"dtb,omitempty"`
Platform string `yaml:"platform"`
Architecture string `yaml:"architecture"`
BootAssets *BootAssets `yaml:"boot-assets,omitempty"`
} `yaml:"hardware,omitempty"`
Software struct {
BuiltIn []string `yaml:"built-in,omitempty"`
Preinstalled []string `yaml:"preinstalled,omitempty"`
} `yaml:"software,omitempty"`
Store *struct {
ID string `yaml:"id,omitempty"`
}
} `yaml:"oem,omitempty"`
Config struct {
UbuntuCore struct {
Modprobe *string `yaml:"modprobe,omitempty"`
} `yaml:"ubuntu-core,omitempty"`
} `yaml:"config,omitempty"`
rootDir string
}
func (o *OemDescription) SetRoot(rootDir string) {
o.rootDir = rootDir
}
// SystemParts returns the system labels depending on the partition layout.
//
// The default is to return a flat structure for any unknown layout.
func (o *OemDescription) SystemParts() []string {
switch o.OEM.Hardware.PartitionLayout {
case partLayoutSystemAB:
return []string{"a", "b"}
default:
return []string{""}
}
}
func (o OemDescription) InstallPath() (string, error) {
glob, err := filepath.Glob(fmt.Sprintf("%s/oem/%s/current", o.rootDir, o.Name))
if err != nil {
return "", err
}
if len(glob) != 1 {
return "", errors.New("oem package not installed")
}
return glob[0], nil
}
func (o OemDescription) Architecture() string {
return o.OEM.Hardware.Architecture
}
func (o *OemDescription) SetArchitecture(architecture string) {
o.OEM.Hardware.Architecture = architecture
}
func (o OemDescription) PartitionLayout() string {
return o.OEM.Hardware.PartitionLayout
}
func (o OemDescription) Platform() string {
return o.OEM.Hardware.Platform
}
func (o *OemDescription) SetPlatform(platform string) {
o.OEM.Hardware.Platform = platform
}
func sectorSize(dev string) (string, error) {
out, err := exec.Command("blockdev", "--getss", dev).CombinedOutput()
if err != nil {
return "", fmt.Errorf("unable to determine block size: %s", out)
}
return strings.TrimSpace(string(out)), err
}
// BaseImage implements the basic primitives to manage images.
type BaseImage struct {
baseMount string
hardware HardwareDescription
location string
oem OemDescription
parts []partition
partCount int
size int64
rootSize int
label string
}
// Mount mounts the image. This also maps the loop device.
func (img *BaseImage) Mount() error {
if err := img.doMap(); err != nil {
return err
}
baseMount, err := ioutil.TempDir(os.TempDir(), "diskimage")
if err != nil {
return err
}
//Remove Mountpoint if we fail along the way
defer func() {
if err != nil {
if err := os.Remove(baseMount); err != nil {
fmt.Println("WARNING: cannot remove", baseMount, "due to", err)
}
}
}()
// We change the mode so snappy can unpack as non root
if err := os.Chmod(baseMount, 0755); err != nil {
return err
}
for _, part := range img.parts {
if part.fs == fsNone {
continue
}
mountpoint := filepath.Join(baseMount, string(part.dir))
if err := os.MkdirAll(mountpoint, 0755); err != nil {
return err
}
dev := filepath.Join("/dev/mapper", part.loop)
printOut("Mounting", dev, part.fs, "to", mountpoint)
if out, errMount := exec.Command("mount", filepath.Join("/dev/mapper", part.loop), mountpoint).CombinedOutput(); errMount != nil {
return ErrMount{dev: dev, mountpoint: mountpoint, fs: part.fs, out: out}
}
// this is cleanup in case one of the mounts fail
defer func() {
if err != nil {
if err := exec.Command("umount", mountpoint).Run(); err != nil {
fmt.Println("WARNING:", mountpoint, "could not be unmounted")
return
}
if err := os.Remove(mountpoint); err != nil {
fmt.Println("WARNING: could not remove ", mountpoint)
}
}
}()
}
img.baseMount = baseMount
return nil
}
// Unmount unmounts the image. This also unmaps the loop device.
func (img *BaseImage) Unmount() error {
defer func() {
if isMapped(img.parts) {
fmt.Println("WARNING: could not unmap partitions")
}
}()
if img.baseMount == "" {
panic("No base mountpoint set")
}
syscallSync()
for _, part := range img.parts {
if part.fs == fsNone {
continue
}
mountpoint := filepath.Join(img.baseMount, string(part.dir))
if out, err := exec.Command("umount", mountpoint).CombinedOutput(); err != nil {
lsof, _ := exec.Command("lsof", "-w", mountpoint).CombinedOutput()
printOut(string(lsof))
dev := filepath.Join("/dev/mapper", part.loop)
return ErrMount{dev: dev, mountpoint: mountpoint, fs: part.fs, out: out}
}
}
if err := os.RemoveAll(img.baseMount); err != nil {
return err
}
img.baseMount = ""
return img.doUnmap()
}
// doMap maps the image to loop devices
func (img *BaseImage) doMap() error {
if isMapped(img.parts) {
panic("cannot double map partitions")
}
kpartxCmd := exec.Command("kpartx", "-avs", img.location)
stdout, err := kpartxCmd.StdoutPipe()
if err != nil {
return err
}
if err := kpartxCmd.Start(); err != nil {
return err
}
loops := make([]string, 0, img.partCount)
scanner := bufio.NewScanner(stdout)
for scanner.Scan() {
fields := strings.Fields(scanner.Text())
if len(fields) > 2 {
loops = append(loops, fields[2])
} else {
return fmt.Errorf("issues while determining drive mappings (%q)", fields)
}
}
if err := scanner.Err(); err != nil {
return err
}
if len(loops) != img.partCount {
return ErrMapCount{expectedParts: img.partCount, foundParts: len(loops)}
}
mapPartitions(img.parts, loops)
if err := kpartxCmd.Wait(); err != nil {
return err
}
return nil
}
// doUnmap destroys loop devices for the partitions
func (img *BaseImage) doUnmap() error {
if img.baseMount != "" {
panic("cannot unmap mounted partitions")
}
for _, part := range img.parts {
dmsetupCmd := []string{"dmsetup", "clear", part.loop}
if out, err := exec.Command(dmsetupCmd[0], dmsetupCmd[1:]...).CombinedOutput(); err != nil {
return &ErrExec{command: dmsetupCmd, output: out}
}
}
kpartxCmd := []string{"kpartx", "-ds", img.location}
if out, err := exec.Command(kpartxCmd[0], kpartxCmd[1:]...).CombinedOutput(); err != nil {
return &ErrExec{command: kpartxCmd, output: out}
}
unmapPartitions(img.parts)
return nil
}
// Format formats the image following the partition types and labels them
// accordingly.
func (img BaseImage) Format() (err error) {
if err := img.doMap(); err != nil {
return err
}
defer func() {
if errUnmap := img.doUnmap(); errUnmap != nil {
if err == nil {
err = errUnmap
} else {
fmt.Println("WARNING: could not unmap partitions after error:", errUnmap)
}
}
}()
for _, part := range img.parts {
dev := filepath.Join("/dev/mapper", part.loop)
if part.fs == fsFat32 {
cmd := []string{"mkfs.vfat", "-F", "32", "-n", string(part.label)}
size, err := sectorSize(dev)
if err != nil {
return err
}
if size != "512" {
cmd = append(cmd, "-s", "1")
}
cmd = append(cmd, "-S", size, dev)
if out, err := exec.Command(cmd[0], cmd[1:]...).CombinedOutput(); err != nil {
return &ErrExec{command: cmd, output: out}
}
} else {
cmd := []string{"mkfs.ext4", "-F", "-L", string(part.label), dev}
if out, err := exec.Command(cmd[0], cmd[1:]...).CombinedOutput(); err != nil {
return &ErrExec{command: cmd, output: out}
}
}
}
return nil
}
// User returns the writable path
func (img BaseImage) Writable() string {
if img.parts == nil {
panic("img is not setup with partitions")
}
if img.baseMount == "" {
panic("img not mounted")
}
return filepath.Join(img.baseMount, string(writableDir))
}
func (img BaseImage) pathToMount(dir directory) string {
if img.parts == nil {
panic("img is not setup with partitions")
}
if img.baseMount == "" {
panic("img not mounted")
}
return filepath.Join(img.baseMount, string(dir))
}
//System returns the system path
func (img BaseImage) System() string {
return img.pathToMount(systemADir)
}
// Boot returns the system-boot path
func (img BaseImage) Boot() string {
return img.pathToMount(bootDir)
}
// BaseMount returns the base directory used to mount the image partitions.
func (img BaseImage) BaseMount() string {
if img.baseMount == "" {
panic("image needs to be mounted")
}
return img.baseMount
}
func (img *BaseImage) GenericBootSetup(bootPath string) error {
// origins
hardwareYamlPath := filepath.Join(img.baseMount, hardwareFileName)
kernelPath := filepath.Join(img.baseMount, img.hardware.Kernel)
initrdPath := filepath.Join(img.baseMount, img.hardware.Initrd)
// populate both A/B
for _, part := range img.oem.SystemParts() {
path := filepath.Join(bootPath, part)
printOut("Setting up", path)
if err := os.MkdirAll(path, 0755); err != nil {
return err
}
if err := sysutils.CopyFile(hardwareYamlPath, filepath.Join(path, hardwareFileName)); err != nil {
return err
}
if err := sysutils.CopyFile(kernelPath, filepath.Join(path, kernelFileName)); err != nil {
return err
}
if err := sysutils.CopyFile(initrdPath, filepath.Join(path, initrdFileName)); err != nil {
return err
}
}
oemRoot, err := img.oem.InstallPath()
if err != nil {
return err
}
return setupBootAssetFiles(img.Boot(), bootPath, oemRoot, img.oem.OEM.Hardware.BootAssets.Files)
}
func (img *BaseImage) FlashExtra() error {
oemRoot, err := img.oem.InstallPath()
if err != nil {
return err
}
if bootAssets := img.oem.OEM.Hardware.BootAssets; bootAssets != nil {
if bootAssets.RawPartitions != nil {
if err := setupBootAssetRawPartitions(img.location, img.partCount, bootAssets.RawPartitions); err != nil {
return err
}
}
return setupBootAssetRawFiles(img.location, oemRoot, bootAssets.RawFiles)
}
return nil
}
func printOut(args ...interface{}) {
if debugPrint {
fmt.Println(args...)
}
}
goget-ubuntu-touch-0.34/diskimage/common_test.go 0000664 0001750 0001750 00000003330 12621156354 021730 0 ustar egon egon 0000000 0000000 //
// diskimage - handles ubuntu disk images
//
// Copyright (c) 2015 Canonical Ltd.
//
// Written by Sergio Schvezov
//
package diskimage
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License version 3, as published
// by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranties of
// MERCHANTABILITY, SATISFACTORY QUALITY, 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, see .
import (
"os"
"path/filepath"
. "launchpad.net/gocheck"
)
type CommonTestSuite struct {
tmpdir string
oem OemDescription
packageInst string
}
var _ = Suite(&CommonTestSuite{})
func (s *CommonTestSuite) SetUpTest(c *C) {
s.tmpdir = c.MkDir()
s.oem = OemDescription{Name: "packagename", Version: "42"}
s.packageInst = s.oem.Name
}
func (s *CommonTestSuite) TestOemInstallPath(c *C) {
err := os.MkdirAll(filepath.Join(s.tmpdir, "oem", s.packageInst, "current"), 0755)
c.Assert(err, IsNil)
s.oem.SetRoot(s.tmpdir)
installPath, err := s.oem.InstallPath()
c.Assert(err, IsNil)
c.Assert(installPath, Equals, filepath.Join(s.tmpdir, "oem/packagename/current"))
}
func (s *CommonTestSuite) TestOemInstallPathNoOem(c *C) {
err := os.MkdirAll(filepath.Join(s.tmpdir, "oem", s.packageInst), 0755)
c.Assert(err, IsNil)
s.oem.SetRoot(s.tmpdir)
installPath, err := s.oem.InstallPath()
c.Assert(err, NotNil)
c.Assert(installPath, Equals, "")
}
goget-ubuntu-touch-0.34/diskimage/core_uboot.go 0000664 0001750 0001750 00000013414 12700703017 021535 0 ustar egon egon 0000000 0000000 //
// diskimage - handles ubuntu disk images
//
// Copyright (c) 2013 Canonical Ltd.
//
// Written by Sergio Schvezov
//
package diskimage
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
"text/template"
"launchpad.net/goget-ubuntu-touch/sysutils"
)
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License version 3, as published
// by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranties of
// MERCHANTABILITY, SATISFACTORY QUALITY, 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, see .
type CoreUBootImage struct {
BaseImage
}
const snappySystemTemplate = `# This is a snappy variables and boot logic file and is entirely generated and
# managed by Snappy. Modifications may break boot
######
# functions to load kernel, initrd and fdt from various env values
loadfiles=run loadkernel; run loadinitrd; run loadfdt
loadkernel=load mmc ${mmcdev}:${mmcpart} ${loadaddr} ${snappy_ab}/${kernel_file}
loadinitrd=load mmc ${mmcdev}:${mmcpart} ${initrd_addr} ${snappy_ab}/${initrd_file}; setenv initrd_size ${filesize}
loadfdt=load mmc ${mmcdev}:${mmcpart} ${fdtaddr} ${snappy_ab}/dtbs/${fdtfile}
# standard kernel and initrd file names; NB: fdtfile is set early from bootcmd
kernel_file={{ .Kernel }}
initrd_file={{ .Initrd }}
{{ .Fdt }}
# extra kernel cmdline args, set via mmcroot
snappy_cmdline=init=/lib/systemd/systemd ro panic=-1 fixrtc
# boot logic
# either "a" or "b"; target partition we want to boot
snappy_ab=a
# stamp file indicating a new version is being tried; removed by s-i after boot
snappy_stamp=snappy-stamp.txt
# either "regular" (normal boot) or "try" when trying a new version
snappy_mode=regular
# if we're trying a new version, check if stamp file is already there to revert
# to other version
snappy_boot=if test "${snappy_mode}" = "try"; then if test -e mmc ${bootpart} ${snappy_stamp}; then if test "${snappy_ab}" = "a"; then setenv snappy_ab "b"; else setenv snappy_ab "a"; fi; else fatwrite mmc ${mmcdev}:${mmcpart} 0x0 ${snappy_stamp} 0; fi; fi; run loadfiles; setenv mmcroot /dev/disk/by-label/system-${snappy_ab} ${snappy_cmdline}; run mmcargs; bootz ${loadaddr} ${initrd_addr}:${initrd_size} ${fdtaddr}
`
type FlashInstructions struct {
Bootloader []string `yaml:"bootloader"`
}
func NewCoreUBootImage(location string, size int64, rootSize int, hw HardwareDescription, oem OemDescription, label string) *CoreUBootImage {
return &CoreUBootImage{
BaseImage{
hardware: hw,
oem: oem,
location: location,
size: size,
rootSize: rootSize,
partCount: 4,
label: label,
},
}
}
//Partition creates a partitioned image from an img
func (img *CoreUBootImage) Partition() error {
if err := sysutils.CreateEmptyFile(img.location, img.size, sysutils.GB); err != nil {
return err
}
table := mkLabelMsdos
if img.label == "gpt" {
table = mkLabelGpt
}
parted, err := newParted(table)
if err != nil {
return err
}
parted.addPart(bootLabel, bootDir, fsFat32, 128)
parted.addPart(systemALabel, systemADir, fsExt4, 1024)
parted.addPart(systemBLabel, systemBDir, fsExt4, 1024)
parted.addPart(writableLabel, writableDir, fsExt4, -1)
parted.setBoot(1)
img.parts = parted.parts
return parted.create(img.location)
}
func (img CoreUBootImage) SetupBoot() error {
// destinations
bootPath := filepath.Join(img.baseMount, string(bootDir))
bootSnappySystemPath := filepath.Join(bootPath, "snappy-system.txt")
if err := img.GenericBootSetup(bootPath); err != nil {
return err
}
// populate both A/B
for _, part := range img.oem.SystemParts() {
bootDtbPath := filepath.Join(bootPath, part, "dtbs")
if err := img.provisionDtbs(bootDtbPath); err != nil {
return err
}
}
snappySystemFile, err := os.Create(bootSnappySystemPath)
if err != nil {
return err
}
defer snappySystemFile.Close()
var fdtfile string
if platform := img.oem.Platform(); platform != "" {
fdtfile = fmt.Sprintf("fdtfile=%s.dtb", platform)
}
templateData := struct{ Fdt, Kernel, Initrd string }{
Fdt: fdtfile, Kernel: kernelFileName, Initrd: initrdFileName,
}
t := template.Must(template.New("snappy-system").Parse(snappySystemTemplate))
t.Execute(snappySystemFile, templateData)
return nil
}
func (img CoreUBootImage) provisionDtbs(bootDtbPath string) error {
dtbsPath := filepath.Join(img.baseMount, img.hardware.Dtbs)
if _, err := os.Stat(dtbsPath); os.IsNotExist(err) {
return nil
} else if err != nil {
return err
}
dtbFis, err := ioutil.ReadDir(dtbsPath)
if err != nil {
return err
}
if err := os.MkdirAll(bootDtbPath, 0755); err != nil {
return err
}
dtb := filepath.Join(dtbsPath, fmt.Sprintf("%s.dtb", img.oem.Platform()))
// if there is a specific dtb for the platform, copy it.
// First look in oem and then in device.
if oemDtb := img.oem.OEM.Hardware.Dtb; oemDtb != "" && img.oem.Platform() != "" {
oemRoot, err := img.oem.InstallPath()
if err != nil {
return err
}
oemDtb := filepath.Join(oemRoot, oemDtb)
dst := filepath.Join(bootDtbPath, filepath.Base(dtb))
if err := sysutils.CopyFile(oemDtb, dst); err != nil {
return err
}
} else if _, err := os.Stat(dtb); err == nil {
dst := filepath.Join(bootDtbPath, filepath.Base(dtb))
if err := sysutils.CopyFile(dtb, dst); err != nil {
return err
}
} else {
for _, dtbFi := range dtbFis {
src := filepath.Join(dtbsPath, dtbFi.Name())
dst := filepath.Join(bootDtbPath, dtbFi.Name())
if err := sysutils.CopyFile(src, dst); err != nil {
return err
}
}
}
return nil
}
goget-ubuntu-touch-0.34/diskimage/customization.go 0000664 0001750 0001750 00000004726 12621156354 022323 0 ustar egon egon 0000000 0000000 //
// ubuntu-emu - Tool to download and run Ubuntu Touch emulator instances
//
// Copyright (c) 2013 Canonical Ltd.
//
// Written by Sergio Schvezov
//
package diskimage
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License version 3, as published
// by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranties of
// MERCHANTABILITY, SATISFACTORY QUALITY, 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, see .
import (
"fmt"
"io/ioutil"
"os"
"path/filepath"
)
const networkConfig string = `# interfaces(5) file used by ifup(8) and ifdown(8)
auto lo
iface lo inet loopback
auto eth0
iface eth0 inet static
address 10.0.2.15
netmask 255.255.255.0
gateway 10.0.2.2
dns-nameservers 10.0.2.3
iface eth1 inet manual
iface eth2 inet manual
iface eth3 inet manual
iface eth4 inet manual
iface eth5 inet manual
`
type setupFile struct{ path, content string }
var setupFiles = []setupFile{
{"custom/custom.prop", "custom.location.fake=true"},
{"etc/network/interfaces", networkConfig},
{"etc/profile.d/hud-service.sh", "export HUD_DISABLE_VOICE=1"},
}
//setupFile writes a setup to a target file
func (img DiskImage) writeFile(file setupFile) error {
profilePath := filepath.Join(img.Mountpoint, file.path)
dirPath := filepath.Dir(profilePath)
if fi, err := os.Stat(dirPath); err != nil {
if err := os.MkdirAll(dirPath, 0755); err != nil {
fmt.Println(err)
}
} else if !fi.IsDir() {
return fmt.Errorf("%s is not a directory, customization failed", profilePath)
}
if err := ioutil.WriteFile(profilePath, []byte(file.content), 0644); err != nil {
return err
}
return nil
}
//Writable allows writes on the created running image
func (img DiskImage) Writable() error {
writeFlag := filepath.Join(img.Mountpoint, ".writable_image")
if err := ioutil.WriteFile(writeFlag, []byte(""), 0644); err != nil {
return err
}
return nil
}
//OverrideAdbInhibit will inhibit abd from shutting down when the screen is locked
func (img DiskImage) OverrideAdbInhibit() error {
writeFlag := filepath.Join(img.Mountpoint, ".adb_onlock")
return ioutil.WriteFile(writeFlag, []byte(""), 0644)
}
goget-ubuntu-touch-0.34/devices/ 0000775 0001750 0001750 00000000000 12700710721 016530 5 ustar egon egon 0000000 0000000 goget-ubuntu-touch-0.34/devices/fastboot.go 0000664 0001750 0001750 00000005500 12621156354 020710 0 ustar egon egon 0000000 0000000 //
// Helpers to talk to devices that support ADB or Fastboot
//
// Copyright (c) 2013 Canonical Ltd.
//
// Written by Sergio Schvezov
//
package devices
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License version 3, as published
// by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranties of
// MERCHANTABILITY, SATISFACTORY QUALITY, 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, see .
import (
"os/exec"
"strings"
)
var fastbootCommand string
func init() {
fastbootCommand = "fastboot"
}
// Sets the serial device to connect to for future calls to *fastboot
func (fastboot *Fastboot) SetSerial(serial string) {
fastboot.serial = serial
fastboot.params = append(fastboot.params, []string{"-s", serial}...)
}
// Reboot restarts the system from the Android bootloader
func (fastboot Fastboot) Reboot() (err error) {
cmd := append(fastboot.params, []string{"reboot"}...)
err = exec.Command(fastbootCommand, cmd...).Run()
return err
}
// Boot boots the system from the Android bootloader from the boot partition
func (fastboot Fastboot) Boot() (err error) {
cmd := append(fastboot.params, []string{"boot"}...)
err = exec.Command(fastbootCommand, cmd...).Run()
return err
}
// BootImage boots the system from the Android specified boot image
func (fastboot Fastboot) BootImage(image string) (err error) {
cmd := append(fastboot.params, []string{"boot", image}...)
err = exec.Command(fastbootCommand, cmd...).Run()
return err
}
// Flash flashes the specified image to partition on the device
func (fastboot Fastboot) Flash(partition, image string) (err error) {
cmd := append(fastboot.params, []string{"flash", partition, image}...)
err = exec.Command(fastbootCommand, cmd...).Run()
return err
}
// Format formats the specified partition on the device
func (fastboot Fastboot) Format(partition string) (err error) {
cmd := append(fastboot.params, []string{"format", partition}...)
err = exec.Command(fastbootCommand, cmd...).Run()
return err
}
// GetDevice obtains the device name from fastboot
func (fastboot Fastboot) GetDevice() (device string, err error) {
cmd := append(fastboot.params, []string{"getvar", "product"}...)
deviceOutput, err := exec.Command(fastbootCommand, cmd...).CombinedOutput()
lines := strings.Split(string(deviceOutput), "\n")
for _, line := range lines {
fields := strings.Split(line, ":")
if strings.Contains(fields[0], "product") {
device = strings.TrimSpace(fields[1])
break
}
}
return device, err
}
goget-ubuntu-touch-0.34/devices/adb.go 0000664 0001750 0001750 00000011234 12621156354 017616 0 ustar egon egon 0000000 0000000 // Copyright (c) 2013 Canonical Ltd.
//
// Written by Sergio Schvezov
//
package devices
import (
"errors"
"fmt"
"os/exec"
"strings"
"time"
)
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License version 3, as published
// by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranties of
// MERCHANTABILITY, SATISFACTORY QUALITY, 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, see .
var adbCommand string
func init() {
// adbCommand = "adb.exe"
adbCommand = "adb"
}
// Returns an AndroidDebugBridge while ensuring the server is started
func NewAndroidDebugBridge() (adb AndroidDebugBridge, err error) {
err = exec.Command(adbCommand, "start-server").Run()
return adb, err
}
// Returns an AndroidDebugBridge while ensuring the server is started
func NewUbuntuDebugBridge() (adb UbuntuDebugBridge, err error) {
err = exec.Command(adbCommand, "start-server").Run()
return adb, err
}
// Sets the serial device to connect to for future calls to *adb
func (adb *AndroidDebugBridge) SetSerial(serial string) {
adb.serial = serial
adb.params = append(adb.params, []string{"-s", serial}...)
}
// Shell runs a specific command on the target device
func (adb *AndroidDebugBridge) Shell(command ...string) (string, error) {
cmd := append(adb.params, "shell")
cmd = append(cmd, command...)
out, err := exec.Command(adbCommand, cmd...).Output()
if err != nil {
return "", err
}
return strings.TrimSpace(string(out)), nil
}
// GetDevice parses the android property system to determine the device being used
func (adb *AndroidDebugBridge) GetDevice() (deviceName string, err error) {
cmd := append(adb.params, []string{"shell", "getprop", "ro.product.device"}...)
out, err := exec.Command(adbCommand, cmd...).Output()
if err != nil {
return deviceName, err
}
// This will fail if a device name ever leaves ASCII
adb.deviceName = strings.TrimSpace(string(out))
return adb.deviceName, err
}
// Push copies a file from src to dst over the adb server
func (adb AndroidDebugBridge) Push(src, dst string) (err error) {
// TODO add file path verification
cmd := append(adb.params, []string{"push", src, dst}...)
b, err := exec.Command(adbCommand, cmd...).CombinedOutput()
if err != nil {
return fmt.Errorf("error pushing: %s\n", b)
}
return nil
}
// Pull copies a file from src to dst over the adb server
func (adb AndroidDebugBridge) Pull(src, dst string) (err error) {
// TODO add file path verification
cmd := append(adb.params, []string{"pull", src, dst}...)
return exec.Command(adbCommand, cmd...).Run()
}
// RebootBooloader restarts the system into the bootloader
func (adb AndroidDebugBridge) RebootBootloader() (err error) {
return adb.reboot("bootloader")
}
// RebootRecovery restarts the system into recovery
func (adb AndroidDebugBridge) RebootRecovery() (err error) {
return adb.reboot("recovery")
}
// reboot restarts into the desired target
func (adb AndroidDebugBridge) reboot(mode string) (err error) {
cmd := append(adb.params, []string{"reboot", mode}...)
return exec.Command(adbCommand, cmd...).Run()
}
// Reboot restarts the system from the shell. This is different than
// calling adb reboot directly.
func (adb UbuntuDebugBridge) Reboot() (err error) {
cmd := append(adb.params, []string{"shell", "reboot"}...)
return exec.Command(adbCommand, cmd...).Run()
}
// WaitForDevice waits for the device to be available
func (adb UbuntuDebugBridge) WaitForDevice() (err error) {
cmd := append(adb.params, []string{"wait-for-device"}...)
err = exec.Command(adbCommand, cmd...).Run()
return err
}
// WaitForRecovery idles until the image has booted into recovery
// for recovery
func (adb UbuntuDebugBridge) WaitForRecovery() error {
// Recovery takes some time to get into, so we wait a bit
time.Sleep(10 * time.Second)
done := make(chan bool)
cmd := append(adb.params, []string{"shell", "ls"}...)
go func() {
for {
err := exec.Command(adbCommand, cmd...).Run()
if err == nil {
done <- true
}
time.Sleep(5 * time.Second)
}
}()
for {
select {
case <-done:
return nil
case <-time.After(60 * time.Second):
return errors.New(fmt.Sprint("Failed to enter Recovery"))
}
}
}
// Ping pings the device to know it's there
func (adb UbuntuDebugBridge) Ping() (err error) {
cmd := append(adb.params, []string{"shell", "ls"}...)
return exec.Command(adbCommand, cmd...).Run()
}
goget-ubuntu-touch-0.34/devices/types.go 0000664 0001750 0001750 00000002110 12621156354 020225 0 ustar egon egon 0000000 0000000 //
// Helpers to talk to devices that support ADB or Fastboot
//
// Copyright (c) 2013 Canonical Ltd.
//
// Written by Sergio Schvezov
//
package devices
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License version 3, as published
// by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranties of
// MERCHANTABILITY, SATISFACTORY QUALITY, 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, see .
type deviceCapabilities interface {
Reboot()
}
type device struct {
serial, deviceName string
params []string
}
type AndroidDebugBridge struct {
deviceCapabilities
device
}
type UbuntuDebugBridge struct {
AndroidDebugBridge
}
type Fastboot struct {
deviceCapabilities
device
}
goget-ubuntu-touch-0.34/ubuntu-emulator/ 0000775 0001750 0001750 00000000000 12700710721 020256 5 ustar egon egon 0000000 0000000 goget-ubuntu-touch-0.34/ubuntu-emulator/run_test.go 0000664 0001750 0001750 00000003073 12621156354 022463 0 ustar egon egon 0000000 0000000 /*
* Copyright 2014 Canonical Ltd.
*
* Authors:
* Sergio Schvezov: sergio.schvezov@canonical.com
*
* This file is part of ubuntu-emulator.
*
* ubuntu-emulator 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; version 3.
*
* ubuntu-emulator 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, see .
*/
package main
import (
"os"
"path/filepath"
"testing"
. "launchpad.net/gocheck"
)
var _ = Suite(&EmulatorRunTestSuite{})
type EmulatorRunTestSuite struct {
tmpDir string
}
func (s *EmulatorRunTestSuite) SetUpTest(c *C) {
s.tmpDir = c.MkDir()
}
func Test(t *testing.T) { TestingT(t) }
func (s *EmulatorRunTestSuite) TestRunPathInstalled(c *C) {
c.Assert(getEmulatorCmd(), Equals, filepath.Join(installPath, subpathEmulatorCmd))
}
func (s *EmulatorRunTestSuite) TestRunPathAndroidTree(c *C) {
emuCmd := filepath.Join(s.tmpDir, subpathEmulatorCmd)
os.MkdirAll(filepath.Dir(emuCmd), 0777)
cmdFile, err := os.Create(emuCmd)
c.Assert(err, IsNil)
cmdFile.Chmod(0755)
cmdFile.Close()
c.Assert(os.Setenv("ANDROID_BUILD_TOP", s.tmpDir), IsNil)
c.Assert(getEmulatorCmd(), Equals, emuCmd)
c.Assert(os.Setenv("ANDROID_BUILD_TOP", ""), IsNil)
}
goget-ubuntu-touch-0.34/ubuntu-emulator/create.go 0000664 0001750 0001750 00000027344 12621156354 022072 0 ustar egon egon 0000000 0000000 //
// ubuntu-emu - Tool to download and run Ubuntu Touch emulator instances
//
// Copyright (c) 2013 Canonical Ltd.
//
// Written by Sergio Schvezov
//
package main
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License version 3, as published
// by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranties of
// MERCHANTABILITY, SATISFACTORY QUALITY, 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, see .
import (
"bufio"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"syscall"
"text/template"
"launchpad.net/goget-ubuntu-touch/diskimage"
"launchpad.net/goget-ubuntu-touch/sysutils"
"launchpad.net/goget-ubuntu-touch/ubuntuimage"
)
type CreateCmd struct {
Channel string `long:"channel" description:"Select device channel"`
Server string `long:"server" description:"Select image server"`
Revision int `long:"revision" description:"Select revision"`
RawDisk bool `long:"use-raw-disk" description:"Use raw disks instead of qcow2"`
SDCard bool `long:"with-sdcard" description:"Create an external vfat sdcard"`
Arch string `long:"arch" description:"Device architecture to use (i386 or armhf)"`
Password string `long:"password" description:"This sets up the default password for the phablet user" default:"0000"`
Locale string `long:"locale" description:"Use a different locale than the default one (e.g.; --locale es_AR.utf8)"`
}
var createCmd CreateCmd
const (
defaultChannel = "ubuntu-touch/devel"
defaultServer = "https://system-image.ubuntu.com"
defaultArch = "i386"
)
const (
binQemuArmStatic = "/usr/bin/qemu-arm-static"
pkgQemuUserStatic = "qemu-user-static"
)
const localeTemplate string = `description "Set wizard language"
author "ubuntu-emulator"
start on starting ubuntu-system-settings-wizard
task
script
setenv() {
initctl set-env --global $1=$2
gdbus call --session --dest org.freedesktop.DBus --object-path /org/freedesktop/DBus --method org.freedesktop.DBus.UpdateActivationEnvironment "@a{ss} {'$1': '$2'}"
}
uid=$(getent passwd $USER|cut -d: -f3)
if [ -z $uid ];then
exit 1
fi
if [ ! -e $HOME/.cache/.first-lang-set ]; then
setenv LANGUAGE {{ . }}
setenv LC_ALL {{ . }}
setenv LANG {{ . }}
dbus-send --print-reply --system --dest=org.freedesktop.Accounts /org/freedesktop/Accounts/User$uid org.freedesktop.Accounts.User.SetFormatsLocale string:{{ . }}
dbus-send --print-reply --system --dest=org.freedesktop.Accounts /org/freedesktop/Accounts/User$uid org.freedesktop.Accounts.User.SetLanguage string:{{ . }}
touch $HOME/.cache/.first-lang-set
fi
end script
# vim:syntax=upstart
`
func init() {
createCmd.Arch = defaultArch
createCmd.Channel = defaultChannel
createCmd.Server = defaultServer
parser.AddCommand("create",
"Create new emulator instance named 'name'",
"Creates a new emulator instance name 'name' by downloading the necessary components "+
"from the image server",
&createCmd)
}
func (createCmd *CreateCmd) Execute(args []string) error {
if len(args) != 1 {
return errors.New("Instance name 'name' is required")
}
instanceName := args[0]
if err := createCmd.verifyDependencies(); err != nil {
return err
}
var device string
if d, ok := devices[createCmd.Arch]; ok {
device = d["name"]
} else {
return errors.New("Selected device not supported on this channel")
}
if syscall.Getuid() != 0 {
return errors.New("Creation requires sudo/pkexec (root)")
}
// hack to circumvent https://code.google.com/p/go/issues/detail?id=1435
runtime.GOMAXPROCS(1)
runtime.LockOSThread()
if err := sysutils.DropPrivs(); err != nil {
return err
}
channels, err := ubuntuimage.NewChannels(createCmd.Server)
if err != nil {
return err
}
deviceChannel, err := channels.GetDeviceChannel(
createCmd.Server, createCmd.Channel, device)
if err != nil {
return err
}
var image ubuntuimage.Image
if createCmd.Revision <= 0 {
image, err = deviceChannel.GetRelativeImage(createCmd.Revision)
} else {
image, err = deviceChannel.GetImage(createCmd.Revision)
}
if err != nil {
return err
}
fmt.Printf("Creating \"%s\" from %s revision %d\n", instanceName, createCmd.Channel, image.Version)
fmt.Println("Downloading...")
files, _ := download(image)
dataDir := getInstanceDataDir(instanceName)
if os.MkdirAll(dataDir, 0700) != nil {
return err
}
fmt.Println("Setting up...")
//This image will later be copied into sdcard.img as system.img and will hold the Ubuntu rootfs
ubuntuImage := diskimage.New(filepath.Join(dataDir, "ubuntu-system.img"), "UBUNTU", 3)
//This image represents userdata, it will be marked with .writable_image and hold the
//Ubuntu rootfs.
sdcardImage := diskimage.New(filepath.Join(dataDir, "sdcard.img"), "USERDATA", 4)
systemImage := diskimage.NewExisting(filepath.Join(dataDir, "system.img"))
if err := createCmd.createSystem(ubuntuImage, sdcardImage, files); err != nil {
return err
}
var deviceTar string
if deviceTar, err = getDeviceTar(files); err != nil {
return err
}
if err = flatExtractImages(deviceTar, dataDir); err != nil {
return err
}
// boot.img must be in dataDir (Normal Boot Ramdisk)
if err = extractBoot(dataDir, bootImage, bootRamdisk); err != nil {
return err
}
// recovery.img must be in dataDir (Recovery Ramdisk)
if err = extractBoot(dataDir, recoveryImage, recoveryRamdisk); err != nil {
return err
}
if err := extractBuildProperties(systemImage, dataDir); err != nil {
return err
}
if createCmd.RawDisk != true {
fmt.Println("Creating snapshots for disks...")
for _, img := range []*diskimage.DiskImage{systemImage, sdcardImage} {
if err := img.ConvertQcow2(); err != nil {
return err
}
}
}
if createCmd.SDCard {
fmt.Println("Creating vfat sdcard...")
sdcard := diskimage.New(filepath.Join(dataDir, "sdcardprime.img"), "SDCARD", 2)
if err := sdcard.CreateVFat(); err != nil {
return err
}
}
if err = writeStamp(dataDir, image); err != nil {
return err
}
if err = writeDeviceStamp(dataDir, createCmd.Arch); err != nil {
return err
}
fmt.Printf("Succesfully created emulator instance %s in %s\n", instanceName, dataDir)
return nil
}
func extractBuildProperties(systemImage *diskimage.DiskImage, dataDir string) error {
// hack to circumvent https://code.google.com/p/go/issues/detail?id=1435
runtime.GOMAXPROCS(1)
runtime.LockOSThread()
return systemImage.ExtractFile("build.prop", filepath.Join(dataDir, "system"))
}
func (createCmd *CreateCmd) verifyDependencies() error {
switch createCmd.Arch {
case "armhf":
if _, err := os.Stat(binQemuArmStatic); err != nil {
return fmt.Errorf("missing dependency %s (apt install %s)", binQemuArmStatic, pkgQemuUserStatic)
}
}
return nil
}
func (createCmd *CreateCmd) createSystem(ubuntuImage, sdcardImage *diskimage.DiskImage, files []string) (err error) {
for _, img := range []*diskimage.DiskImage{ubuntuImage, sdcardImage} {
if err := img.CreateExt4(); err != nil {
return err
}
}
// hack to circumvent https://code.google.com/p/go/issues/detail?id=1435
runtime.GOMAXPROCS(1)
runtime.LockOSThread()
if err := sysutils.EscalatePrivs(); err != nil {
return err
}
defer func() (err error) {
return sysutils.DropPrivs()
}()
if err := ubuntuImage.Mount(); err != nil {
return err
}
if err := ubuntuImage.Provision(files); err != nil {
if err := ubuntuImage.Unmount(); err != nil {
fmt.Println("Unmount error:", err)
}
return err
}
fmt.Printf("Setting up a default password for phablet to: '%s'\n", createCmd.Password)
if err := createCmd.setPassword(ubuntuImage.Mountpoint); err != nil {
if err := ubuntuImage.Unmount(); err != nil {
fmt.Println("Unmount error :", err)
}
return err
}
if err := createCmd.setLocale(ubuntuImage.Mountpoint); err != nil {
if err := ubuntuImage.Unmount(); err != nil {
fmt.Println("Unmount error :", err)
}
return err
}
if err := ubuntuImage.Unmount(); err != nil {
return err
}
if err := sdcardImage.Mount(); err != nil {
return err
}
defer sdcardImage.Unmount()
if err = sdcardImage.Writable(); err != nil {
return err
}
if err = sdcardImage.OverrideAdbInhibit(); err != nil {
return err
}
if err := ubuntuImage.Move(filepath.Join(sdcardImage.Mountpoint, "system.img")); err != nil {
return err
}
return nil
}
// setLocale sets the locale to the one specified in locale
func (createCmd *CreateCmd) setLocale(chroot string) error {
if createCmd.Locale == "" {
return nil
}
if createCmd.Arch == "armhf" {
if err := addQemuStatic(chroot); err != nil {
return err
}
defer removeQemuStatic(chroot)
}
cmd := exec.Command("chroot", chroot, "/bin/sh", "-c", "locale -a")
stdout, err := cmd.StdoutPipe()
if err != nil {
return err
}
if err := cmd.Start(); err != nil {
return err
}
// Verify that the locale is actually part of the emulator
var localeInstalled bool
scanner := bufio.NewScanner(stdout)
for scanner.Scan() {
locale := scanner.Text()
if createCmd.Locale == locale {
localeInstalled = true
break
}
}
if !localeInstalled {
return errors.New("the selected locale is not available on the image")
}
if err := scanner.Err(); err != nil {
return err
}
if err := cmd.Wait(); err != nil {
return err
}
// Setup the locale
localeFile, err := os.Create(filepath.Join(chroot, "/usr/share/upstart/sessions/emulator-language.conf"))
if err != nil {
return err
}
defer localeFile.Close()
t := template.Must(template.New("locale").Parse(localeTemplate))
return t.Execute(localeFile, createCmd.Locale)
}
// setPassword is an ugly hack to set the password
func (createCmd *CreateCmd) setPassword(chroot string) error {
if createCmd.Arch == "armhf" {
if err := addQemuStatic(chroot); err != nil {
return err
}
defer removeQemuStatic(chroot)
}
// Run something that would look like this
// PATH=$path chroot "$SYSTEM_MOUNTPOINT" /bin/sh -c "echo -n "$user:$password" | chpasswd"
chrootCmd := fmt.Sprintf("echo -n '%s:%s' | chpasswd", "phablet", createCmd.Password)
if out, err := exec.Command("chroot", chroot, "/bin/sh", "-c", chrootCmd).CombinedOutput(); err != nil {
return errors.New(string(out))
}
return nil
}
func addQemuStatic(chroot string) error {
dst := filepath.Join(chroot, binQemuArmStatic)
if out, err := exec.Command("cp", binQemuArmStatic, dst).CombinedOutput(); err != nil {
return fmt.Errorf("issues while setting up password: %s", out)
}
return nil
}
func removeQemuStatic(chroot string) error {
dst := filepath.Join(chroot, binQemuArmStatic)
return os.Remove(dst)
}
func download(image ubuntuimage.Image) (files []string, err error) {
cacheDir := ubuntuimage.GetCacheDir()
totalFiles := len(image.Files)
done := make(chan string, totalFiles)
for _, file := range image.Files {
go bitDownloader(file, done, createCmd.Server, cacheDir)
}
for i := 0; i < totalFiles; i++ {
files = append(files, <-done)
}
return files, nil
}
// bitDownloader downloads
func bitDownloader(file ubuntuimage.File, done chan<- string, server, downloadDir string) {
err := file.MakeRelativeToServer(server)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// hack to circumvent https://code.google.com/p/go/issues/detail?id=1435
runtime.GOMAXPROCS(1)
runtime.LockOSThread()
if err := sysutils.DropPrivs(); err != nil {
fmt.Println(err)
os.Exit(1)
}
err = file.Download(downloadDir)
if err != nil {
fmt.Printf("Cannot download %s%s: %s\n", file.Server, file.Path, err)
os.Exit(1)
}
filePath := filepath.Join(downloadDir, file.Path)
done <- filePath
}
goget-ubuntu-touch-0.34/ubuntu-emulator/stamp.go 0000664 0001750 0001750 00000003743 12621156354 021750 0 ustar egon egon 0000000 0000000 //
// ubuntu-emu - Tool to download and run Ubuntu Touch emulator instances
//
// Copyright (c) 2013 Canonical Ltd.
//
// Written by Sergio Schvezov
//
package main
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License version 3, as published
// by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranties of
// MERCHANTABILITY, SATISFACTORY QUALITY, 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, see .
import (
"bufio"
"encoding/json"
"io/ioutil"
"os"
"path/filepath"
"launchpad.net/goget-ubuntu-touch/ubuntuimage"
)
func writeDeviceStamp(dataDir, device string) (err error) {
path := filepath.Join(dataDir, ".device")
return ioutil.WriteFile(path, []byte(device), 0600)
}
func readDeviceStamp(dataDir string) (string, error) {
path := filepath.Join(dataDir, ".device")
device, err := ioutil.ReadFile(path)
if err != nil {
return "", err
}
return string(device), nil
}
func writeStamp(dataDir string, image ubuntuimage.Image) (err error) {
path := filepath.Join(dataDir, ".stamp")
file, err := os.Create(path)
if err != nil {
return err
}
defer func() {
file.Close()
if err != nil {
os.Remove(path)
}
}()
w := bufio.NewWriter(file)
defer w.Flush()
jsonWriter := json.NewEncoder(w)
if err := jsonWriter.Encode(image); err != nil {
return err
}
return nil
}
func readStamp(dataDir string) (image ubuntuimage.Image, err error) {
path := filepath.Join(dataDir, ".stamp")
file, err := os.Open(path)
if err != nil {
return image, err
}
jsonReader := json.NewDecoder(file)
if err := jsonReader.Decode(&image); err != nil {
return image, err
}
return image, nil
}
goget-ubuntu-touch-0.34/ubuntu-emulator/extract.go 0000664 0001750 0001750 00000004674 12621156354 022302 0 ustar egon egon 0000000 0000000 //
// ubuntu-emu - Tool to download and run Ubuntu Touch emulator instances
//
// Copyright (c) 2013 Canonical Ltd.
//
// Written by Sergio Schvezov
//
package main
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License version 3, as published
// by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranties of
// MERCHANTABILITY, SATISFACTORY QUALITY, 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, see .
import (
"archive/tar"
"bufio"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path"
"path/filepath"
)
func flatExtractImages(tarxz, dataDir string) error {
f, err := os.Open(tarxz)
if err != nil {
return errors.New(fmt.Sprintf("Can't open %s for extraction", tarxz))
}
r := xzReader(f)
tempfile, err := ioutil.TempFile(os.TempDir(), "image")
if err != nil {
return errors.New("Can't create tempfile to create emulator instance")
}
defer func() {
tempfile.Close()
os.Remove(tempfile.Name())
}()
n, err := io.Copy(tempfile, r)
if err != nil {
return errors.New(fmt.Sprintf("copied %d bytes with err: %v", n, err))
}
_, err = tempfile.Seek(0, 0)
if err != nil {
return errors.New("Failed to rewind")
}
tr := tar.NewReader(tempfile)
var imageFile *os.File
for {
hdr, err := tr.Next()
if err == io.EOF {
// end of tar archive
break
}
if err != nil {
return err
}
imageFileName := path.Base(hdr.Name)
if path.Ext(imageFileName) != ".img" {
fmt.Println("Non image file found:", imageFileName, hdr.Name)
continue
}
if imageFile, err = os.Create(filepath.Join(dataDir, imageFileName)); err != nil {
return err
}
defer imageFile.Close()
writer := bufio.NewWriter(imageFile)
reader := bufio.NewReader(tr)
defer func() {
if err == nil {
err = writer.Flush()
}
}()
if _, err := io.Copy(writer, reader); err != nil {
return err
}
}
return nil
}
func xzReader(r io.Reader) io.ReadCloser {
rpipe, wpipe := io.Pipe()
cmd := exec.Command("xz", "--decompress", "--stdout")
cmd.Stdin = r
cmd.Stdout = wpipe
go func() {
err := cmd.Run()
wpipe.CloseWithError(err)
}()
return rpipe
}
goget-ubuntu-touch-0.34/ubuntu-emulator/skins/ 0000775 0001750 0001750 00000000000 12700710721 021405 5 ustar egon egon 0000000 0000000 goget-ubuntu-touch-0.34/ubuntu-emulator/skins/EDGE/ 0000775 0001750 0001750 00000000000 12700710721 022111 5 ustar egon egon 0000000 0000000 goget-ubuntu-touch-0.34/ubuntu-emulator/skins/EDGE/edge-land.png 0000664 0001750 0001750 00001155335 12621156354 024464 0 ustar egon egon 0000000 0000000 ‰PNG
IHDR í ¹ô.k bKGD ÿ ÿ ÿ ½§“ pHYs .# .#x¥?v tIMEÞ
]qM IDATxÚì½iŒ\çq6úœÓ=½LÏÒ³/äp(®E‘²%y[‰ãEqèCF Føþ] rƒüKø"À‡\àCdAX€qáäC`ĉ'ÈçØŠ6J”L™¤(—áìk÷LïÝçÜÓõ²ºXõž–ÿ]àDÎtŸå]êzê©§‚8ŽÓ " 1º‚ pOúÇñ{ûí·û½÷Þ{¦ÝnçÛí6êõ:â8F§ÓA§ÓA&“A«Õ ´ÛmA€4
ÓéÐõDZû]*• ¤Ói¤R)w½\. hµZèt:Èf³H¥Rh6›‚ ù|VÍfétÚý?CÄqŒ ÐjµÜ½Ã0D†h·ÛH¥R‚ ÕjÙl¶ç³ E‘{þó Ðét000àþžJ¥Ðh4ËåP©T044„jµŠL& H¥Rh·ÛhµZH¥R@»Ýv×ÃÐK§Óq?‚À½½SÇ=Ïûw:FîYšÍ¦»Eî=Úí6:†††P¯×‘N§Ý}øse³YÔëuwt:z½Ž\.‡(ŠÜ³Aàþ£ù¤g£ñ‰¢ ÉdÐh4¹g.—sãS«ÕÜ<A€T*åÖ½½sEîøÏi}Ñ÷¢(rcHë4Ct:¤Ói÷<´øüg³Y4
·&;â8F.—CVsïNÏ’N§Ñn·Ñl6‘ÍfÝz.
=sLë(Š"´ÛmÄqŒ0‘ÉdÐétÜÏ2™šÍ¦[OétQ¡Ùl"Žc÷|™LQ¹ëÒÜМòuGû%C´Z-äóy7ŸVËý=C¸½EsI{ºÙl"—˹÷§}Æç—¯_šš[zÖv»ÁÁAÔëu7îA P( Ñh¸5HÏEãA×¥ÿpk–Æ…ì_¯´.Ûí¶[kdŸh]ÅqìÞƒž—ÛZS|í£y$[ÅÿNãJÏBû’ž‹>CcCk”Æ–_#ŽãGž…ì@Çîýè½ø¸Ðýißd³YT*¤R)w?úA>ŸÇÁÁR©²Ù,Z–³nÃ0ì±åÜžq»Åí4ß[Qa||¨×ën¿ÑXÐgh>hÏÐsK»HóIsE?ç6•Æö
ÿýŽ¿G6›E:FVs¿cg¦›º&Ù.¾ig³ÙGÖ"ß7|}“
¡1n·Ûîûôœü;Ü>Ó¿i^iÿÓÙHߣûÓô§Ýn»5)Ï%ú;={yþô‡>Oã$Ïo¾®éû4ôíA~¦ÒÑÏh]Ò÷麴?i
¥ÓéžûËuÂÿM?ã{–Ö=3ÝÛ7æõìQîðïs—Þ‘¯;éûÐ5hÝóûòëÒ³‘] çâŸ×ÆU»&ÿ;_3|\è{ÜWÑ|#šwú¼ü¬\Û|®¸
à6›¾Ïç„·Yt}Å?îÙkòûrÌä8ñç—6DþŽÍ5íKº¶œzyNð½¨Wz¾~øïøsj{›ÏýŒŸc|ÿòÏñ9äcBïEó$ýO>Ö³ý$´÷ÕæÝúüOr?¹>þÿ?ÿßøÇq
ÀVE¯GQô¿[ÖÚíör»ÝîDQTh·ÛcÍfs¿Õj•Ïœ9À믿4›Í ^¯ív;EÑÌO4󇇇òo|ã7ðƒðàêõ:fff077‡ÑÑQºƒLfî@óCÁr¶¤óIÁíàà`ÓDŸã†–odÚ¸d¸¸æM>+]®Á]pÒ!¦ :$)Àä=Ö8Ž{€2¶˜I'–îüq‰²üPxä0¤ÏZwÒ%° r¸óÂTîÄñƒ”Þ›æ…^
`yÐÇlþž<@çÎ ?˜ù³Ð÷ù{ÑXÐõø{ó÷’ƘƊ;”ôsÍ #ç˜ïÍù£€šL4v´h|äAȃú¬vxÊù uNãÄÏÇ‚|z‡N§ƒJ¥‚B¡Ð³éôŒt=îDÐXsgV:e|ò€‹Ö-Ð4çK®Wr¨ù<ò=Âï-MÚ‡šKû—ÖßÛÒù¤Ï“‘dxpGïǃ,[~
¹½’ÙZ¾'¹á ˜l¹cOïI€ßOüûÜ“N,V«ULLL Ýncbb›››ì}Zg´¾šÍ&Ý3U«Õ0žì·cæQ —Íf{Ö·ý2(ÈHKøÈµ@óÏí2qx`E§€™–Û.z'4=ãg!Ý[¡|ÿÓµx ÀíQ†h6›n?…aˆF£áÎhœÉàœ©šM#ûGëJs†¹! ürð’žOn|ÿs{Åm–Ð9ÀCó̓nùyG@?18p;Î×:?¾Wè̗댿”´ ‘ƒÉ2€£sN®=¾N¹
ç¶ZÎ7_WdÏhNhðuÌŸÛ4Z×Ú™F`m£ÑÀää$J¥RϼÒxq_QžÛÜwàkQ¥|HßH<ØæŸå÷åïÂW¸P’LKžp[GsÈí*OvÐ:KùùÀŸ™ß[³å|mñ¹ãþ9½¯´ùô<üLâ " ~^I›ùÂÜ?å{†@NþYº>½7}V‚=2vøÚ䶘ì8_7<>àg=†t^HÜjµzö±*iŒhÜ)¹Ã@ngxìÂ}
sð3‹ö.÷Å9ÐÇ} Š)‘ÂÇ„Ÿ·ôî|
È÷ u¯MÏC>_»š“±_ÛÜ6Ð:á~?×(–ãvD€{q>ŸoŒïÍÎξ¿¸¸ø—¹\îÖþþþ@µZ}¿Ýn¯Ÿ={6€W_}5Õl6ƒf³5›ÍT§ÓI %nß¾ý?þüÏÿü¿ÿûßO —Ë!ŸÏ#ŸÏ£X,âܹsíÙ Ù4:´¸ƒÄ퀴%ÄàsLsÆ;~?:8ã8F¡Ppío@Ð<Òº¡,8Ùoú±èé^ûûû°/Z–cqf·Ù<›'÷Ý“˜´OdöŸÛb~=q»McÈi|s;G×á` ÌÉ3–þMÁ\CÜ™hn79ØJk›“ ù/Ï)r élàAwòøºáŒ'¾ù¿%8ÌÇ“žŸŸäÈl!í?näçhOò±‘ãGNº¿rÑûÑ:áL6¹¦¸oÃÏ ÚÒz—ïHßçÉnø” 2g³h ¾o¸¯,“0üÎd2=‰~ð@H‚Œ’ÁV¹NøsðŒ¾f¹¡Ä±Áå:—ÌJâIû%™FÄdæ€ØÐЦ§§›§OŸ¾úØcýéÎÎοÕëõF§Ó ›Íæ`V‹[VÕjµ^xá…( €\éœ"Çñg¿öµ¯ý?_ÿú×G‰Y¯×E‘ËåðüóÏ» ¥—EµZuˆQ±XÄÁÁAÏ‹
8Šc&“Ááá!
…BO–™(°ä8ÒŸžžÆîînO Ntttûûû ç 5›M£R©¸¬_ årÙ}wnnëë똚šB¹\FEqÈìðð°Cl±°°€½½=ç8uŸœú\.ç6?G¤ Z:ç‡Æ¤P(`ooÙlù|Þ=ëàà Êå2†††å<Žc÷rDè`Èd2¨T*=ÔEn8òù<Êå²£ sª!6iAg2ìíí¹±¥à¶Ýn#ŸÏ÷Ç0ÝØÓû¶Z-ÔëuŒŽŽ:
uVëÙXFÃ=ÑvéÙ3™Œû<ß Ü§ÍÄ
+}®ZbxxØÑ€Ã0D©TB¡PÀàà [³ÜÐñ wxxØYîPæóyºuEþààÀ=ýfŽ°Ò¸Ñ÷ø!Ã>‡4o4?q£R©¸€‚öOµZE¡P@¥Rq%%|]U«U·¦é%ª|Ç=4øL&Ó㸺ëd2÷4®õzÝ1HèÍfÝÏ”ó5Hÿçöe–™#þ< £`X‚GN£££Ã[[[n¯çóyg#x‡~š“Äiå2””Sr"hp „æ~FsÈV®rÛAcK¥E–s (ÚKÜé$;›N§Ñh4\ÖØMœI•Ïç }qqwîÜéÉäsÒšåŒ"b¡ýæNÝKf⃠è±Ã<